Search Results

Search found 1354 results on 55 pages for 'compute scalar'.

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

  • Cannot compute equation, always gives zero

    - by user1738391
    Did i miss something? The variable percentage_ always equals 0. I've checked nTimes and winnings, they give the correct values as what is being input. Even when I test out a simple equation like, percentage_=1+1, percentage_ will give 0. Can someone help? #pragma once #include <iostream> #include <string> #include <cstdlib> #include <iomanip> using namespace std; class GuessMachine { private: int nTimes; int winnings; string nM[6]; public: GuessMachine(); void displayPrizes(); void displayMenu(); int getInput(); void checkNumber(); void checkPrize(); }; void GuessMachine::checkPrize() { MagicNumber mn; int prize_=mn.generateNumber(); float percentage_; percentage_ = float (winnings/nTimes*100); //<--On this line percentage is always 0 no matter what winnings and nTimes are cout<<"Percentage is "<<percentage_<<endl; if(percentage_ >= 50) { cout<<"You have scored "<<percentage_<<"% and won "<<nM[prize_]; } else { cout<<"You have scored "<<percentage_<<"%. You lose!!"; } cin.ignore(); cin.ignore(); }

    Read the article

  • CSG operations on implicit surfaces with marching cubes [SOLVED]

    - by Mads Elvheim
    I render isosurfaces with marching cubes, (or perhaps marching squares as this is 2D) and I want to do set operations like set difference, intersection and union. I thought this was easy to implement, by simply choosing between two vertex scalars from two different implicit surfaces, but it is not. For my initial testing, I tried with two spheres circles, and the set operation difference. i.e A - B. One circle is moving and the other one is stationary. Here's the approach I tried when picking vertex scalars and when classifying corner vertices as inside or outside. The code is written in C++. OpenGL is used for rendering, but that's not important. Normal rendering without any CSG operations does give the expected result. void march(const vec2& cmin, //min x and y for the grid cell const vec2& cmax, //max x and y for the grid cell std::vector<vec2>& tri, float iso, float (*cmp1)(const vec2&), //distance from stationary circle float (*cmp2)(const vec2&) //distance from moving circle ) { unsigned int squareindex = 0; float scalar[4]; vec2 verts[8]; /* initial setup of the grid cell */ verts[0] = vec2(cmax.x, cmax.y); verts[2] = vec2(cmin.x, cmax.y); verts[4] = vec2(cmin.x, cmin.y); verts[6] = vec2(cmax.x, cmin.y); float s1,s2; /********************************** ********For-loop of interest****** *******Set difference between **** *******two implicit surfaces****** **********************************/ for(int i=0,j=0; i<4; ++i, j+=2){ s1 = cmp1(verts[j]); s2 = cmp2(verts[j]); if((s1 < iso)){ //if inside circle1 if((s2 < iso)){ //if inside circle2 scalar[i] = s2; //then set the scalar to the moving circle } else { scalar[i] = s1; //only inside circle1 squareindex |= (1<<i); //mark as inside } } else { scalar[i] = s1; //inside neither circle } } if(squareindex == 0) return; /* Usual interpolation between edge points to compute the new intersection points */ verts[1] = mix(iso, verts[0], verts[2], scalar[0], scalar[1]); verts[3] = mix(iso, verts[2], verts[4], scalar[1], scalar[2]); verts[5] = mix(iso, verts[4], verts[6], scalar[2], scalar[3]); verts[7] = mix(iso, verts[6], verts[0], scalar[3], scalar[0]); for(int i=0; i<10; ++i){ //10 = maxmimum 3 triangles, + one end token int index = triTable[squareindex][i]; //look up our indices for triangulation if(index == -1) break; tri.push_back(verts[index]); } } This gives me weird jaggies: It looks like the CSG operation is done without interpolation. It just "discards" the whole triangle. Do I need to interpolate in some other way, or combine the vertex scalar values? I'd love some help with this. A full testcase can be downloaded HERE EDIT: Basically, my implementation of marching squares works fine. It is my scalar field which is broken, and I wonder what the correct way would look like. Preferably I'm looking for a general approach to implement the three set operations I discussed above, for the usual primitives (circle, rectangle/square, plane)

    Read the article

  • how to deploy web application directly from git master branch

    - by mobile.linkr
    For educational purpose, I am writing a server instance in GCE(google compute engine) to serve a few web apps mostly (to be) written in Dart and Polymer. My workflow is, when my students log-in the server above, they will automatically fork those web apps into their own registries in their own server instances for further development. My issues are, How to serve web applications(they are git registries as well) in GCE like Github Pages? Is it possible to manipulate Github Pages to serve web apps mostly using Dart and Polymer packages? Thanks in advance.

    Read the article

  • Insert not working

    - by user1642318
    I've searched evreywhere and tried all suggestions but still no luck when running the following code. Note that some code is commented out. Thats just me trying different things. SqlConnection connection = new SqlConnection("Data Source=URB900-PC\SQLEXPRESS;Initial Catalog=usersSQL;Integrated Security=True"); string password = PasswordTextBox.Text; string email = EmailTextBox.Text; string firstname = FirstNameTextBox.Text; string lastname = SurnameTextBox.Text; //command.Parameters.AddWithValue("@UserName", username); //command.Parameters.AddWithValue("@Password", password); //command.Parameters.AddWithValue("@Email", email); //command.Parameters.AddWithValue("@FirstName", firstname); //command.Parameters.AddWithValue("@LastName", lastname); command.Parameters.Add("@UserName", SqlDbType.VarChar); command.Parameters["@UserName"].Value = username; command.Parameters.Add("@Password", SqlDbType.VarChar); command.Parameters["@Password"].Value = password; command.Parameters.Add("@Email", SqlDbType.VarChar); command.Parameters["@Email"].Value = email; command.Parameters.Add("@FirstName", SqlDbType.VarChar); command.Parameters["@FirstName"].Value = firstname; command.Parameters.Add("@LasttName", SqlDbType.VarChar); command.Parameters["@LasttName"].Value = lastname; SqlCommand command2 = new SqlCommand("INSERT INTO users (UserName, Password, UserEmail, FirstName, LastName)" + "values (@UserName, @Password, @Email, @FirstName, @LastName)", connection); connection.Open(); command2.ExecuteNonQuery(); //command2.ExecuteScalar(); connection.Close(); When I run this, fill in the textboxes and hit the button I get...... Must declare the scalar variable "@UserName". Any help would be greatly appreciated. Thanks.

    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

  • Is there a problem with scrollTop in Chrome?

    - by Shaun
    I am setting scrollTop and scrollLeft for a div that I am working with. The code looks like this: div.scrollLeft = content.cx*scalar - parseInt(div.style.width)/2; div.scrollTop = content.cy*scalar - parseInt(div.style.height)/2; This works just fine in FF, but only scrollLeft works in chrome. As you can see, the two use almost identical equations and as it works in FF I am just wondering if this is a problem with Chrome? Update: If I switch the order of the assignments then scrollTop will work and scrollLeft won't. <div id="container" style = "height:600px; width:600px; overflow:auto;" onscroll = "updateCenter()"> <script> var div = document.getElementById('container'); function updateCenter() { svfdim.cx = (div.scrollLeft + parseFloat(div.style.width)/2)/scalar; svfdim.cy = (div.scrollTop + parseFloat(div.style.height)/2)/scalar; } function updateScroll(svfdim, scalar, div) { div.scrollTop = svgdim.cy*scalar - parseFloat(div.style.height)/2; div.scrollLeft = svgdim.cx*scalar - parseFloat(div.style.width)/2; } function resizeSVG(Root) { Root.setAttribute("height", svfdim.height*scalar); Root.setAttribute("width", svfdim.width*scalar); updateScroll(svgdim, scalar, div); } </script>

    Read the article

  • CSG operations on implicit surfaces with marching cubes

    - by Mads Elvheim
    I render isosurfaces with marching cubes, (or perhaps marching squares as this is 2D) and I want to do set operations like set difference, intersection and union. I thought this was easy to implement, by simply choosing between two vertex scalars from two different implicit surfaces, but it is not. For my initial testing, I tried with two spheres, and the set operation difference. i.e A - B. One sphere is moving and the other one is stationary. Here's the approach I tried when picking vertex scalars and when classifying corner vertices as inside or outside. The code is written in C++. OpenGL is used for rendering, but that's not important. Normal rendering without any CSG operations does give the expected result. void march(const vec2& cmin, //min x and y for the grid cell const vec2& cmax, //max x and y for the grid cell std::vector<vec2>& tri, float iso, float (*cmp1)(const vec2&), //distance from stationary sphere float (*cmp2)(const vec2&) //distance from moving sphere ) { unsigned int squareindex = 0; float scalar[4]; vec2 verts[8]; /* initial setup of the grid cell */ verts[0] = vec2(cmax.x, cmax.y); verts[2] = vec2(cmin.x, cmax.y); verts[4] = vec2(cmin.x, cmin.y); verts[6] = vec2(cmax.x, cmin.y); float s1,s2; /********************************** ********For-loop of interest****** *******Set difference between **** *******two implicit surfaces****** **********************************/ for(int i=0,j=0; i<4; ++i, j+=2){ s1 = cmp1(verts[j]); s2 = cmp2(verts[j]); if((s1 < iso)){ //if inside sphere1 if((s2 < iso)){ //if inside sphere2 scalar[i] = s2; //then set the scalar to the moving sphere } else { scalar[i] = s1; //only inside sphere1 squareindex |= (1<<i); //mark as inside } } else { scalar[i] = s1; //inside neither sphere } } if(squareindex == 0) return; /* Usual interpolation between edge points to compute the new intersection points */ verts[1] = mix(iso, verts[0], verts[2], scalar[0], scalar[1]); verts[3] = mix(iso, verts[2], verts[4], scalar[1], scalar[2]); verts[5] = mix(iso, verts[4], verts[6], scalar[2], scalar[3]); verts[7] = mix(iso, verts[6], verts[0], scalar[3], scalar[0]); for(int i=0; i<10; ++i){ //10 = maxmimum 3 triangles, + one end token int index = triTable[squareindex][i]; //look up our indices for triangulation if(index == -1) break; tri.push_back(verts[index]); } } This gives me weird jaggies: It looks like the CSG operation is done without interpolation. It just "discards" the whole triangle. Do I need to interpolate in some other way, or combine the vertex scalar values? I'd love some help with this. A full testcase can be downloaded HERE

    Read the article

  • Why doesn't Perl file glob() work outside of a loop in scalar context?

    - by Rob
    According to the Perl documentation on file globbing, the <*> operator or glob() function, when used in a scalar context, should iterate through the list of files matching the specified pattern, returning the next file name each time it is called or undef when there are no more files. But, the iterating process only seems to work from within a loop. If it isn't in a loop, then it seems to start over immediately before all values have been read. From the Perl docs: In scalar context, glob iterates through such filename expansions, returning undef when the list is exhausted. http://perldoc.perl.org/functions/glob.html However, in scalar context the operator returns the next value each time it's called, or undef when the list has run out. http://perldoc.perl.org/perlop.html#I/O-Operators Example code: use warnings; use strict; my $filename; # in scalar context, <*> should return the next file name # each time it is called or undef when the list has run out $filename = <*>; print "$filename\n"; $filename = <*>; # doesn't work as documented, starts over and print "$filename\n"; # always returns the same file name $filename = <*>; print "$filename\n"; print "\n"; print "$filename\n" while $filename = <*>; # works in a loop, returns next file # each time it is called In a directory with 3 files...file1.txt, file2.txt, and file3.txt, the above code will output: file1.txt file1.txt file1.txt file1.txt file2.txt file3.txt Note: The actual perl script should be outside the test directory, or you will see the file name of the script in the output as well. Am I doing something wrong here, or is this how it is supposed to work?

    Read the article

  • Visual basic 6.0 - ComputeHash invalid procedure call or argument error

    - by Mohan Babu Vijaya Gopal
    I am getting the error "invalid procedure call or arguments" at the step computeHash(). Any help highly appreciated. Private Sub Form_Load() Dim rngcsp As New RNGCryptoServiceProvider '= new RNGCryptoServiceProvider() Dim u8 As Encoding 'u8 = Encoding.UTF8 Dim minSaltSize As Integer Dim maxSaltSize As Integer Dim saltSize As Integer minSaltSize = 4 maxSaltSize = 8 Dim randm As Random Set randm = New Random Dim saltBytes() As Byte ReDim saltBytes(saltSize) Set rngcsp = New RNGCryptoServiceProvider rngcsp.GetNonZeroBytes (saltBytes) Dim plainTextBytes() As Byte plainTextBytes() = ConvertStringToUtf8Bytes("Mohan") Dim plainTextBytesLen As Long plainTextBytesLen = UBound(plainTextBytes) - LBound(plainTextBytes) + 1 Dim saltBytesLen As Long saltBytesLen = UBound(saltBytes) - LBound(saltBytes) + 1 Dim plainTextWithSaltBytes() As Byte ReDim plainTextWithSaltBytes(plainTextBytesLen + saltBytesLen) For i = 0 To plainTextBytesLen - 1 plainTextWithSaltBytes(i) = plainTextBytes(i) Next For i = 0 To saltBytesLen - 1 plainTextWithSaltBytes(i) = saltBytes(i) Next 'Dim hash As HashAlgorithm = New MD5CryptoServiceProvider() Dim hash12 As New SHA256Managed 'SHA256Managed Dim totLen As Integer totLen = plainTextBytesLen + saltBytesLen Dim str As String Dim hashBytes() As Byte 'With hashBytes = hash12.computeHash(plainTextWithSaltBytes) ', 0, totLen) 'End With End Sub

    Read the article

  • AS3 computeSpectrum fft true

    - by cr1ms0n3cho
    I am just trying to understand what the values sent back from computeSpectrum(bytes,true,0) mean. I have values ranging from 0 to 1 for each float i read from the byte array but does each value represent a range of Hz Thanks!

    Read the article

  • similarity between strings - sql server 2005

    - by csetzkorn
    Hi, I am looking for a simple way (UDF?) to establish the similarity between strings. The SOUNDEX and DIFFERENCE function do not seem to do the job. Similarity should be based on number of characters in common (order matters). For example: Spiruroidea sp. AM-2008 and Spiruroidea gen. sp. AM-2008 should be recognised as similar. Any pointers would be very much appreciated. Thanks. Christian

    Read the article

  • T-SQL User-Defined Functions: the good, the bad, and the ugly (part 4)

    - by Hugo Kornelis
    Scalar user-defined functions are bad for performance. I already showed that for T-SQL scalar user-defined functions without and with data access, and for most CLR scalar user-defined functions without data access , and in this blog post I will show that CLR scalar user-defined functions with data access fit into that picture. First attempt Sticking to my simplistic example of finding the triple of an integer value by reading it from a pre-populated lookup table and following the standard recommendations...(read more)

    Read the article

  • Windows Azure HPC Scheduler Architecture

    - by Churianov Roman
    So far I've found very little information on the scheduling policy, resource management policy of Azure HPC Scheduler. I would appreciate any kind of information regarding some of these questions: What scheduling policy does a Head Node use to scatter jobs to Compute Nodes? Does Azure Scheduler use prior information about the jobs (compute time, memory demands ...) ? If 'yes', how it gets this information? Does Azure Scheduler split a job into several parallel jobs on one Compute node? Does it have any protection from Compute Node failures? (what it does when a compute node stops responding) Does it support addition/subtraction of Compute nodes? Is it possible to cancel a job? P.S. I'm aware of the MSDN resource Windows Azure HPC Scheduler. I found only information of how to use this Scheduler but almost nothing about how it works inside.

    Read the article

  • How does the dataset determine the return type of a scalar query?

    - by Tobias Funke
    I am attempting to add a scalar query to a dataset. The query is pretty straight forward, it's just adding up some decimal values in a few columns and returning them. I am 100% confident that only one row and one column is returned, and that it is of decimal type (SQL money type). The problem is that for some reason, the generated method (in the .designer.cs code file) is returning a value of type object, when it should be decimal. What's strange is that there's another scalar query that has the exact same SQL but is returning decimal like it should. How does the dataset designer determine the data type, and how can I tell it to return decimal?

    Read the article

  • How does the dataset designer determine the return type of a scalar query?

    - by Tobias Funke
    I am attempting to add a scalar query to a dataset. The query is pretty straight forward, it's just adding up some decimal values in a few columns and returning them. I am 100% confident that only one row and one column is returned, and that it is of decimal type (SQL money type). The problem is that for some reason, the generated method (in the .designer.cs code file) is returning a value of type object, when it should be decimal. What's strange is that there's another scalar query that has the exact same SQL but is returning decimal like it should. How does the dataset designer determine the data type, and how can I tell it to return decimal?

    Read the article

  • Is there a way to test if a scalar has been stringified or not?

    - by Yobert
    I am writing a thing to output something similar to JSON, from a perl structure. I want the quoting to behave like this: "string" outputs "string" "05" outputs "05" "5" outputs "5" 5 outputs 5 05 outputs 5, or 05 would be acceptable JSON::XS handles this by testing if a scalar has been "stringified" or not, which I think is very cool. But I can't find a way to do this test myself without writing XS, which I'd rather avoid. Is this possible? I can't find this anywhere on CPAN without finding vast pedantry about Scalar::Util::looks_like_number, etc which completely isn't what I want. The only stopgap I can find is Devel::Peek, which feels evil. And also, just like JSON::XS, I'm fine with this secenario: my $a = 5; print $a."\n"; # now $a outputs "5" instead of 5)

    Read the article

  • Do you know of a C macro to compute Unix time and date?

    - by Alexis Wilke
    I'm wondering if someone knows/has a C macro to compute a static Unix time from a hard coded date and time as in: time_t t = UNIX_TIMESTAMP(2012, 5, 10, 9, 26, 13); I'm looking into that because I want to have a numeric static timestamp. This will be done hundred of times throughout the software, each time with a different date, and I want to make sure it is fast because it will run hundreds of times every second. Converting dates that many times would definitively slow down things (i.e. calling mktime() is slower than having a static number compiled in place, right?) [made an update to try to render this paragraph clearer, Nov 23, 2012] Update I want to clarify the question with more information about the process being used. As my server receives requests, for each request, it starts a new process. That process is constantly updated with new plugins and quite often such updates require a database update. Those must be run only once. To know whether an update is necessary, I want to use a Unix date (which is better than using a counter because a counter is much more likely to break once in a while.) The plugins will thus receive an update signal and have their on_update() function called. There I want to do something like this: void some_plugin::on_update(time_t last_update) { if(last_update < UNIX_TIMESTAMP(2010, 3, 22, 20, 9, 26)) { ...run update... } if(last_update < UNIX_TIMESTAMP(2012, 5, 10, 9, 26, 13)) { ...run update... } // as many test as required... } As you can see, if I have to compute the unix timestamp each time, this could represent thousands of calls per process and if you receive 100 hits a second x 1000 calls, you wasted 100,000 calls when you could have had the compiler compute those numbers once at compile time. Putting the value in a static variable is of no interest because this code will run once per process run. Note that the last_update variable changes depending on the website being hit (it comes from the database.) Code Okay, I got the code now: // helper (Days in February) #define _SNAP_UNIX_TIMESTAMP_FDAY(year) \ (((year) % 400) == 0 ? 29LL : \ (((year) % 100) == 0 ? 28LL : \ (((year) % 4) == 0 ? 29LL : \ 28LL))) // helper (Days in the year) #define _SNAP_UNIX_TIMESTAMP_YDAY(year, month, day) \ ( \ /* January */ static_cast<qint64>(day) \ /* February */ + ((month) >= 2 ? 31LL : 0LL) \ /* March */ + ((month) >= 3 ? _SNAP_UNIX_TIMESTAMP_FDAY(year) : 0LL) \ /* April */ + ((month) >= 4 ? 31LL : 0LL) \ /* May */ + ((month) >= 5 ? 30LL : 0LL) \ /* June */ + ((month) >= 6 ? 31LL : 0LL) \ /* July */ + ((month) >= 7 ? 30LL : 0LL) \ /* August */ + ((month) >= 8 ? 31LL : 0LL) \ /* September */+ ((month) >= 9 ? 31LL : 0LL) \ /* October */ + ((month) >= 10 ? 30LL : 0LL) \ /* November */ + ((month) >= 11 ? 31LL : 0LL) \ /* December */ + ((month) >= 12 ? 30LL : 0LL) \ ) #define SNAP_UNIX_TIMESTAMP(year, month, day, hour, minute, second) \ ( /* time */ static_cast<qint64>(second) \ + static_cast<qint64>(minute) * 60LL \ + static_cast<qint64>(hour) * 3600LL \ + /* year day (month + day) */ (_SNAP_UNIX_TIMESTAMP_YDAY(year, month, day) - 1) * 86400LL \ + /* year */ (static_cast<qint64>(year) - 1970LL) * 31536000LL \ + ((static_cast<qint64>(year) - 1969LL) / 4LL) * 86400LL \ - ((static_cast<qint64>(year) - 1901LL) / 100LL) * 86400LL \ + ((static_cast<qint64>(year) - 1601LL) / 400LL) * 86400LL ) WARNING: Do not use these macros to dynamically compute a date. It is SLOWER than mktime(). This being said, if you have a hard coded date, then the compiler will compute the time_t value at compile time. Slower to compile, but faster to execute over and over again.

    Read the article

  • Perl : In splice() type of arg1 must be array, cannot be scalar dereference. How to fix?

    - by Michael Mao
    I am trying to comprehend the reference/dereference system in Perl. What I am trying to do is to remove an element by using reference: my $ref= \@{$collection{$_[0]}}; # delete($$ref[$i]); # delete works, I've tested that already splice($$ref, $i, 1); # this wouldn't do. I first tried the delete() subroutine, it works; however, it doesn't shift the index after the removed elements forward by 1, so I cannot continue working on other stuff. I then Googled and found the splice() subroutine which does delete and shift in one go. But the error feedback tells me that "Type of arg 1 to splice must be array (not scalar dereference)..." I then tried something like this: splice(@{$$ref}, $i, 1); That resulted in another error like this: "Not a SCALAR reference at...(pointing at that line)" So I am a bit puzzled, how could I handle this issue? I prefer not using any CPAN or additional library for the solution, if possible.

    Read the article

  • What to set the scalar type to contain a byte []. Entity in MVC2

    - by Brad8118
    I'm trying out the EF 4.0 and using the Model first approach. I'd like to store images into the database and I'm not sure of the best type for the scalar in the entity. I currently have it(the image scalar type) setup as a binary. From what I have been reading the best way to store the image in the db is a byte[]. So I'm assuming that binary is the way to go. If there is a better way I'd switch. In my controller I have: //file from client to store in the db HttpPostedFileBase file = Request.Files[inputTagName]; if (file.ContentLength > 0) { keyToAdd.Image = new byte[file.ContentLength]; file.InputStream.Write(keyToAdd.Image, 0, file.ContentLength); } This builds fine but when I run it I get an exception writing the stream to keyToAdd.Image. The exception is something like: Method does not exist. Any ideas? Note that when using a EF 4.0 model first approach I only have int16, int32, double, string, decimal, binary, byte, DateTime, Double, Single, and SByte as available types. Thanks

    Read the article

  • When is a SQL function not a function?

    - by Rob Farley
    Should SQL Server even have functions? (Oh yeah – this is a T-SQL Tuesday post, hosted this month by Brad Schulz) Functions serve an important part of programming, in almost any language. A function is a piece of code that is designed to return something, as opposed to a piece of code which isn’t designed to return anything (which is known as a procedure). SQL Server is no different. You can call stored procedures, even from within other stored procedures, and you can call functions and use these in other queries. Stored procedures might query something, and therefore ‘return data’, but a function in SQL is considered to have the type of the thing returned, and can be used accordingly in queries. Consider the internal GETDATE() function. SELECT GETDATE(), SomeDatetimeColumn FROM dbo.SomeTable; There’s no logical difference between the field that is being returned by the function and the field that’s being returned by the table column. Both are the datetime field – if you didn’t have inside knowledge, you wouldn’t necessarily be able to tell which was which. And so as developers, we find ourselves wanting to create functions that return all kinds of things – functions which look up values based on codes, functions which do string manipulation, and so on. But it’s rubbish. Ok, it’s not all rubbish, but it mostly is. And this isn’t even considering the SARGability impact. It’s far more significant than that. (When I say the SARGability aspect, I mean “because you’re unlikely to have an index on the result of some function that’s applied to a column, so try to invert the function and query the column in an unchanged manner”) I’m going to consider the three main types of user-defined functions in SQL Server: Scalar Inline Table-Valued Multi-statement Table-Valued I could also look at user-defined CLR functions, including aggregate functions, but not today. I figure that most people don’t tend to get around to doing CLR functions, and I’m going to focus on the T-SQL-based user-defined functions. Most people split these types of function up into two types. So do I. Except that most people pick them based on ‘scalar or table-valued’. I’d rather go with ‘inline or not’. If it’s not inline, it’s rubbish. It really is. Let’s start by considering the two kinds of table-valued function, and compare them. These functions are going to return the sales for a particular salesperson in a particular year, from the AdventureWorks database. CREATE FUNCTION dbo.FetchSales_inline(@salespersonid int, @orderyear int) RETURNS TABLE AS  RETURN (     SELECT e.LoginID as EmployeeLogin, o.OrderDate, o.SalesOrderID     FROM Sales.SalesOrderHeader AS o     LEFT JOIN HumanResources.Employee AS e     ON e.EmployeeID = o.SalesPersonID     WHERE o.SalesPersonID = @salespersonid     AND o.OrderDate >= DATEADD(year,@orderyear-2000,'20000101')     AND o.OrderDate < DATEADD(year,@orderyear-2000+1,'20000101') ) ; GO CREATE FUNCTION dbo.FetchSales_multi(@salespersonid int, @orderyear int) RETURNS @results TABLE (     EmployeeLogin nvarchar(512),     OrderDate datetime,     SalesOrderID int     ) AS BEGIN     INSERT @results (EmployeeLogin, OrderDate, SalesOrderID)     SELECT e.LoginID, o.OrderDate, o.SalesOrderID     FROM Sales.SalesOrderHeader AS o     LEFT JOIN HumanResources.Employee AS e     ON e.EmployeeID = o.SalesPersonID     WHERE o.SalesPersonID = @salespersonid     AND o.OrderDate >= DATEADD(year,@orderyear-2000,'20000101')     AND o.OrderDate < DATEADD(year,@orderyear-2000+1,'20000101')     ;     RETURN END ; GO You’ll notice that I’m being nice and responsible with the use of the DATEADD function, so that I have SARGability on the OrderDate filter. Regular readers will be hoping I’ll show what’s going on in the execution plans here. Here I’ve run two SELECT * queries with the “Show Actual Execution Plan” option turned on. Notice that the ‘Query cost’ of the multi-statement version is just 2% of the ‘Batch cost’. But also notice there’s trickery going on. And it’s nothing to do with that extra index that I have on the OrderDate column. Trickery. Look at it – clearly, the first plan is showing us what’s going on inside the function, but the second one isn’t. The second one is blindly running the function, and then scanning the results. There’s a Sequence operator which is calling the TVF operator, and then calling a Table Scan to get the results of that function for the SELECT operator. But surely it still has to do all the work that the first one is doing... To see what’s actually going on, let’s look at the Estimated plan. Now, we see the same plans (almost) that we saw in the Actuals, but we have an extra one – the one that was used for the TVF. Here’s where we see the inner workings of it. You’ll probably recognise the right-hand side of the TVF’s plan as looking very similar to the first plan – but it’s now being called by a stack of other operators, including an INSERT statement to be able to populate the table variable that the multi-statement TVF requires. And the cost of the TVF is 57% of the batch! But it gets worse. Let’s consider what happens if we don’t need all the columns. We’ll leave out the EmployeeLogin column. Here, we see that the inline function call has been simplified down. It doesn’t need the Employee table. The join is redundant and has been eliminated from the plan, making it even cheaper. But the multi-statement plan runs the whole thing as before, only removing the extra column when the Table Scan is performed. A multi-statement function is a lot more powerful than an inline one. An inline function can only be the result of a single sub-query. It’s essentially the same as a parameterised view, because views demonstrate this same behaviour of extracting the definition of the view and using it in the outer query. A multi-statement function is clearly more powerful because it can contain far more complex logic. But a multi-statement function isn’t really a function at all. It’s a stored procedure. It’s wrapped up like a function, but behaves like a stored procedure. It would be completely unreasonable to expect that a stored procedure could be simplified down to recognise that not all the columns might be needed, but yet this is part of the pain associated with this procedural function situation. The biggest clue that a multi-statement function is more like a stored procedure than a function is the “BEGIN” and “END” statements that surround the code. If you try to create a multi-statement function without these statements, you’ll get an error – they are very much required. When I used to present on this kind of thing, I even used to call it “The Dangers of BEGIN and END”, and yes, I’ve written about this type of thing before in a similarly-named post over at my old blog. Now how about scalar functions... Suppose we wanted a scalar function to return the count of these. CREATE FUNCTION dbo.FetchSales_scalar(@salespersonid int, @orderyear int) RETURNS int AS BEGIN     RETURN (         SELECT COUNT(*)         FROM Sales.SalesOrderHeader AS o         LEFT JOIN HumanResources.Employee AS e         ON e.EmployeeID = o.SalesPersonID         WHERE o.SalesPersonID = @salespersonid         AND o.OrderDate >= DATEADD(year,@orderyear-2000,'20000101')         AND o.OrderDate < DATEADD(year,@orderyear-2000+1,'20000101')     ); END ; GO Notice the evil words? They’re required. Try to remove them, you just get an error. That’s right – any scalar function is procedural, despite the fact that you wrap up a sub-query inside that RETURN statement. It’s as ugly as anything. Hopefully this will change in future versions. Let’s have a look at how this is reflected in an execution plan. Here’s a query, its Actual plan, and its Estimated plan: SELECT e.LoginID, y.year, dbo.FetchSales_scalar(p.SalesPersonID, y.year) AS NumSales FROM (VALUES (2001),(2002),(2003),(2004)) AS y (year) CROSS JOIN Sales.SalesPerson AS p LEFT JOIN HumanResources.Employee AS e ON e.EmployeeID = p.SalesPersonID; We see here that the cost of the scalar function is about twice that of the outer query. Nicely, the query optimizer has worked out that it doesn’t need the Employee table, but that’s a bit of a red herring here. There’s actually something way more significant going on. If I look at the properties of that UDF operator, it tells me that the Estimated Subtree Cost is 0.337999. If I just run the query SELECT dbo.FetchSales_scalar(281,2003); we see that the UDF cost is still unchanged. You see, this 0.0337999 is the cost of running the scalar function ONCE. But when we ran that query with the CROSS JOIN in it, we returned quite a few rows. 68 in fact. Could’ve been a lot more, if we’d had more salespeople or more years. And so we come to the biggest problem. This procedure (I don’t want to call it a function) is getting called 68 times – each one between twice as expensive as the outer query. And because it’s calling it in a separate context, there is even more overhead that I haven’t considered here. The cheek of it, to say that the Compute Scalar operator here costs 0%! I know a number of IT projects that could’ve used that kind of costing method, but that’s another story that I’m not going to go into here. Let’s look at a better way. Suppose our scalar function had been implemented as an inline one. Then it could have been expanded out like a sub-query. It could’ve run something like this: SELECT e.LoginID, y.year, (SELECT COUNT(*)     FROM Sales.SalesOrderHeader AS o     LEFT JOIN HumanResources.Employee AS e     ON e.EmployeeID = o.SalesPersonID     WHERE o.SalesPersonID = p.SalesPersonID     AND o.OrderDate >= DATEADD(year,y.year-2000,'20000101')     AND o.OrderDate < DATEADD(year,y.year-2000+1,'20000101')     ) AS NumSales FROM (VALUES (2001),(2002),(2003),(2004)) AS y (year) CROSS JOIN Sales.SalesPerson AS p LEFT JOIN HumanResources.Employee AS e ON e.EmployeeID = p.SalesPersonID; Don’t worry too much about the Scan of the SalesOrderHeader underneath a Nested Loop. If you remember from plenty of other posts on the matter, execution plans don’t push the data through. That Scan only runs once. The Index Spool sucks the data out of it and populates a structure that is used to feed the Stream Aggregate. The Index Spool operator gets called 68 times, but the Scan only once (the Number of Executions property demonstrates this). Here, the Query Optimizer has a full picture of what’s being asked, and can make the appropriate decision about how it accesses the data. It can simplify it down properly. To get this kind of behaviour from a function, we need it to be inline. But without inline scalar functions, we need to make our function be table-valued. Luckily, that’s ok. CREATE FUNCTION dbo.FetchSales_inline2(@salespersonid int, @orderyear int) RETURNS table AS RETURN (SELECT COUNT(*) as NumSales     FROM Sales.SalesOrderHeader AS o     LEFT JOIN HumanResources.Employee AS e     ON e.EmployeeID = o.SalesPersonID     WHERE o.SalesPersonID = @salespersonid     AND o.OrderDate >= DATEADD(year,@orderyear-2000,'20000101')     AND o.OrderDate < DATEADD(year,@orderyear-2000+1,'20000101') ); GO But we can’t use this as a scalar. Instead, we need to use it with the APPLY operator. SELECT e.LoginID, y.year, n.NumSales FROM (VALUES (2001),(2002),(2003),(2004)) AS y (year) CROSS JOIN Sales.SalesPerson AS p LEFT JOIN HumanResources.Employee AS e ON e.EmployeeID = p.SalesPersonID OUTER APPLY dbo.FetchSales_inline2(p.SalesPersonID, y.year) AS n; And now, we get the plan that we want for this query. All we’ve done is tell the function that it’s returning a table instead of a single value, and removed the BEGIN and END statements. We’ve had to name the column being returned, but what we’ve gained is an actual inline simplifiable function. And if we wanted it to return multiple columns, it could do that too. I really consider this function to be superior to the scalar function in every way. It does need to be handled differently in the outer query, but in many ways it’s a more elegant method there too. The function calls can be put amongst the FROM clause, where they can then be used in the WHERE or GROUP BY clauses without fear of calling the function multiple times (another horrible side effect of functions). So please. If you see BEGIN and END in a function, remember it’s not really a function, it’s a procedure. And then fix it. @rob_farley

    Read the article

  • How does Minecraft compute lighting for it's non-block objects?

    - by Darestium
    I was wondering how the creator of Minecraft went about lighting the objects (player and pickaxe) based on the lighting level around the player. I have implemented the ability to light the blocks around the player but I can't really think of anyway to implement with objects. Also, when I the player moves and the lighting values change will I have to rebuild it's vertexbuffers? Or is there some other way? Any ideas?

    Read the article

  • Compute the AES-encryption key given the plaintext and its ciphertext?

    - by Null Pointers etc.
    I'm tasked with creating database tables in Oracle which contain encrypted strings (i.e., the columns are RAW). The strings are encrypted by the application (using AES, 128-bit key) and stored in Oracle, then later retrieved from Oracle and decrypted (i.e., Oracle itself never sees the unencrypted strings). I've come across this one column that will be one of two strings. I'm worried that someone will notice and presumably figure out what those two values to figure out the AES key. For example, if someone sees that the column is either Ciphertext #1 or #2: Ciphertext #1: BF,4F,8B,FE, 60,D8,33,56, 1B,F2,35,72, 49,20,DE,C6. Ciphertext #2: BC,E8,54,BD, F4,B3,36,3B, DD,70,76,45, 29,28,50,07. and knows the corresponding Plaintexts: Plaintext #1 ("Detroit"): 44,00,65,00, 74,00,72,00, 6F,00,69,00, 74,00,00,00. Plaintext #2 ("Chicago"): 43,00,68,00, 69,00,63,00, 61,00,67,00, 6F,00,00,00. can he deduce that the encryption key is "Buffalo"? 42,00,75,00, 66,00,66,00, 61,00,6C,00, 6F,00,00,00. I'm thinking that there should be only one 128-bit key that could convert Plaintext #1 to Ciphertext #1. Does this mean I should go to a 192-bit or 256-bit key instead, or find some other solution? (As an aside, here are two other ciphertexts for the same plaintexts but with a different key.) Ciphertext #1 A ("Detroit"): E4,28,29,E3, 6E,C2,64,FA, A1,F4,F4,96, FC,18,4A,C5. Ciphertext #2 A ("Chicago"): EA,87,30,F0, AC,44,5D,ED, FD,EB,A8,79, 83,59,53,B7.

    Read the article

  • How can I compute the Big-O notation for a given piece of code?

    - by TheNew Rob Mullins
    So I just took a data structure midterm today and I was asked to determine the run time, in Big O notation, of the following nested loop: for (int i = 0; i < n-1; i++) { for(int j = 0; j < i; j++2) { //1 Statement } } I'm having trouble understanding the formula behind determining the run time. I thought that since the inner loop has 1 statement, and using the series equation of: (n * (n - 1)) / 2, I figured it to be: 1n * (n-1) / 2. Thus equaling (n^2 - 1) / 2. And so I generalized the runtime to be O(n^2 / 2). I'm not sure this is right though haha, was I supposed to divide my answer again by 2 since j is being upped in intervals of 2? Or is my answer completely off?

    Read the article

  • SQL Server 2008 table variable error: Must declare the scalar variable "@RESULT".

    - by Trindaz
    I'm using table values for the first time as a parameter to a function in SQL Server 2008. The code below produces this error: Must declare the scalar variable "@RESULT". Why?! I'm declaring it on the first line of the function! ALTER FUNCTION f_Get_Total_Amount_Due( @CUSTOMER_LIST [tpCSFM_CUSTOMER_SET_FOR_MONEY] READONLY ) RETURNS [tpCSFM_CUSTOMER_SET_FOR_MONEY] AS BEGIN --Prepare the return value, start with initial customer list DECLARE @RESULT AS [tpCSFM_CUSTOMER_SET_FOR_MONEY] INSERT INTO @RESULT SELECT * FROM @CUSTOMER_LIST --Todo: populate with real values UPDATE @RESULT SET tpCSAM_MONEY_VALUE = 100 --return total amounts as currency RETURN @RESULT END

    Read the article

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