Search Results

Search found 9134 results on 366 pages for 'variadic functions'.

Page 11/366 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • Does query plan optimizer works well with joined/filtered table-valued functions?

    - by smoothdeveloper
    In SQLSERVER 2005, I'm using table-valued function as a convenient way to perform arbitrary aggregation on subset data from large table (passing date range or such parameters). I'm using theses inside larger queries as joined computations and I'm wondering if the query plan optimizer work well with them in every condition or if I'm better to unnest such computation in my larger queries. Does query plan optimizer unnest table-valued functions if it make sense? If it doesn't, what do you recommend to avoid code duplication that would occur by manually unnesting them? If it does, how do you identify that from the execution plan? code sample: create table dbo.customers ( [key] uniqueidentifier , constraint pk_dbo_customers primary key ([key]) ) go /* assume large amount of data */ create table dbo.point_of_sales ( [key] uniqueidentifier , customer_key uniqueidentifier , constraint pk_dbo_point_of_sales primary key ([key]) ) go create table dbo.product_ranges ( [key] uniqueidentifier , constraint pk_dbo_product_ranges primary key ([key]) ) go create table dbo.products ( [key] uniqueidentifier , product_range_key uniqueidentifier , release_date datetime , constraint pk_dbo_products primary key ([key]) , constraint fk_dbo_products_product_range_key foreign key (product_range_key) references dbo.product_ranges ([key]) ) go . /* assume large amount of data */ create table dbo.sales_history ( [key] uniqueidentifier , product_key uniqueidentifier , point_of_sale_key uniqueidentifier , accounting_date datetime , amount money , quantity int , constraint pk_dbo_sales_history primary key ([key]) , constraint fk_dbo_sales_history_product_key foreign key (product_key) references dbo.products ([key]) , constraint fk_dbo_sales_history_point_of_sale_key foreign key (point_of_sale_key) references dbo.point_of_sales ([key]) ) go create function dbo.f_sales_history_..snip.._date_range ( @accountingdatelowerbound datetime, @accountingdateupperbound datetime ) returns table as return ( select pos.customer_key , sh.product_key , sum(sh.amount) amount , sum(sh.quantity) quantity from dbo.point_of_sales pos inner join dbo.sales_history sh on sh.point_of_sale_key = pos.[key] where sh.accounting_date between @accountingdatelowerbound and @accountingdateupperbound group by pos.customer_key , sh.product_key ) go -- TODO: insert some data -- this is a table containing a selection of product ranges declare @selectedproductranges table([key] uniqueidentifier) -- this is a table containing a selection of customers declare @selectedcustomers table([key] uniqueidentifier) declare @low datetime , @up datetime -- TODO: set top query parameters . select saleshistory.customer_key , saleshistory.product_key , saleshistory.amount , saleshistory.quantity from dbo.products p inner join @selectedproductranges productrangeselection on p.product_range_key = productrangeselection.[key] inner join @selectedcustomers customerselection on 1 = 1 inner join dbo.f_sales_history_..snip.._date_range(@low, @up) saleshistory on saleshistory.product_key = p.[key] and saleshistory.customer_key = customerselection.[key] I hope the sample makes sense. Much thanks for your help!

    Read the article

  • Implement two functions with the same name but different, non-covariant return types due to multiple abstract base classes

    - by user1508167
    If I have two abstract classes defining a pure virtual function with the same name, but different, non-covariant return types, how can I derive from these and define an implementation for both their functions? #include <iostream> class ITestA { public: virtual ~ITestA() {}; virtual float test() =0; }; class ITestB { public: virtual ~ITestB() {}; virtual bool test() =0; }; class C : public ITestA, public ITestB { public: /* Somehow implement ITestA::test and ITestB::test */ }; int main() { ITestA *a = new C(); std::cout << a->test() << std::endl; // should print a float, like "3.14" ITestB *b = dynamic_cast<ITestB *>(a); if (b) { std::cout << b->test() << std::endl; // should print "1" or "0" } delete(a); return 0; } As long as I don't call C::test() directly there's nothing ambiguous, so I think that it should work somehow and I guess I just didn't find the right notation yet. Or is this impossible, if so: Why?

    Read the article

  • What triggered the popularity of lambda functions in modern mainstream programming languages?

    - by Giorgio
    In the last few years anonymous functions (AKA lambda functions) have become a very popular language construct and almost every major / mainstream programming language has introduced them or is planned to introduce them in an upcoming revision of the standard. Yet, anonymous functions are a very old and very well-known concept in Mathematics and Computer Science (invented by the mathematician Alonzo Church around 1936, and used by the Lisp programming language since 1958, see e.g. here). So why didn't today's mainstream programming languages (many of which originated 15 to 20 years ago) support lambda functions from the very beginning and only introduced them later? And what triggered the massive adoption of anonymous functions in the last few years? Is there some specific event, new requirement or programming technique that started this phenomenon? IMPORTANT NOTE The focus of this question is the introduction of anonymous functions in modern, main-stream (and therefore, maybe with a few exceptions, non functional) languages. Also, note that anonymous functions (blocks) are present in Smalltalk, which is not a functional language, and that normal named functions have been present even in procedural languages like C and Pascal for a long time. Please do not overgeneralize your answers by speaking about "the adoption of the functional paradigm and its benefits", because this is not the topic of the question.

    Read the article

  • F#: Advantages of converting top-level functions to member methods?

    - by J Cooper
    Earlier I requested some feedback on my first F# project. Before closing the question because the scope was too large, someone was kind enough to look it over and leave some feedback. One of the things they mentioned was pointing out that I had a number of regular functions that could be converted to be methods on my datatypes. Dutifully I went through changing things like let getDecisions hand = let (/=/) card1 card2 = matchValue card1 = matchValue card2 let canSplit() = let isPair() = match hand.Cards with | card1 :: card2 :: [] when card1 /=/ card2 -> true | _ -> false not (hasState Splitting hand) && isPair() let decisions = [Hit; Stand] let split = if canSplit() then [Split] else [] let doubleDown = if hasState Initial hand then [DoubleDown] else [] decisions @ split @ doubleDown to this: type Hand // ...stuff... member hand.GetDecisions = let (/=/) (c1 : Card) (c2 : Card) = c1.MatchValue = c2.MatchValue let canSplit() = let isPair() = match hand.Cards with | card1 :: card2 :: [] when card1 /=/ card2 -> true | _ -> false not (hand.HasState Splitting) && isPair() let decisions = [Hit; Stand] let split = if canSplit() then [Split] else [] let doubleDown = if hand.HasState Initial then [DoubleDown] else [] decisions @ split @ doubleDown Now, I don't doubt I'm an idiot, but other than (I'm guessing) making C# interop easier, what did that gain me? Specifically, I found a couple *dis*advantages, not counting the extra work of conversion (which I won't count, since I could have done it this way in the first place, I suppose, although that would have made using F# Interactive more of a pain). For one thing, I'm now no longer able to work with function "pipelining" easily. I had to go and change some |> chained |> calls to (some |> chained).Calls etc. Also, it seemed to make my type system dumber--whereas with my original version, my program needed no type annotations, after converting largely to member methods, I got a bunch of errors about lookups being indeterminate at that point, and I had to go and add type annotations (an example of this is in the (/=/) above). I hope I haven't come off too dubious, as I appreciate the advice I received, and writing idiomatic code is important to me. I'm just curious why the idiom is the way it is :) Thanks!

    Read the article

  • Is it possible to view the "source" for a ksh function?

    - by stevec
    Our ksh environment defines several functions, which can be listed using then "functions" ksh function. Is it possible to see the definition (ie source code) for these functions? This seems like an obvious question, but I've tried all manner of parameters to the "functions" and "function" functions with no luck. Thanks, Steve

    Read the article

  • T-SQL Tuesday #24 : Dude, where's the rest of my procedure?

    - by AaronBertrand
    This month's T-SQL Tuesday is being hosted by Brad Schulz ( blog ) and the topic is one that should attract a lot of submissions: Procedures and Functions. Last week, I talked about the case against INFORMATION_SCHEMA views - I provided several examples where I feel the INFORMATION_SCHEMA views fall short of the catalog views, and expressed my belief that you are better off programming consistently against the catalog views all the time, instead of only when the INFORMATION_SCHEMA views fail. Having...(read more)

    Read the article

  • Looking for terminology for the relation of a subject and a predicate

    - by kostja
    While writing some predicates for collection filtering I have stumbled over the choice of the right words for the relation of the subject and the predicate (English is a foreign language for me). What I ended up writing was "Subjects matching this predicate..." This seems to be incorrect, since predicates are functions and not regular expressions. But saying "Subjects for which this predicate returns true..." sounds awkward to me as well.. So what would be the correct term?

    Read the article

  • I'm new to C++. Please Help me with the Linked List (What functions to add)?

    - by Igal
    DEAR All; Hi, I'm just beginner to C++; Please help me to understand: What functions should be in the Linked list class ? I think there should be overloaded operators << and ; Please help me to improve the code (style, errors, etc,) Thanks for advance. Igal. Please review the small code for the integer List (enclosed MyNODE.h and ListDriver1.cpp); MyNODE.h // This is my first attempt to write linked list. Igal Spector, June 2010. #include <iostream.h> #include <assert.h> //Forward Declaration of the classes: class ListNode; class TheLinkedlist; // Definition of the node (WITH IMPLEMENTATION !!!, without test drive): class ListNode{ friend class TheLinkedlist; public: // constructor: ListNode(const int& value, ListNode *next= 0); // note: no destructor, as this handled by TheLinkedList class. // accessor: return data in the node. // int Show() const {return theData;} private: int theData; //the Data ListNode* theNext; //points to the next node in the list. }; //Implementations: //constructor: inline ListNode::ListNode(const int &value,ListNode *next) :theData(value),theNext(next){} //end of ListNode class, now for the LL class: class TheLinkedlist { public: //constructors: TheLinkedlist(); virtual ~TheLinkedlist(); // Accessors: void InsertAtFront(const &); void AppendAtBack(const &); // void InOrderInsert(const &); bool IsEmpty()const;//predicate function void Print() const; private: ListNode * Head; //pointer to first node ListNode * Tail; //pointer to last node. }; //Implementation: //Default constructor inline TheLinkedlist::TheLinkedlist():Head(0),Tail(0) {} //Destructor inline TheLinkedlist::~TheLinkedlist(){ if(!IsEmpty()){ //list is not empty cout<<"\n\tDestroying Nodes"<<endl; ListNode *currentPointer=Head, *tempPtr; while(currentPointer != 0){ //Delete remaining Nodes. tempPtr=currentPointer; cout<<"The node: "<<tempPtr->theData <<" is Destroyed."<<endl<<endl; currentPointer=currentPointer->theNext; delete tempPtr; } Head=Tail = 0; //don't forget this, as it may be checked one day. } } //Insert the Node to the beginning of the list: void TheLinkedlist::InsertAtFront(const int& value){ ListNode *newPtr = new ListNode(value,Head); assert(newPtr!=0); if(IsEmpty()) //list is empty Head = Tail = newPtr; else { //list is NOT empty newPtr->theNext = Head; Head = newPtr; } } //Insert the Node to the beginning of the list: void TheLinkedlist::AppendAtBack(const int& value){ ListNode *newPtr = new ListNode(value, NULL); assert(newPtr!=0); if(IsEmpty()) //list is empty Head = Tail = newPtr; else { //list is NOT empty Tail->theNext = newPtr; Tail = newPtr; } } //is the list empty? inline bool TheLinkedlist::IsEmpty() const { return (Head == 0); } // Display the contents of the list void TheLinkedlist::Print()const{ if ( IsEmpty() ){ cout << "\n\t The list is empty!!"<<endl; return; } ListNode *tempPTR = Head; cout<<"\n\t The List is: "; while ( tempPTR != 0 ){ cout<< tempPTR->theData <<" "; tempPTR = tempPTR->theNext; } cout<<endl<<endl; } ////////////////////////////////////// The test Driver: //Driver test for integer Linked List. #include <iostream.h> #include "MyNODE.h" // main Driver int main(){ cout<< "\n\t This is the test for integer LinkedList."<<endl; const int arraySize=11, ARRAY[arraySize]={44,77,88,99,11,2,22,204,50,58,12}; cout << "\n\tThe array is: "; //print the numbers. for (int i=0;i<arraySize; i++) cout<<ARRAY[i]<<", "; TheLinkedlist list; //declare the list for(int index=0;index<arraySize;index++) list.AppendAtBack( ARRAY[index] );//create the list cout<<endl<<endl; list.Print(); //print the list return 0; //end of the program. }

    Read the article

  • Port to use CentOS init.d functions

    - by jcalfee314
    What are good equivalent centos commands using functions in /etc/init.d/functions such as daemon to perform the following tasks? STARTCMD='start-stop-daemon --start --exec /usr/sbin/swapspace --quiet --pidfile /var/run/swapspace.pid -- -d -p' STOPCMD='start-stop-daemon --stop --oknodo --quiet --pidfile /var/run/swapspace.pid' It looks like daemon will work for the start command and killproc is used for the stop command. . /etc/init.d/functions pushd /usr/sbin daemon --pidfile /var/run/swapspace.pid /usr/sbin/swapspace . /etc/init.d/functions killproc -p $(cat /var/run/swapspace.pid) Would the --oknodo be needed in the CentOS env (the swap file is really only boot-time)? "oknodo - Return exit status 0 instead of 1 if no actions are (would be) taken." I don't see quiet in daemon or killproc, I can't imagine that it would matter though. The original start-stop-daemon for swapspace seems to have both -p and --pidfile (the same command). That must be an error. Did I miss anything? Any idea why daemon not create the pid file?

    Read the article

  • SQL SERVER – Introduction to PERCENTILE_CONT() – Analytic Functions Introduced in SQL Server 2012

    - by pinaldave
    SQL Server 2012 introduces new analytical function PERCENTILE_CONT(). The book online gives following definition of this function: Computes a specific percentile for sorted values in an entire rowset or within distinct partitions of a rowset in Microsoft SQL Server 2012 Release Candidate 0 (RC 0). For a given percentile value P, PERCENTILE_DISC sorts the values of the expression in the ORDER BY clause and returns the value with the smallest CUME_DIST value (with respect to the same sort specification) that is greater than or equal to P. If you are clear with understanding of the function – no need to read further. If you got lost here is the same in simple words – it is lot like finding median with percentile value. Now let’s have fun following query: USE AdventureWorks GO SELECT SalesOrderID, OrderQty, ProductID, PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY ProductID) OVER (PARTITION BY SalesOrderID) AS MedianCont FROM Sales.SalesOrderDetail WHERE SalesOrderID IN (43670, 43669, 43667, 43663) ORDER BY SalesOrderID DESC GO The above query will give us the following result: You can see that I have used PERCENTILE_COUNT(0.5) in query, which is similar to finding median. Let me explain above diagram with little more explanation. The defination of median is as following: In case of Even Number of elements = In ordered list add the two digits from the middle and devide by 2 In case of Odd Numbers of elements = In ordered list select the digits from the middle I hope this example gives clear idea how PERCENTILE_CONT() works. Reference: Pinal Dave (http://blog.SQLAuthority.com) Filed under: Pinal Dave, PostADay, SQL, SQL Authority, SQL Function, SQL Query, SQL Scripts, SQL Server, SQL Tips and Tricks, T SQL, Technology

    Read the article

  • System Variables, Stored Procedures or Functions for Meta Data

    - by BuckWoody
    Whenever you want to know something about SQL Server’s configuration, whether that’s the Instance itself or a database, you have a few options. If you want to know “dynamic” data, such as how much memory or CPU is consumed or what a particular query is doing, you should be using the Dynamic Management Views (DMVs) that you can read about here: http://msdn.microsoft.com/en-us/library/ms188754.aspx  But if you’re looking for how much memory is installed on the server, the version of the Instance, the drive letters of the backups and so on, you have other choices. The first of these are system variables. You access these with a SELECT statement, and they are useful when you need a discrete value for use, say in another query or to put into a table. You can read more about those here: http://msdn.microsoft.com/en-us/library/ms173823.aspx You also have a few stored procedures you can use. These often bring back a lot more data, pre-formatted for the screen. You access these with the EXECUTE syntax. It is a bit more difficult to take the data they return and get a single value or place the results in another table, but it is possible. You can read more about those here: http://msdn.microsoft.com/en-us/library/ms187961.aspx Yet another option is to use a system function, which you access with a SELECT statement, which also brings back a discrete value that you can use in a test or to place in another table. You can read about those here: http://msdn.microsoft.com/en-us/library/ms187812.aspx  By the way, many of these constructs simply query from tables in the master or msdb databases for the Instance or the system tables in a user database. You can get much of the information there as well, and there are even system views in each database to show you the meta-data dealing with structure – more on that here: http://msdn.microsoft.com/en-us/library/ms186778.aspx  Some of these choices are the only way to get at a certain piece of data. But others overlap – you can use one or the other, they both come back with the same data. So, like many Microsoft products, you have multiple ways to do the same thing. And that’s OK – just research what each is used for and how it’s intended to be used, and you’ll be able to select (pun intended) the right choice. Share this post: email it! | bookmark it! | digg it! | reddit! | kick it! | live it!

    Read the article

  • Gathering all data in single iteration vs using functions for readable code

    - by user828584
    Say I have an array of runners with which I need to find the tallest runner, the fastest runner, and the lightest runner. It seems like the most readable solution would be: runners = getRunners(); tallestRunner = getTallestRunner(runners); fastestRunner = getFastestRunner(runners); lightestRunner = getLightestRunner(runners); ..where each function iterates over the runners and keeps track of the largest height, greatest speed, and lowest weight. Iterating over the array three times, however, doesn't seem like a very good idea. It would instead be better to do: int greatestHeght, greatestSpeed, leastWeight; Runner tallestRunner, fastestRunner, lightestRunner; for(runner in runners){ if(runner.height > greatestHeight) { greatestHeight = runner.height; tallestRunner = runner; } if(runner.speed > ... } While this isn't too unreadable, it can get messy when there is more logic for each piece of information being extracted in the iteration. What's the middle ground here? How can I use only a single iteration while still keeping the code divided into logical units?

    Read the article

  • My PowerShell functions do not appear to be used

    - by Frank
    Hi there, I have a ps1 script in which I define 2 functions as such: function Invoke-Sql([string]$query) { Invoke-Sqlcmd -ServerInstance $Server -Database $DB -User $User -Password $Password -Query $query } function Get-Queued { Invoke-Sql "Select * From Comment where AwaitsModeration = 1" } I then call the ps1 file by typing it in (it's in a folder in the path, and autocompletion works) However, I cannot start using the functions. I am confused, because when I copy / paste the functions into the console, all is fine and they work. I also have a function defined in my profile, and it works. Where am I thinking wrong, why doesn't it work what I'm trying to do?

    Read the article

  • Is it possible to make a MS-SQL Scalar function do this?

    - by Hokken
    I have a 3rd party application that can call a MS-SQL scalar function to return some summary information from a table. I was able to return the summary values with a table-valued function, but the application won't utilize table-valued functions, so I'm kind of stuck. Here's a sample from the table: trackingNumber, projTaskAward, expenditureType, amount 1122, 12345-67-89, Supplies, 100 1122, 12345-67-89, Supplies, 150 1122, 12345-67-89, Supplies, 250 1122, 12345-67-89, Misc, 50 1122, 12345-67-89, Misc, 100 1122, 98765-43-21, General, 200 1122, 98765-43-21, Conference, 500 1122, 98765-43-21, Misc, 300 1122, 98765-43-21, Misc, 100 1122, 98765-43-21, Misc, 100 I want to summarize the amounts by projTaskAward & expenditureType, based on the trackingNumber. Here is the output I'm looking for: Proj/Task/Award: 12345-67-89 Expenditure Type: Supplies Total: 500 Proj/Task/Award: 12345-67-89 Expenditure Type: Misc Total: 150 Proj/Task/Award: 98765-43-21 Expenditure Type: General Total: 200 Proj/Task/Award: 98765-43-21 Expenditure Type: Conference Total: 500 Proj/Task/Award: 98765-43-21 Expenditure Type: Misc Total: 500 I'd appreciate any help anyone can give in steering me in the right direction.

    Read the article

  • My PowerShell functions do not appear to be registered

    - by Frank
    Hi there, I have a ps1 script in which I define 2 functions as such: function Invoke-Sql([string]$query) { Invoke-Sqlcmd -ServerInstance $Server -Database $DB -User $User -Password $Password -Query $query } function Get-Queued { Invoke-Sql "Select * From Comment where AwaitsModeration = 1" } I then call the ps1 file by typing it in (it's in a folder in the path, and autocompletion works) However, I cannot start using the functions. I am confused, because when I copy / paste the functions into the console, all is fine and they work. I also have a function defined in my profile, and it works. Where am I thinking wrong, why doesn't it work what I'm trying to do?

    Read the article

  • SQL SERVER – Using RAND() in User Defined Functions (UDF)

    - by pinaldave
    Here is the question I received in email. “Pinal, I am writing a function where we need to generate random password. While writing T-SQL I faced following issue. Everytime I tried to use RAND() function in my User Defined Function I am getting following error: Msg 443, Level 16, State 1, Procedure RandFn, Line 7 Invalid use of a side-effecting operator ‘rand’ within a function. Here is the simplified T-SQL code of the function which I am using: CREATE FUNCTION RandFn() RETURNS INT AS BEGIN DECLARE @rndValue INT SET @rndValue = RAND() RETURN @rndValue END GO I must use UDF so is there any workaround to use RAND function in UDF.” Here is the workaround how RAND() can be used in UDF. The scope of the blog post is not to discuss the advantages or disadvantages of the function or random function here but just to show how RAND() function can be used in UDF. RAND() function is directly not allowed to use in the UDF so we have to find alternate way to use the same function. This can be achieved by creating a VIEW which is using RAND() function and use the same VIEW in the UDF. Here is the step by step instructions. Create a VIEW using RAND function. CREATE VIEW rndView AS SELECT RAND() rndResult GO Create a UDF using the same VIEW. CREATE FUNCTION RandFn() RETURNS DECIMAL(18,18) AS BEGIN DECLARE @rndValue DECIMAL(18,18) SELECT @rndValue = rndResult FROM rndView RETURN @rndValue END GO Now execute the UDF and it will just work fine and return random result. SELECT dbo.RandFn() GO In T-SQL world, I have noticed that there are more than one solution to every problem. Is there any better solution to this question? Please post that question as a comment and I will include it with due credit. Reference: Pinal Dave (http://blog.SQLAuthority.com) Filed under: PostADay, SQL, SQL Authority, SQL Function, SQL Query, SQL Server, SQL Tips and Tricks, T SQL, Technology Tagged: technology

    Read the article

  • Improving Comparison Operators and Window Functions

    It is dangerous to assume that your data is sound. SQL already has intrinsic ways to cope with missing, or unknown data in its comparison predicate operators, or Theta operators. Can SQL be more effective in the way it deals with data quality? Joe Celko describes how the SQL Standard could soon evolve to deal with data in ways that allow aggregation and windowing in cases where the data quality is less than perfect

    Read the article

  • Recordings Available - Features & Functions Forms Module

    - by MHundal
    ETPM provides robust Forms functionality that allows implementations to configure Registration & Tax Forms, configure Form Rules and process the Forms.  The Forms Definition allows for defining the Form Sections and Form Lines.  The Forms Generator uses the Forms Definition details to create the necessary Business Objects, Application Security and User Interfaces to allow interaction with the Forms.  Form Rules are used for validation of the Form Line details and creating entities in the system (creating taxpayers, accounts, financial transactions, etc...). The following recordings provide an overview of the Forms Definition Process, Form Rules and other important concepts part of the Forms Module. Forms Module Overview:  https://oracletalk.webex.com/oracletalk/ldr.php?AT=pb&SP=MC&rID=66851417&rKey=7de22df4978e7974 Forms Configuration Overview:  https://oracletalk.webex.com/oracletalk/ldr.php?AT=pb&SP=MC&rID=66964342&rKey=ea564cfd701bb32d Form Rules Overview:  https://oracletalk.webex.com/oracletalk/ldr.php?AT=pb&SP=MC&rID=66966652&rKey=2e02c1e28e058d70  

    Read the article

  • Functions returning pointers

    - by fg nu
    C++ noob here. I have a very basic question about a construct I found in the C++ book I am reading. // class declaration class CStr { char sData[256]; public: char* get(void); }; // implementation of the function char* CStr::get(void) { return sData; } So the Cstr::get function is obviously meant to return a character pointer, but the function is passing what looks like the value (return sData). Does C++ know to return the address of the returned object? My guess would have been that the function definition would be return &sData.

    Read the article

  • Access functions from user control without events?

    - by BornToCode
    I have an application made with usercontrols and a function on main form that removes the previous user controls and shows the desired usercontrol centered and tweaked: public void DisplayControl(UserControl uControl) I find it much easier to make this function static or access this function by reference from the user control, like this: MainForm mainform_functions = (MainForm)Parent; mainform_functions.DisplayControl(uc_a); You probably think it's a sin to access a function in mainform, from the usercontrol, however, raising an event seems much more complex in such case - I'll give a simple example - let's say I raise an event from usercontrol_A to show usercontrol_B on mainform, so I write this: uc_a.show_uc_b+= (s,e) => { usercontrol_B uc_b = new usercontrol_B(); DisplayControl(uc_b); }; Now what if I want usercontrol_B to also have an event to show usercontrol_C? now it would look like this: uc_a.show_uc_b+= (s,e) => { usercontrol_B uc_b = new usercontrol_B(); DisplayControl(uc_b); uc_b.show_uc_c += (s2,e2) => {usercontrol_C uc_c = new usercontrol_C(); DisplayControl(uc_c);} }; THIS LOOKS AWFUL! The code is much simpler and readable when you actually access the function from the usercontrol itself, therefore I came to the conclusion that in such case it's not so terrible if I break the rules and not use events for such general function, I also think that a readable usercontrol that you need to make small adjustments for another app is preferable than a 100% 'generic' one which makes my code look like a pile of mud. What is your opinion? Am I mistaken?

    Read the article

  • OpenGL loading functions error [on hold]

    - by Ghilliedrone
    I'm new to OpenGL, and I bought a book on it for beginners. I finished writing the sample code for making a context/window. I get an error on this line at the part PFNWGLCREATECONTEXTATTRIBSARBPROC, saying "Error: expected a ')'": typedef HGLRC(APIENTRYP PFNWGLCREATECONTEXTATTRIBSARBPROC)(HDC, HGLRC, const int*); Replacing it or adding a ")" makes it error, but the error disappears when I use the OpenGL headers included in the books CD, which are OpenGL 3.0. I would like a way to make this work with the newest gl.h/wglext.h and without libraries. Here's the rest of the class if it's needed: #include <ctime> #include <windows.h> #include <iostream> #include <gl\GL.h> #include <gl\wglext.h> #include "Example.h" #include "GLWindow.h" typedef HGLRC(APIENTRYP PFNWGLCREATECONTEXTATTRIBSARBPROC)(HDC, HGLRC, const int*); PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = NULL; bool GLWindow::create(int width, int height, int bpp, bool fullscreen) { DWORD dwExStyle; //Window Extended Style DWORD dwStyle; //Window Style m_isFullscreen = fullscreen;//Store the fullscreen flag m_windowRect.left = 0L; m_windowRect.right = (long)width; m_windowRect.top = 0L; m_windowRect.bottom = (long)height;//Set bottom to height // fill out the window class structure m_windowClass.cbSize = sizeof(WNDCLASSEX); m_windowClass.style = CS_HREDRAW | CS_VREDRAW; m_windowClass.lpfnWndProc = GLWindow::StaticWndProc; //We set our static method as the event handler m_windowClass.cbClsExtra = 0; m_windowClass.cbWndExtra = 0; m_windowClass.hInstance = m_hinstance; m_windowClass.hIcon = LoadIcon(NULL, IDI_APPLICATION); // default icon m_windowClass.hCursor = LoadCursor(NULL, IDC_ARROW); // default arrow m_windowClass.hbrBackground = NULL; // don't need background m_windowClass.lpszMenuName = NULL; // no menu m_windowClass.lpszClassName = (LPCWSTR)"GLClass"; m_windowClass.hIconSm = LoadIcon(NULL, IDI_WINLOGO); // windows logo small icon if (!RegisterClassEx(&m_windowClass)) { MessageBox(NULL, (LPCWSTR)"Failed to register window class", NULL, MB_OK); return false; } if (m_isFullscreen)//If we are fullscreen, we need to change the display { DEVMODE dmScreenSettings; //Device mode memset(&dmScreenSettings, 0, sizeof(dmScreenSettings)); dmScreenSettings.dmSize = sizeof(dmScreenSettings); dmScreenSettings.dmPelsWidth = width; //Screen width dmScreenSettings.dmPelsHeight = height; //Screen height dmScreenSettings.dmBitsPerPel = bpp; //Bits per pixel dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) { MessageBox(NULL, (LPCWSTR)"Display mode failed", NULL, MB_OK); m_isFullscreen = false; } } if (m_isFullscreen) //Is it fullscreen? { dwExStyle = WS_EX_APPWINDOW; //Window Extended Style dwStyle = WS_POPUP; //Windows Style ShowCursor(false); //Hide mouse pointer } else { dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; //Window Exteneded Style dwStyle = WS_OVERLAPPEDWINDOW; //Windows Style } AdjustWindowRectEx(&m_windowRect, dwStyle, false, dwExStyle); //Adjust window to true requested size //Class registered, so now create window m_hwnd = CreateWindowEx(NULL, //Extended Style (LPCWSTR)"GLClass", //Class name (LPCWSTR)"Chapter 2", //App name dwStyle | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, 0, 0, //x, y coordinates m_windowRect.right - m_windowRect.left, m_windowRect.bottom - m_windowRect.top, //Width and height NULL, //Handle to parent NULL, //Handle to menu m_hinstance, //Application instance this); //Pass a pointer to the GLWindow here //Check if window creation failed, hwnd would equal NULL if (!m_hwnd) { return 0; } m_hdc = GetDC(m_hwnd); ShowWindow(m_hwnd, SW_SHOW); UpdateWindow(m_hwnd); m_lastTime = GetTickCount() / 1000.0f; return true; } LRESULT CALLBACK GLWindow::StaticWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { GLWindow* window = nullptr; //If this is the create message if (uMsg == WM_CREATE) { //Get the pointer we stored during create window = (GLWindow*)((LPCREATESTRUCT)lParam)->lpCreateParams; //Associate the window pointer with the hwnd for the other events to access SetWindowLongPtr(hWnd, GWL_USERDATA, (LONG_PTR)window); } else { //If this is not a creation event, then we should have stored a pointer to the window window = (GLWindow*)GetWindowLongPtr(hWnd, GWL_USERDATA); if (!window) { //Do the default event handling return DefWindowProc(hWnd, uMsg, wParam, lParam); } } //Call our window's member WndProc(allows us to access member variables) return window->WndProc(hWnd, uMsg, wParam, lParam); } LRESULT GLWindow::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_CREATE: { m_hdc = GetDC(hWnd); setupPixelFormat(); //Set the version that we want, in this case 3.0 int attribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 3, WGL_CONTEXT_MINOR_VERSION_ARB, 0, 0}; //Create temporary context so we can get a pointer to the function HGLRC tmpContext = wglCreateContext(m_hdc); //Make the context current wglMakeCurrent(m_hdc, tmpContext); //Get the function pointer wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB"); //If this is NULL then OpenGl 3.0 is not supported if (!wglCreateContextAttribsARB) { MessageBox(NULL, (LPCWSTR)"OpenGL 3.0 is not supported", (LPCWSTR)"An error occured", MB_ICONERROR | MB_OK); DestroyWindow(hWnd); return 0; } //Create an OpenGL 3.0 context using the new function m_hglrc = wglCreateContextAttribsARB(m_hdc, 0, attribs); //Delete the temporary context wglDeleteContext(tmpContext); //Make the GL3 context current wglMakeCurrent(m_hdc, m_hglrc); m_isRunning = true; } break; case WM_DESTROY: //Window destroy case WM_CLOSE: //Windows is closing wglMakeCurrent(m_hdc, NULL); wglDeleteContext(m_hglrc); m_isRunning = false; //Stop the main loop PostQuitMessage(0); break; case WM_SIZE: { int height = HIWORD(lParam); //Get height and width int width = LOWORD(lParam); getAttachedExample()->onResize(width, height); //Call the example's resize method } break; case WM_KEYDOWN: if (wParam == VK_ESCAPE) //If the escape key was pressed { DestroyWindow(m_hwnd); } break; default: break; } return DefWindowProc(hWnd, uMsg, wParam, lParam); } void GLWindow::processEvents() { MSG msg; //While there are messages in the queue, store them in msg while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { //Process the messages TranslateMessage(&msg); DispatchMessage(&msg); } } Here is the header: #pragma once #include <ctime> #include <windows.h> class Example;//Declare our example class class GLWindow { public: GLWindow(HINSTANCE hInstance); //default constructor bool create(int width, int height, int bpp, bool fullscreen); void destroy(); void processEvents(); void attachExample(Example* example); bool isRunning(); //Is the window running? void swapBuffers() { SwapBuffers(m_hdc); } static LRESULT CALLBACK StaticWndProc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam); LRESULT CALLBACK WndProc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam); float getElapsedSeconds(); private: Example* m_example; //A link to the example program bool m_isRunning; //Is the window still running? bool m_isFullscreen; HWND m_hwnd; //Window handle HGLRC m_hglrc; //Rendering context HDC m_hdc; //Device context RECT m_windowRect; //Window bounds HINSTANCE m_hinstance; //Application instance WNDCLASSEX m_windowClass; void setupPixelFormat(void); Example* getAttachedExample() { return m_example; } float m_lastTime; };

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >