Search Results

Search found 3947 results on 158 pages for 'passing'.

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

  • Passing a parameter so that it cannot be changed – C#

    - by nmarun
    I read this requirement of not allowing a user to change the value of a property passed as a parameter to a method. In C++, as far as I could recall (it’s been over 10 yrs, so I had to refresh memory), you can pass ‘const’ to a function parameter and this ensures that the parameter cannot be changed inside the scope of the function. There’s no such direct way of doing this in C#, but that does not mean it cannot be done!! Ok, so this ‘not-so-direct’ technique depends on the type of the parameter – a simple property or a collection. Parameter as a simple property: This is quite easy (and you might have guessed it already). Bulent Ozkir clearly explains how this can be done here. Parameter as a collection property: Obviously the above does not work if the parameter is a collection of some type. Let’s dig-in. Suppose I need to create a collection of type KeyTitle as defined below. 1: public class KeyTitle 2: { 3: public int Key { get; set; } 4: public string Title { get; set; } 5: } My class is declared as below: 1: public class Class1 2: { 3: public Class1() 4: { 5: MyKeyTitleList = new List<KeyTitle>(); 6: } 7: 8: public List<KeyTitle> MyKeyTitleList { get; set; } 9: public ReadOnlyCollection<KeyTitle> ReadonlyKeyTitleCollection 10: { 11: // .AsReadOnly creates a ReadOnlyCollection<> type 12: get { return MyKeyTitleList.AsReadOnly(); } 13: } 14: } See the .AsReadOnly() method used in the second property? As MSDN says it: “Returns a read-only IList<T> wrapper for the current collection.” Knowing this, I can implement my code as: 1: public static void Main() 2: { 3: Class1 class1 = new Class1(); 4: class1.MyKeyTitleList.Add(new KeyTitle { Key = 1, Title = "abc" }); 5: class1.MyKeyTitleList.Add(new KeyTitle { Key = 2, Title = "def" }); 6: class1.MyKeyTitleList.Add(new KeyTitle { Key = 3, Title = "ghi" }); 7: class1.MyKeyTitleList.Add(new KeyTitle { Key = 4, Title = "jkl" }); 8:  9: TryToModifyCollection(class1.MyKeyTitleList.AsReadOnly()); 10:  11: Console.ReadLine(); 12: } 13:  14: private static void TryToModifyCollection(ReadOnlyCollection<KeyTitle> readOnlyCollection) 15: { 16: // can only read 17: for (int i = 0; i < readOnlyCollection.Count; i++) 18: { 19: Console.WriteLine("{0} - {1}", readOnlyCollection[i].Key, readOnlyCollection[i].Title); 20: } 21: // Add() - not allowed 22: // even the indexer does not have a setter 23: } The output is as expected: The below image shows two things. In the first line, I’ve tried to access an element in my read-only collection through an indexer. It shows that the ReadOnlyCollection<> does not have a setter on the indexer. The second line tells that there’s no ‘Add()’ method for this type of collection. The capture below shows there’s no ‘Remove()’ method either, there-by eliminating all ways of modifying a collection. Mission accomplished… right? Now, even if you have a collection of different type, all you need to do is to somehow cast (used loosely) it to a List<> and then do a .AsReadOnly() to get a ReadOnlyCollection of your custom collection type. As an example, if you have an IDictionary<int, string>, you can create a List<T> of this type with a wrapper class (KeyTitle in our case). 1: public IDictionary<int, string> MyDictionary { get; set; } 2:  3: public ReadOnlyCollection<KeyTitle> ReadonlyDictionary 4: { 5: get 6: { 7: return (from item in MyDictionary 8: select new KeyTitle 9: { 10: Key = item.Key, 11: Title = item.Value, 12: }).ToList().AsReadOnly(); 13: } 14: } Cool huh? Just one thing you need to know about the .AsReadOnly() method is that the only way to modify your ReadOnlyCollection<> is to modify the original collection. So doing: 1: public static void Main() 2: { 3: Class1 class1 = new Class1(); 4: class1.MyKeyTitleList.Add(new KeyTitle { Key = 1, Title = "abc" }); 5: class1.MyKeyTitleList.Add(new KeyTitle { Key = 2, Title = "def" }); 6: class1.MyKeyTitleList.Add(new KeyTitle { Key = 3, Title = "ghi" }); 7: class1.MyKeyTitleList.Add(new KeyTitle { Key = 4, Title = "jkl" }); 8: TryToModifyCollection(class1.MyKeyTitleList.AsReadOnly()); 9:  10: Console.WriteLine(); 11:  12: class1.MyKeyTitleList.Add(new KeyTitle { Key = 5, Title = "mno" }); 13: class1.MyKeyTitleList[2] = new KeyTitle{Key = 3, Title = "GHI"}; 14: TryToModifyCollection(class1.MyKeyTitleList.AsReadOnly()); 15:  16: Console.ReadLine(); 17: } Gives me the output of: See that the second element’s Title is changed to upper-case and the fifth element also gets displayed even though we’re still looping through the same ReadOnlyCollection<KeyTitle>. Verdict: Now you know of a way to implement ‘Method(const param1)’ in your code!

    Read the article

  • Obscure SPUtility.SendMail Behavior When Manually Passing in Mail Headers

    - by Damon
    There are two ways to send mail in SharePoint: you can either use the mail components from the System.Net namespace, or you can send email using SharePoint's SPUtility.SendMail method.  One of the benefits of the SPUtility.SendMail method is that it uses the mail configuration from SharePoint, so you can manage settings in Central Administration instead of having to go through and modify your web.config file.  SPUtility.SendMail can get the job done, but it's defiantly not as developer friendly as the components from the System.Net namespace.  If you want to CC someone on an email, for example, you do NOT have a nice CC parameter - you have to manually add the CC mail header and pass it into the SPUtility.SendMail method.  I had to do this the other day, and ran into a really obscure issue. If you do NOT pass the headers into the method then SharePoint sends the email using the From Address configured in the Outgoing Mail settings in Central Admin.  If you pass headers into the method, but do not include the from header, then SharePoint sends the mail using the email address of the current user. This can be an issue if your mail server is setup to reject an email from an invalid email address or an email address that is not on your domain.  The way to fix this issue is to always pass in the from header.  If you want to use the configured From address, then you can do the following: SPWebApplication webApp = SPWebApplication.Lookup(new Uri(SPContext.Current.Site.Url)); StringDictionary headers = new StringDictionary(); headers.Add("from", webApp.OutboundMailSenderAddress);

    Read the article

  • JS closures - Passing a function to a child, how should the shared object be accessed

    - by slicedtoad
    I have a design and am wondering what the appropriate way to access variables is. I'll demonstrate with this example since I can't seem to describe it better than the title. Term is an object representing a bunch of time data (a repeating duration of time defined by a bunch of attributes) Term has some print functionality but does not implement the print functions itself, rather they are passed in as anonymous functions by the parent. This would be similar to how shaders can be passed to a renderer rather than defined by the renderer. A container (let's call it Box) has a Schedule object that can understand and use Term objects. Box creates Term objects and passes them to Schedule as required. Box also defines the print functions stored in Term. A print function usually takes an argument and uses it to return a string based on that argument and Term's internal data. Sometime the print function could also use data stored in Schedule, though. I'm calling this data shared. So, the question is, what is the best way to access this shared data. I have a lot of options since JS has closures and I'm not familiar enough to know if I should be using them or avoiding them in this case. Options: Create a local "reference" (term used lightly) to the shared data (data is not a primitive) when defining the print function by accessing the shared data through Schedule from Box. Example: var schedule = function(){ var sched = Schedule(); var t1 = Term( function(x){ // Term.print() return (x + sched.data).format(); }); }; Bind it to Term explicitly. (Pass it in Term's constructor or something). Or bind it in Sched after Box passes it. And then access it as an attribute of Term. Pass it in at the same time x is passed to the print function, (from sched). This is the most familiar way for my but it doesn't feel right given JS's closure ability. Do something weird like bind some context and arguments to print. I'm hoping the correct answer isn't purely subjective. If it is, then I guess the answer is just "do whatever works". But I feel like there are some significant differences between the approaches that could have a large impact when stretched beyond my small example.

    Read the article

  • Passing data between the VirtualBox Host and the Guest

    - by Fat Bloke
    Here's a good question: "How can you figure out the VM name from within the VM itself?" While this data is not automatically available, the general purpose, and very powerful VirtualBox "GuestProperty" APIs can be used from the host and guest to pass arbitrary data, in key/value pairs format, in and out of the guest. Note that this does require that the VirtualBox Guest Additions have been installed in the guest. To play with this, try using the "VBoxManage" command line on your VirtualBox host machine, and "VBoxControl" in the guest. Host syntax VBoxManage guestproperty get <vmname>|<uuid> <property> [--verbose] VBoxManage guestproperty set <vmname>|<uuid> <property> [<value> [--flags <flags>]] VBoxManage guestproperty enumerate <vmname>|<uuid> [--patterns <patterns>] VBoxManage guestproperty wait <vmname>|<uuid> <patterns> [--timeout <msec>] [--fail-on-timeout]   Guest syntax VBoxControl.exe guestproperty        get <property> [-verbose] VBoxControl.exe guestproperty        set <property> [<value> [-flags <flags>]] VBoxControl.exe guestproperty        enumerate [-patterns <patterns>] VBoxControl.exe guestproperty        wait <patterns>                                      [-timestamp <last timestamp>]                                      [-timeout <timeout in ms>  So to solve our problem above, we set the vm name in the Host system on an arbitrary key like this: $ VBoxManage guestproperty set "Windows 7 (x64)" /MyData/VMname "Windows 7 (x64)" And within the guest we can use: C:\Program Files\Oracle\VirtualBox Guest Additions>VBoxControl.exe guestproperty get /MyData/VMname Oracle VM VirtualBox Guest Additions Command Line Management Interface Version 4.1.14 (C) 2008-2012 Oracle Corporation All rights reserved. Value: Windows 7 (x64) The GuestProperty API is pretty powerful, so for the interested, get more info in the User Manual. - FB 

    Read the article

  • Passing an objects rotation down through its children

    - by MintyAnt
    In my topdown 2d game you have a player with a sword, like an old Zelda game. The sword is a seperate entity, and its collision box "rotates" around the player like an orbit, but always follows the player wherever he goes. The player and sword both have a vector2 heading. The sword is a weapon object that is attached to the character. In order to allow swinging in a direction, I have the following property inside sword (RotateCopy returns a copy of the mHeading after rotation) public Vector2 Heading { get { return mHeading.RotateCopy(mOwner.Rotation); } } This seems a bit messy to me, and slower than it could be. Is there a better way to "translate" the base/owner component rotations through to whatever component I am using, like this sword? Would using a rotation MATRIX be better? (Curretnly rotates by sin/cos) If so, how can I "add" up the matrices? Thank you.

    Read the article

  • Passing variables from PHP to C++

    - by Alex
    I’m new to this so I’m sorry if my question is trivial. I have the following situation: I need to call a program from PHP and pass some vars and/or sets of key-value pairs to it. Now, my question is: how do I pass these vars, through arguments to the called function (e.g. exec("/path/to/program flag1 flag2 [key1=A,key2=B]");)? Or is there a better method to achieve this? Somebody suggested me to write them into a txt file and pass the path to it to as an argument instead (e.g. exec("/path/to/program path_to_txt_file);), but I’m not to excited about this method.

    Read the article

  • Passing variable from SharePoint to external website

    - by TechDaddyK
    My company has a SharePoint site that is administered by the IT department (versus the Web Developer... go figure!). We have partnered with a vendor that has built a site for our staff to order customized stationery, etc. I need to create a link on the SharePoint site that will take the user to the external site but identify them individually. The vendor is suggesting this format: https://www.VENDORSITE.com/UI/Profile.hcf?id=a02b8106-4115-47cd-bca7-ce4dd447ef89&username=<user name>&password=<password>&name1=<first name>&name2=<last name>&email=<email> Here's the problem: I don't know how to pass that info, or even a single variable, from the SharePoint site to the external site. I would appreciate ANY suggestions.

    Read the article

  • Syntax of passing lambda causing hair loss (pulling out)

    - by Astara
    Right now, I'm working on refactoring a program that calls its parts by polling to a more event-driven structure. I've created sched and task classes with the sced to become a base class of the current main loop. The tasks will be created for each meter so they can be called off of that instead of polling. Each of the events main calls are a type of meter that gather info and display it. When the program is coming up, all enabled meters get 'constructed' by a main-sub. In that sub, I want to store off the "this" pointer associated with the meter, as well as the common name for the "action routine. void MeterMaker::Meter_n_Task (Meter * newmeter,) { push(newmeter); // handle non-timed draw events Task t = new Task(now() + 0.5L); t.period={0,1U}; t.work_meter = newmeter; t.work = [&newmeter](){newmeter.checkevent();};<<--attempt at lambda t.flags = T_Repeat; t.enable_task(); _xos->sched_insert(t); } A sample call to it: Meter_n_Task(new CPUMeter(_xos, "CPU ")); 've made the scheduler a base class of the main routine (that handles the loop), and I've tried serveral variations to get the task class to be a base of the meter class, but keep running into roadblocks. It's alot like "whack-a-mole" -- pound in something to fix something one place, and then a new probl pops out elsewhere. Part of the problem, is that the sched.h file that is trying to hold the Task Q, includes the Task header file. The task file Wants to refer to the most "base", Meter class. The meter class pulls in the main class of the parent as it passes a copy of the parent to the children so they can access the draw routines in the parent. Two references in the task file are for the 'this' pointer of the meter and the meter's update sub (to be called via this). void *this_data= NULL; void (*this_func)() = NULL; Note -- I didn't really want to store these in the class, as I wanted to use a lamdba in that meter&task routine above to store a routine+context to be used to call the meter's action routine. Couldn't figure out the syntax. But am running into other syntax problems trying to store the pointers...such as g++: COMPILE lsched.cc In file included from meter.h:13:0, from ltask.h:17, from lsched.h:13, from lsched.cc:13: xosview.h:30:47: error: expected class-name before ‘{’ token class XOSView : public XWin, public Scheduler { Like above where it asks for a class, where the classname "Scheduler" is. !?!? Huh? That IS a class name. I keep going in circles with things that don't make sense... Ideally I'd get the lamba to work right in the Meter_n_Task routine at the top. I wanted to only store 1 pointer in the 'Task' class that was a pointer to my lambda that would have already captured the "this" value ... but couldn't get that syntax to work at all when I tried to start it into a var in the 'Task' class. This project, FWIW, is my teething project on the new C++... (of course it's simple!.. ;-))... I've made quite a bit of progress in other areas in the code, but this lambda syntax has me stumped...its at times like thse that I appreciate the ease of this type of operation in perl. Sigh. Not sure the best way to ask for help here, as this isn't a simple question. But thought I'd try!... ;-) Too bad I can't attach files to this Q.

    Read the article

  • Passing class names or objects?

    - by nischayn22
    I have a switch statement switch ( $id ) { case 'abc': return 'Animal'; case 'xyz': return 'Human'; //many more } I am returning class names,and use them to call some of their static functions using call_user_func(). Instead I can also create a object of that class, return that and then call the static function from that object as $object::method($param) switch ( $id ) { case 'abc': return new Animal; case 'xyz': return new Human; //many more } Which way is efficient? To make this question broader : I have classes that have mostly all static methods right now, putting them into classes is kind of a grouping idea here (for example the DB table structure of Animal is given by class Animal and so for Human class). I need to access many functions from these classes so the switch needs to give me access to the class

    Read the article

  • Page Navigation and Passing, Sharing and Retaining Data in Windows Phone 7

    Page navigation would seem to be an advanced Silverlight programming topic, and a topic that applies only to Silverlight programming rather than XNA programming. However, there are issues involved with navigation that are related to the very important topic of tombstoning, which is what happens to your Windows Phone 7 application when the user navigates to another application through the phone’s Start screen.

    Read the article

  • Passing an ActionScript JPG Byte Array to Javscript (and eventually to PHP)

    - by Gus
    Our web application has a feature which uses Flash (AS3) to take photos using the user's web cam, then passes the resulting byte array to PHP where it is reconstructed and saved on the server. However, we need to be able to take this web application offline, and we have chosen Gears to do so. The user takes the app offline, performs his tasks, then when he's reconnected to the server, we "sync" the data back with our central database. We don't have PHP to interact with Flash anymore, but we still need to allow users to take and save photos. We don't know how to save a JPG that Flash creates in a local database. Our hope was that we could save the byte array, a serialized string, or somehow actually persist the object itself, then pass it back to either PHP or Flash (and then PHP) to recreate the JPG. We have tried: - passing the byte array to Javascript instead of PHP, but javascript doesn't seem to be able to do anything with it (the object seems to be stripped of its methods) - stringifying the byte array in Flash, and then passing it to Javascript, but we always get the same string: ÿØÿà Now we are thinking of serializing the string in Flash, passing it to Javascript, then on the return route, passing that string back to Flash which will then pass it to PHP to be reconstructed as a JPG. (whew). Since no one on our team has extensive Flash background, we're a bit lost. Is serialization the way to go? Is there a more realistic way to do this? Does anyone have any experience with this sort of thing? Perhaps we can build a javascript class that is the same as the byte array class in AS?

    Read the article

  • PHP Sessions and Passing Session ID

    - by Jason McCreary
    I have an API where I am passing the session id back and forth between calls. I set up the session like so: // start API session session_name('apikey'); session_id($data['apikey']); // required to link session session_start(); Although I named my session and am passing the session id via GET and POST using the name, PHP does not automatically resume that session. It always creates a new one unless I set the explicitly set the session id. I found some old user comments on www.php.net that said unless the session id is the first parameter PHP won't set it automatically. This seems odd, but even when I call tried it still didn't work: rest_services.php?apikey=sdr6d3subaofcav53cpf71j4v3&q=testing I have used PHP for years, but am a little confused on why I needed to explicitly set the session with session_id() when I am naming the session and passing it's key accordingly. UPDATE It seems I wasn't clear. My question is why is setting the session ID with session_id() required when I am passing the id, using the session name apikey, via $_GET or $_POST. Theoretically this is no different than PHP's SID when cookies are disabled. But for me it doesn't work unless I explicitly set the session ID. Why?

    Read the article

  • HP Procurve Issue Passing Multiple VLANs over a link

    - by MichaelRwat
    Just to start off with I am a Cisco guy that got placed into an HP project. Basic topology overview from outside in: ASA 5505 with two Ethernet connections to a 2910-24 port switch. This switch is then (Cisco Trunking) to a 2626 switch passing vlan (1 untagged and 100 tagged)between them. I created SVI's on each of the switches for both VLAN's for testing purposes. I can not get vlan 100 to pass across this link. I also have trunks configured to AP's off of the switch and can not ping the vlan 100 BVI on the AP's but can reach the vlan 1 BVI. Port 25 on Access layer (2626) connects (trunks) with port A1 of 2610. STP is not running at all on any switch (this is not my network I can't change this nor did I design this) Distribution Sw: MP1-0# show run ip default-gateway 10.100.100.100 vlan 1 name "DATA" untagged 1-22,24-A1,B1 ip address 10.100.100.6 255.255.255.0 no untagged 23 exit vlan 100 name "GUEST" untagged 23 tagged 24-A1 ip address 10.100.102.6 255.255.255.0 exit Access Sw: ip default-gateway 10.100.100.100 vlan 1 name "DEFAULT_VLAN" untagged 1-26 ip address 10.100.100.5 255.255.255.0 exit vlan 100 name "GUEST" ip address 10.100.102.5 255.255.255.0 tagged 15,25 exitt From the ASA I can ping the vlan 100 address of the 2610 but not the 2626 (10.100.102.6)[Not passing the "trunk"] If I plug into an access port vlan 100 of the 2626 I can ping the SVI for vlan 100 as intended. I can not ping across the "trunk" over vlan 100 but I can across vlan 1. There may be something obvious I'm missing but please review my configuration and thank you for the assistance.

    Read the article

  • Passing IP address with mod_proxy

    - by Konrad Garus
    I have Apache with mod_proxy passing requests to Tomcat. The trouble is, when I get client IP address associated with a request in web app hosted on Tomcat, it always returns 127.0.0.1. Is it possible to have Apache pass the original IP address to Tomcat?

    Read the article

  • Using a function with reference as a function with pointers?

    - by epatel
    Today I stumbled over a piece of code that looked horrifying to me. The pieces was chattered in different files, I have tried write the gist of it in a simple test case below. The code base is routinely scanned with FlexeLint on a daily basis, but this construct has been laying in the code since 2004. The thing is that a function implemented with a parameter passing using references is called as a function with a parameter passing using pointers...due to a function cast. The construct has worked since 2004 on Irix and now when porting it actually do work on Linux/gcc too. My question now. Is this a construct one can trust? I can understand if compiler constructors implement the reference passing as it was a pointer, but is it reliable? Are there hidden risks? Should I change the fref(..) to use pointers and risk braking anything in the process? What to you think? #include <iostream> using namespace std; // ---------------------------------------- // This will be passed as a reference in fref(..) struct string_struct { char str[256]; }; // ---------------------------------------- // Using pointer here! void fptr(const char *str) { cout << "fptr: " << str << endl; } // ---------------------------------------- // Using reference here! void fref(string_struct &str) { cout << "fref: " << str.str << endl; } // ---------------------------------------- // Cast to f(const char*) and call with pointer void ftest(void (*fin)()) { void (*fcall)(const char*) = (void(*)(const char*))fin; fcall("Hello!"); } // ---------------------------------------- // Let's go for a test int main() { ftest((void (*)())fptr); // test with fptr that's using pointer ftest((void (*)())fref); // test with fref that's using reference return 0; }

    Read the article

  • When parsing XML with jquery, how can we pass the current node from within each() to another functio

    - by Johusa
    Say we have an XML document with many book nodes... When parsing XML with jquery, how can i pass the current node from each() iteration to another function that will do some stuff until something is reached and then go back to the previous function (passing along the current node from this function back to the first function)? Here something more descriptive (this is just an example out of my head, not accurate): function MyParser(x1,x2,dom) { // if i am called by anotherFunction(thisNode) proceed from the passed node dom.find('book').each(function() { var Letter = thisNode.find(author).charAt(0); if(x1 == Letter) { // print everything till the next letter (x2) anotherFunction(thisNode) } } } function anotherFunction(x2,thisNode) { //continue parsing here until you reached x2 //when x2 is reached, return to previous function passing again the current node }

    Read the article

  • WP Oembed not passing through the “autoplay=1” variable

    - by criticerz
    Hi guys, I'm having a problem here.. I am passing this through a custom field: http://www.youtube.com/watch?v=E6P1Q-UycHA&autoplay=1 (notice the "autoplay=1") But when I load the video on my theme using wp_oembed_get... it displays the video fine, but it does not listen to the "autoplay=1" variable I am passing through. I need the videos to play on the load of the page. Any ideas? Thanks, Alain Fontaine

    Read the article

  • C++ How fast is passing around objects?

    - by wndsr
    Assuming we are running a compiled C++ binary: Is passing around an int (e.g. function to function, or writing it into variables) slower than passing around structs/class objects like the following? class myClass { int a; int b; char c; vector d; string e; }

    Read the article

  • non-privileged normal user passing environment variables to /bin/login [closed]

    - by AAAAAAAA
    Suppose that in FreeBSD (or linux maybe) there is a non-privileged normal user (non-superuser). And there is a telnet standalone (I know that telnet is usually run under inetd) running under (owned by) this user. (Suppose that there was no original, root-owned telnet running.) This telnet server is programmed so that it does not check ld_* environment variables before passing it to /bin/login owned by root that has setuid set up. The question would be: 1. Will this telnet work? 2. If it does work, will it even be able to pass environment variables to /bin/login?

    Read the article

  • Passing the output of the last command to sed as an argument

    - by neurolysis
    Hi, Basically, I'm wanting to automate adding something to xorg.conf in the right place, I've used some commands to get the line number of the line I want to manipulate, but I'm not really sure how to go about passing this line number (as an argument and NOT something to be manipulated) to sed. I have been told about xargs and looked at the docs on it, but after some reading and experimentation I can't seem to get it to work. In case anyone can think of a better method entirely, the process I want to automate is just finding the line containing both "Identifier" and "Monitor0" (there will only be one) and adding a line below it. The problem with just finding Monitor0 and manipulating that line is that there are multiple lines with Monitor0 in. I've got this far: fgrep -n "Monitor0" </etc/X11/xorg.conf | fgrep "Identifier" | cut -f1 -d: This gives out the line number which I'm wanting to pass to sed, but I'm not really sure how to do it. ...or is there a simpler way which I'm not seeing? Thanks. :)

    Read the article

  • The cost of passing by shared_ptr

    - by Artem
    I use std::tr1::shared_ptr extensively throughout my application. This includes passing objects in as function arguments. Consider the following: class Dataset {...} void f( shared_ptr< Dataset const > pds ) {...} void g( shared_ptr< Dataset const > pds ) {...} ... While passing a dataset object around via shared_ptr guarantees its existence inside f and g, the functions may be called millions of times, which causes a lot of shared_ptr objects being created and destroyed. Here's a snippet of the flat gprof profile from a recent run: Each sample counts as 0.01 seconds. % cumulative self self total time seconds seconds calls s/call s/call name 9.74 295.39 35.12 2451177304 0.00 0.00 std::tr1::__shared_count::__shared_count(std::tr1::__shared_count const&) 8.03 324.34 28.95 2451252116 0.00 0.00 std::tr1::__shared_count::~__shared_count() So, ~17% of the runtime was spent on reference counting with shared_ptr objects. Is this normal? A large portion of my application is single-threaded and I was thinking about re-writing some of the functions as void f( const Dataset& ds ) {...} and replacing the calls shared_ptr< Dataset > pds( new Dataset(...) ); f( pds ); with f( *pds ); in places where I know for sure the object will not get destroyed while the flow of the program is inside f(). But before I run off to change a bunch of function signatures / calls, I wanted to know what the typical performance hit of passing by shared_ptr was. Seems like shared_ptr should not be used for functions that get called very often. Any input would be appreciated. Thanks for reading. -Artem

    Read the article

  • Understanding OOP Principles in passing around objects/values

    - by Hans
    I'm not quite grokking a couple of things in OOP and I'm going to use a fictional understanding of SO to see if I can get help understand. So, on this page we have a question. You can comment on the question. There are also answers. You can comment on the answers. Question - comment - comment - comment Answer -comment Answer -comment -comment -comment Answer -comment -comment So, I'm imagining a very high level understanding of this type of system (in PHP, not .Net as I am not yet familiar with .Net) would be like: $question = new Question; $question->load($this_question_id); // from the URL probably echo $question->getTitle(); To load the answers, I imagine it's something like this ("A"): $answers = new Answers; $answers->loadFromQuestion($question->getID()); // or $answers->loadFromQuestion($this_question_id); while($answer = $answers->getAnswer()) { echo $answer->showFormatted(); } Or, would you do ("B"): $answers->setQuestion($question); // inject the whole obj, so we have access to all the data and public methods in $question $answers->loadFromQuestion(); // the ID would be found via $this->question->getID() instead of from the argument passed in while($answer = $answers->getAnswer()) { echo $answer->showFormatted(); } I guess my problem is, I don't know when or if I should be passing in an entire object, and when I should just be passing in a value. Passing in the entire object gives me a lot of flexibility, but it's more memory and subject to change, I'd guess (like a property or method rename). If "A" style is better, why not just use a function? OOP seems pointless here. Thanks, Hans

    Read the article

  • How can multiple variables be passed to a function cleanly in C?

    - by aquanar
    I am working on an embedded system that has different output capabilities (digital out, serial, analog, etc). I am trying to figure out a clean way to pass many of the variables that will control those functions. I don't need to pass ALL of them too often, but I was hoping to have a function that would read the input data (in this case from a TCP network), and then parse the data (IE, the 3rd byte contains the states of 8 of the digital outputs (according to which bit in that byte is high or low)), and put that into a variable where I can then use elsewhere in the program. I wanted that function to be separate from the main() function, but to do so would require passing pointers to some 20 or so variables that it would be writing to. I know I could make the variables global, but I am trying to make it easier to debug by making it obvious when a function is allowed to edit that variable, by passing it to the function. My best idea was a struct, and just pass a pointer to it, but wasn't sure if there was a more efficient way, especially since there is only really 1 function that would need to access all of them at once, while most others only require parts of the information that will be stored in this bunch of state variables. So anyway, is there a clean way to send many variables between functions at once that need to be edited?

    Read the article

  • jquery dialog calls a server side method with button parameters

    - by Chiefy
    Hello all, I have a gridview control with delete asp:ImageButton for each row of the grid. What I would like is for a jquery dialog to pop up when a user clicks the delete button to ask if they are sure they want to delete it. So far I have the dialog coming up just fine, Ive got buttons on that dialog and I can make the buttons call server side methods but its getting the dialog to know the ID of the row that the user has selected and then passing that to the server side code. The button in the page row is currently just an 'a' tag with the id 'dialog_link'. The jquery on the page looks like this: $("button").button(); $("#DeleteButton").click(function () { $.ajax({ type: "POST", url: "ManageUsers.aspx/DeleteUser", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { // Replace the div's content with the page method's return. $("#DeleteButton").text(msg.d); } }); }); // Dialog $('#dialog').dialog({ autoOpen: false, width: 400, modal: true, bgiframe: true }); // Dialog Link $('#dialog_link').click(function () { $('#dialog').dialog('open'); return false; }); The dialog itself is just a set of 'div' tags. Ive thought of lots of different ways of doing this (parameter passing, session variable etc...) but cant figure out how to get any of them working. Any ideas are most welcome As always, thanks in advance to those who contribute.

    Read the article

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