Search Results

Search found 313 results on 13 pages for 'logically'.

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

  • Utility to LOGICALLY compare two xml files?

    - by Matthew
    Right now we are attempting to build golden configurations for our environment. One piece of software that we use relies on large XML files to contain the bulk of its configuration. We want tot ake our lab environment, catalog it as our "golden configuration" and then be able to audit against that configuration in the future. Since diff is bytewise comparison and NOT logical comparison, we can't use it to compare files in this case (XML is unordered, so it won't work). What I am looking for is something that can parse the two XML files, and compare them element by element. So far we have yet to find any utilities that can do this. OS doesn't matter, I can do it on anything where it will work. The preference is something off the shelf. Any ideas? Edit: One issue we have run into is one vendor's config files will occasionally mention the same element several times, each time with different attributes. Whatever diff utility we use would need to be able to identify either the set of attributes or identify them all as part of one element. Tall order :)

    Read the article

  • how to order string logically

    - by just_name
    Q: I have the following case : set of letters (grades) A,A+,A-,B,B+,B- stored as strings in the database i wanna to order these grades logically from the small one to the big one ,, but this not what happen in real.. because these are strings the order is: A,A+,A- i wanna ASC A-,A,A+ DESC A+,A,A- i bind those grades in drop down list and i wanna these grades with this logical order in it.. is there any idea how to do something like this..

    Read the article

  • Help organising controllers logically

    - by kenny99
    Hi guys, I'm working on a site which i'm developing using an MVC structure. My models will represent all of data in the site, but i'm struggling a bit to decide on a good controller structure. The site will allow users to login/register and see personal data on a number of pages, but also still have access to public pages, e.g FAQs, Contact page etc. This is what I have at the moment... A Template Controller which handles main template display. The basic template for the site will remain the same whether or not you are logged in. A main Website Controller which extends the Template Controller and handles basic authentication. If the user is logged in, a User::control_panel() method is called from the constructor and this builds the control panel which will be present throughout the authenticated session. If user is not logged in, then a different view is loaded instead of the control panel, e.g with a login form. All protected/public page related controllers will extend the website controller. The user homepage has a number of widgets I want to display, which I'm doing via a Home Controller which extends the Website Controller. This controller generates these widgets via the following static calls: $this->template->content->featured_pet = Pet::featured(); $this->template->content->popular_names = Pet::most_popular(); $this->template->content->owner_map = User::generate_map(); $this->template->content->news = News::snippet(); I suppose the first thing I'm unsure about is if the above static calls to controllers (e.g Pet and User) are ok to remain static - these static methods will return views which are loaded into the main template. This is the way I've done things in the past but I'm curious to find out if this is a sensible approach. Other protected pages for signed in users will be similar to the Home Controller. Static pages will be handled by a Page Controller which will also extend the Website Controller, so that it will know whether or not the user control panel or login form should be shown on the left hand side of the template. The protected member only pages will not be routed to the Page Controller, this controller will only handle publicly available pages. One problem I have at the moment, is that if both public and protected pages extend the Website Controller, how do I avoid an infinite loop - for example, the idea is that the website controller should handle authentication then redirect to the requested controller (URL), but this will cause an infinite redirect loop, so i need to come up with a better way of dealing with this. All in all, does this setup make any sense?! Grateful for any feedback.

    Read the article

  • Overloading methods that do logically different things, does this break any major principles?

    - by siva.k
    This is something that's been bugging me for a bit now. In some cases you see code that is a series of overloads, but when you look at the actual implementation you realize they do logically different things. However writing them as overloads allows the caller to ignore this and get the same end result. But would it be more sound to name the methods more explicitly then to write them as overloads? public void LoadWords(string filePath) { var lines = File.ReadAllLines(filePath).ToList(); LoadWords(lines); } public void LoadWords(IEnumerable<string> words) { // loads words into a List<string> based on some filters } Would these methods better serve future developers to be named as LoadWordsFromFile() and LoadWordsFromEnumerable()? It seems unnecessary to me, but if that is better what programming principle would apply here? On the flip side it'd make it so you didn't need to read the signatures to see exactly how you can load the words, which as Uncle Bob says would be a double take. But in general is this type of overloading to be avoided then?

    Read the article

  • How to determine if a file will be logically moved or physically moved.

    - by Frederic Morin
    The facts: When a file is moved, there's two possibilities: The source and destination file are on the same partition and only the file system index is updated The source and destination are on two different file system and the file need to be moved byte per byte. (aka copy on move) The question: How can I determine if a file will be either logically or physically moved ? I'm transferring large files (700+ megs) and would adopt a different behaviors for each situation. Edit: I've already coded a moving file dialog with a worker thread that perform the blocking io call to copy the file a meg at a time. It provide information to the user like rough estimate of the remaining time and transfer rate. The problem is: how do I know if the file can be moved logically before trying to move it physically ?

    Read the article

  • What is Logically and semantically correct, A-grade browsers compatible and W3C valid way to clear f

    - by metal-gear-solid
    What is Logically correct and W3C valid way to clear float? zoom:1 is not valid by W3C and IE8 don't have hash layout problem overflow:hidden and overflow:hidden were not made to do this,as the spec intended overflow to be used <div class="clear"/> is not semantically correct and i don't want to add extra markup. clearfix hack generates content that really hasn’t any semantic value. I've asked many questions and read many articles on this issue but haven't find best way.

    Read the article

  • How can you logically group HTML elements without taking the help of CSS classes ?

    - by Perpetualcoder
    I know that in jQuery you can use something like $(".cssClass") to get all elements with this class. However in plain html and javascript how do you group elements logically? For example: <input id="fee1" data-id="1" data-group="Fees" type="text" value="$15.00"/> <input id="fee2" data-id="2" data-group="Fees" type="text" value="$25.00"/> <input id="fee3" data-id="3" data-group="Fees" type="text" value="$35.00"/> I want to create a javascript function like this: function GetByDataGroup(dataGroup){ /* returns something like [[1,"$15.00"],[2,"$25.00"],[3,"$35.00"]]*/ } EDIT : Due to some political reasons I cant use jQuery or any framework..i know it doesnt make sense :)

    Read the article

  • I am not the most logically-organized person. Do I have any chance at being a good 'low-level' programmer?

    - by user217902
    Background: I am entering college next year. I really enjoy making stuff and solving logical problems, so I'm thinking of majoring in compsci and working in software development. I hope to have the kind of job where I can work with implementing / improving algorithms and data structures on a regular basis.. as opposed to, say, a job that's purely concerned with mashing different libraries together, or 'finding the right APIs for the job'. (Hence the word 'low-level' in the title. No, I don't wish to write assembly all day.) Thing is, I've never been the most logically-sharp person. Thus far I have only worked on hobby projects, but I find that I make the silliest of errors ever so often, and it can take me ages to find it. Like anywhere between three hours to a day to locate a simple segfault, off-by-one error, or other logical mistake. (Of course, I do other things in the meantime, like browsing SO, reddit, and the like..) It's not like I'm 'new' to programming either; I first tried C++ maybe five years ago. My question is: is this normal? Should a programmer with any talent solve it in less time? Having read Spolsky's Smart and gets things done, where he talks about the large variance in programming speed, am I near the bottom of the curve, and therefore destined to work in companies that cannot afford to hire quality programmers? I'd like to think that conceptually I'm okay -- I can grasp algorithms and concepts pretty well, I do fine in math and science, although I probably drop signs in my equations more often than the next guy. Still, grokking concepts makes me happy, and is the reason why I want to work with algorithms. I'm hoping to hear from those of you with real-world programming experience. TL;DR: I make many careless mistakes, should I not consider programming as a career?

    Read the article

  • Should interface only be used for behavior and not to show logical data grouped together?

    - by jags
    Should an interface only be used to specify certain behavior? Would it be wrong to use interface to group logically related data? To me it looks like we should not use interface to group logically related data as structure seems a better fit. A class may be used but class name should indicate something like DTO so that user gets the impression that class does not have any behavior. Please let me know if my assumption is correct. Also, are there any exceptions where interface can be used to group logically related data?

    Read the article

  • Prolog adding and removing list element if non present in second list

    - by logically
    I don't know what I'm missing here. I wan't to add an element if it is in arg1 but not in arg2 and want to remove an element if it is in arg1 but not in arg2. I'm using an if condition with includes function that return true if the element is in the arg2 list, false otherwise. Then use built it predicates append and select to add or remove. I'm getting false to all my objectives searches. I comment and uncomment depending on what predicate I want, add or remove. includes([],_). includes([P|Z],S) :- memberchk(P,S), includes(Z,S). addop([],list,res). addop([P|R],list,res) :- includes(P,s0) - addop(R,list,res) ; append(P,list,res), addop(R,list,res). rem([],list,res). rem([P|R],list,res) :- includes(P,list) - rem(R,list,res) ; select(P,list,res),rem(R,list,res). Thanks for help.

    Read the article

  • Why is a linked list implementation considered linear?

    - by VeeKay
    My apologies for asking such a simple question. Instead of posting such basic question in SO, I felt that this is more apt a question here. I tried finding an answer for this but none of them are logically appealing or convincing to my understanding. Typically, computer memory is always linear. So is the term non linear used for a data structure in a logical sense? If so, to logically achieve non linearity in a linear computer memory, we use pointers. Right? In that case, if pointers are virtual implementations for achieving non linearity, Why would a data structure like linked list be considered linear if in reality the nodes are never physically adjacent?

    Read the article

  • Manageable Services

    This article describes a design, implementation and tooling of model driven WorkflowServices logically centralized in the Repository and physically decentralized for their runtime projecting.

    Read the article

  • Is implementing an interface defined in a subpackage an anti-pattern?

    - by Michael Kjörling
    Let's say I have the following: package me.my.pkg; public interface Something { /* ... couple of methods go here ... */ } and: package me.my; import me.my.pkg.Something; public class SomeClass implements Something { /* ... implementation of Something goes here ... */ /* ... some more method implementations go here too ... */ } That is, the class implementing an interface lives closer to the package hierarchy root than does the interface it implements but they both belong in the same package hierarchy. The reason for this in the particular case I have in mind is that there is a previously-existing package that groups functionality which the Something interface logically belongs to, and the logical (as in both "the one you'd expect" and "the one where it needs to go given the current architecture") implementation class exists previously and lives one level "up" from the logical placement of the interface. The implementing class does not logically belong anywhere under me.my.pkg. In my particular case, the class in question implements several interfaces, but that feels like it doesn't make any (or at least no significant) difference here. I can't decide if this is an acceptable pattern or not. Is it or is it not, and why?

    Read the article

  • What URL scheme would be better for "nested" resources in a RESTful application?

    - by Luke404
    Let's say we want a RESTful web service to manage some logically nested resources, where each instance of resource 'B' is logically contained by an instance of resource 'A'. The first example that comes to mind, working as a sysadmin, is email accounts and their domains: [email protected] [email protected] [email protected] ... What URL scheme would you suggest? At first I'd try: /domain/[domainname] /domain/[domainname]/account/[accountname] is that in line with RESTful principles? or should I go with something like: /domain/[domainname] /account/[account@domainname]/ or anything else?

    Read the article

  • Adding pdb files to VSS

    - by George
    Every time I try to compile my web app, I am prompted if i want to add pdb extensioned files to VSS. I thought pdb files do not belong in VSS see a previous post. Is there any way to prevent them from being added. I cannot even logically delete them from VSS because a previous version has been logically deleted and if I were to delete the current version, the previous version would have to be purged, for which I need vss admin rights that I do not have. I just can't get a handle on how to avoid getting a million files added to VSS that prevent otehr develoeprs from compiling their solutions because they have unchecked out read only copies. Is the only solution to check them in but flip the readonly flag off locally? This is not a good option in my mind.

    Read the article

  • Two different definitions of database schema

    - by AspOnMyNet
    a) I found two definitions of schema: FIRST - A set of information that describes a table is known as a schema, and schemas are used to describe specific tables within a database, as well as entire databases (and the relationship between tables in them, if any). SECOND - A database schema is a way to logically group objects such as tables, views, stored procedures etc. Think of a schema as a container of objects. I assume the two descriptions describe entirely different concepts, which just happen to use the same name? b) A database schema is a way to logically group objects such as tables, views, stored procedures etc. Think of a schema as a container of objects. If I understand the above definition correctly, then database schema is similar to a namespace, only difference being that we can assign access permissions to database schema, while same can’t be done with namespaces? thanx

    Read the article

  • Fun with Aggregates

    - by Paul White
    There are interesting things to be learned from even the simplest queries.  For example, imagine you are given the task of writing a query to list AdventureWorks product names where the product has at least one entry in the transaction history table, but fewer than ten. One possible query to meet that specification is: SELECT p.Name FROM Production.Product AS p JOIN Production.TransactionHistory AS th ON p.ProductID = th.ProductID GROUP BY p.ProductID, p.Name HAVING COUNT_BIG(*) < 10; That query correctly returns 23 rows (execution plan and data sample shown below): The execution plan looks a bit different from the written form of the query: the base tables are accessed in reverse order, and the aggregation is performed before the join.  The general idea is to read all rows from the history table, compute the count of rows grouped by ProductID, merge join the results to the Product table on ProductID, and finally filter to only return rows where the count is less than ten. This ‘fully-optimized’ plan has an estimated cost of around 0.33 units.  The reason for the quote marks there is that this plan is not quite as optimal as it could be – surely it would make sense to push the Filter down past the join too?  To answer that, let’s look at some other ways to formulate this query.  This being SQL, there are any number of ways to write logically-equivalent query specifications, so we’ll just look at a couple of interesting ones.  The first query is an attempt to reverse-engineer T-SQL from the optimized query plan shown above.  It joins the result of pre-aggregating the history table to the Product table before filtering: SELECT p.Name FROM ( SELECT th.ProductID, cnt = COUNT_BIG(*) FROM Production.TransactionHistory AS th GROUP BY th.ProductID ) AS q1 JOIN Production.Product AS p ON p.ProductID = q1.ProductID WHERE q1.cnt < 10; Perhaps a little surprisingly, we get a slightly different execution plan: The results are the same (23 rows) but this time the Filter is pushed below the join!  The optimizer chooses nested loops for the join, because the cardinality estimate for rows passing the Filter is a bit low (estimate 1 versus 23 actual), though you can force a merge join with a hint and the Filter still appears below the join.  In yet another variation, the < 10 predicate can be ‘manually pushed’ by specifying it in a HAVING clause in the “q1” sub-query instead of in the WHERE clause as written above. The reason this predicate can be pushed past the join in this query form, but not in the original formulation is simply an optimizer limitation – it does make efforts (primarily during the simplification phase) to encourage logically-equivalent query specifications to produce the same execution plan, but the implementation is not completely comprehensive. Moving on to a second example, the following query specification results from phrasing the requirement as “list the products where there exists fewer than ten correlated rows in the history table”: SELECT p.Name FROM Production.Product AS p WHERE EXISTS ( SELECT * FROM Production.TransactionHistory AS th WHERE th.ProductID = p.ProductID HAVING COUNT_BIG(*) < 10 ); Unfortunately, this query produces an incorrect result (86 rows): The problem is that it lists products with no history rows, though the reasons are interesting.  The COUNT_BIG(*) in the EXISTS clause is a scalar aggregate (meaning there is no GROUP BY clause) and scalar aggregates always produce a value, even when the input is an empty set.  In the case of the COUNT aggregate, the result of aggregating the empty set is zero (the other standard aggregates produce a NULL).  To make the point really clear, let’s look at product 709, which happens to be one for which no history rows exist: -- Scalar aggregate SELECT COUNT_BIG(*) FROM Production.TransactionHistory AS th WHERE th.ProductID = 709;   -- Vector aggregate SELECT COUNT_BIG(*) FROM Production.TransactionHistory AS th WHERE th.ProductID = 709 GROUP BY th.ProductID; The estimated execution plans for these two statements are almost identical: You might expect the Stream Aggregate to have a Group By for the second statement, but this is not the case.  The query includes an equality comparison to a constant value (709), so all qualified rows are guaranteed to have the same value for ProductID and the Group By is optimized away. In fact there are some minor differences between the two plans (the first is auto-parameterized and qualifies for trivial plan, whereas the second is not auto-parameterized and requires cost-based optimization), but there is nothing to indicate that one is a scalar aggregate and the other is a vector aggregate.  This is something I would like to see exposed in show plan so I suggested it on Connect.  Anyway, the results of running the two queries show the difference at runtime: The scalar aggregate (no GROUP BY) returns a result of zero, whereas the vector aggregate (with a GROUP BY clause) returns nothing at all.  Returning to our EXISTS query, we could ‘fix’ it by changing the HAVING clause to reject rows where the scalar aggregate returns zero: SELECT p.Name FROM Production.Product AS p WHERE EXISTS ( SELECT * FROM Production.TransactionHistory AS th WHERE th.ProductID = p.ProductID HAVING COUNT_BIG(*) BETWEEN 1 AND 9 ); The query now returns the correct 23 rows: Unfortunately, the execution plan is less efficient now – it has an estimated cost of 0.78 compared to 0.33 for the earlier plans.  Let’s try adding a redundant GROUP BY instead of changing the HAVING clause: SELECT p.Name FROM Production.Product AS p WHERE EXISTS ( SELECT * FROM Production.TransactionHistory AS th WHERE th.ProductID = p.ProductID GROUP BY th.ProductID HAVING COUNT_BIG(*) < 10 ); Not only do we now get correct results (23 rows), this is the execution plan: I like to compare that plan to quantum physics: if you don’t find it shocking, you haven’t understood it properly :)  The simple addition of a redundant GROUP BY has resulted in the EXISTS form of the query being transformed into exactly the same optimal plan we found earlier.  What’s more, in SQL Server 2008 and later, we can replace the odd-looking GROUP BY with an explicit GROUP BY on the empty set: SELECT p.Name FROM Production.Product AS p WHERE EXISTS ( SELECT * FROM Production.TransactionHistory AS th WHERE th.ProductID = p.ProductID GROUP BY () HAVING COUNT_BIG(*) < 10 ); I offer that as an alternative because some people find it more intuitive (and it perhaps has more geek value too).  Whichever way you prefer, it’s rather satisfying to note that the result of the sub-query does not exist for a particular correlated value where a vector aggregate is used (the scalar COUNT aggregate always returns a value, even if zero, so it always ‘EXISTS’ regardless which ProductID is logically being evaluated). The following query forms also produce the optimal plan and correct results, so long as a vector aggregate is used (you can probably find more equivalent query forms): WHERE Clause SELECT p.Name FROM Production.Product AS p WHERE ( SELECT COUNT_BIG(*) FROM Production.TransactionHistory AS th WHERE th.ProductID = p.ProductID GROUP BY () ) < 10; APPLY SELECT p.Name FROM Production.Product AS p CROSS APPLY ( SELECT NULL FROM Production.TransactionHistory AS th WHERE th.ProductID = p.ProductID GROUP BY () HAVING COUNT_BIG(*) < 10 ) AS ca (dummy); FROM Clause SELECT q1.Name FROM ( SELECT p.Name, cnt = ( SELECT COUNT_BIG(*) FROM Production.TransactionHistory AS th WHERE th.ProductID = p.ProductID GROUP BY () ) FROM Production.Product AS p ) AS q1 WHERE q1.cnt < 10; This last example uses SUM(1) instead of COUNT and does not require a vector aggregate…you should be able to work out why :) SELECT q.Name FROM ( SELECT p.Name, cnt = ( SELECT SUM(1) FROM Production.TransactionHistory AS th WHERE th.ProductID = p.ProductID ) FROM Production.Product AS p ) AS q WHERE q.cnt < 10; The semantics of SQL aggregates are rather odd in places.  It definitely pays to get to know the rules, and to be careful to check whether your queries are using scalar or vector aggregates.  As we have seen, query plans do not show in which ‘mode’ an aggregate is running and getting it wrong can cause poor performance, wrong results, or both. © 2012 Paul White Twitter: @SQL_Kiwi email: [email protected]

    Read the article

  • Breaking down CS courses for freshmen

    - by Avinash
    I'm a student putting together a slide geared towards freshmen level students who are trying to understand what the importance of various classes in the CS curriculum are. Would it be safe to say that this list is fairly accurate? Data structures: how to store stuff in programs Discrete math: how to think logically Bits & bytes: how to ‘speak’ the machine’s language Advanced data structures: how to store stuff in more ways Algorithms: how to compute things efficiently Operating systems: how to do manage different processes/threads Thanks!

    Read the article

  • Fun with Aggregates

    - by Paul White
    There are interesting things to be learned from even the simplest queries.  For example, imagine you are given the task of writing a query to list AdventureWorks product names where the product has at least one entry in the transaction history table, but fewer than ten. One possible query to meet that specification is: SELECT p.Name FROM Production.Product AS p JOIN Production.TransactionHistory AS th ON p.ProductID = th.ProductID GROUP BY p.ProductID, p.Name HAVING COUNT_BIG(*) < 10; That query correctly returns 23 rows (execution plan and data sample shown below): The execution plan looks a bit different from the written form of the query: the base tables are accessed in reverse order, and the aggregation is performed before the join.  The general idea is to read all rows from the history table, compute the count of rows grouped by ProductID, merge join the results to the Product table on ProductID, and finally filter to only return rows where the count is less than ten. This ‘fully-optimized’ plan has an estimated cost of around 0.33 units.  The reason for the quote marks there is that this plan is not quite as optimal as it could be – surely it would make sense to push the Filter down past the join too?  To answer that, let’s look at some other ways to formulate this query.  This being SQL, there are any number of ways to write logically-equivalent query specifications, so we’ll just look at a couple of interesting ones.  The first query is an attempt to reverse-engineer T-SQL from the optimized query plan shown above.  It joins the result of pre-aggregating the history table to the Product table before filtering: SELECT p.Name FROM ( SELECT th.ProductID, cnt = COUNT_BIG(*) FROM Production.TransactionHistory AS th GROUP BY th.ProductID ) AS q1 JOIN Production.Product AS p ON p.ProductID = q1.ProductID WHERE q1.cnt < 10; Perhaps a little surprisingly, we get a slightly different execution plan: The results are the same (23 rows) but this time the Filter is pushed below the join!  The optimizer chooses nested loops for the join, because the cardinality estimate for rows passing the Filter is a bit low (estimate 1 versus 23 actual), though you can force a merge join with a hint and the Filter still appears below the join.  In yet another variation, the < 10 predicate can be ‘manually pushed’ by specifying it in a HAVING clause in the “q1” sub-query instead of in the WHERE clause as written above. The reason this predicate can be pushed past the join in this query form, but not in the original formulation is simply an optimizer limitation – it does make efforts (primarily during the simplification phase) to encourage logically-equivalent query specifications to produce the same execution plan, but the implementation is not completely comprehensive. Moving on to a second example, the following query specification results from phrasing the requirement as “list the products where there exists fewer than ten correlated rows in the history table”: SELECT p.Name FROM Production.Product AS p WHERE EXISTS ( SELECT * FROM Production.TransactionHistory AS th WHERE th.ProductID = p.ProductID HAVING COUNT_BIG(*) < 10 ); Unfortunately, this query produces an incorrect result (86 rows): The problem is that it lists products with no history rows, though the reasons are interesting.  The COUNT_BIG(*) in the EXISTS clause is a scalar aggregate (meaning there is no GROUP BY clause) and scalar aggregates always produce a value, even when the input is an empty set.  In the case of the COUNT aggregate, the result of aggregating the empty set is zero (the other standard aggregates produce a NULL).  To make the point really clear, let’s look at product 709, which happens to be one for which no history rows exist: -- Scalar aggregate SELECT COUNT_BIG(*) FROM Production.TransactionHistory AS th WHERE th.ProductID = 709;   -- Vector aggregate SELECT COUNT_BIG(*) FROM Production.TransactionHistory AS th WHERE th.ProductID = 709 GROUP BY th.ProductID; The estimated execution plans for these two statements are almost identical: You might expect the Stream Aggregate to have a Group By for the second statement, but this is not the case.  The query includes an equality comparison to a constant value (709), so all qualified rows are guaranteed to have the same value for ProductID and the Group By is optimized away. In fact there are some minor differences between the two plans (the first is auto-parameterized and qualifies for trivial plan, whereas the second is not auto-parameterized and requires cost-based optimization), but there is nothing to indicate that one is a scalar aggregate and the other is a vector aggregate.  This is something I would like to see exposed in show plan so I suggested it on Connect.  Anyway, the results of running the two queries show the difference at runtime: The scalar aggregate (no GROUP BY) returns a result of zero, whereas the vector aggregate (with a GROUP BY clause) returns nothing at all.  Returning to our EXISTS query, we could ‘fix’ it by changing the HAVING clause to reject rows where the scalar aggregate returns zero: SELECT p.Name FROM Production.Product AS p WHERE EXISTS ( SELECT * FROM Production.TransactionHistory AS th WHERE th.ProductID = p.ProductID HAVING COUNT_BIG(*) BETWEEN 1 AND 9 ); The query now returns the correct 23 rows: Unfortunately, the execution plan is less efficient now – it has an estimated cost of 0.78 compared to 0.33 for the earlier plans.  Let’s try adding a redundant GROUP BY instead of changing the HAVING clause: SELECT p.Name FROM Production.Product AS p WHERE EXISTS ( SELECT * FROM Production.TransactionHistory AS th WHERE th.ProductID = p.ProductID GROUP BY th.ProductID HAVING COUNT_BIG(*) < 10 ); Not only do we now get correct results (23 rows), this is the execution plan: I like to compare that plan to quantum physics: if you don’t find it shocking, you haven’t understood it properly :)  The simple addition of a redundant GROUP BY has resulted in the EXISTS form of the query being transformed into exactly the same optimal plan we found earlier.  What’s more, in SQL Server 2008 and later, we can replace the odd-looking GROUP BY with an explicit GROUP BY on the empty set: SELECT p.Name FROM Production.Product AS p WHERE EXISTS ( SELECT * FROM Production.TransactionHistory AS th WHERE th.ProductID = p.ProductID GROUP BY () HAVING COUNT_BIG(*) < 10 ); I offer that as an alternative because some people find it more intuitive (and it perhaps has more geek value too).  Whichever way you prefer, it’s rather satisfying to note that the result of the sub-query does not exist for a particular correlated value where a vector aggregate is used (the scalar COUNT aggregate always returns a value, even if zero, so it always ‘EXISTS’ regardless which ProductID is logically being evaluated). The following query forms also produce the optimal plan and correct results, so long as a vector aggregate is used (you can probably find more equivalent query forms): WHERE Clause SELECT p.Name FROM Production.Product AS p WHERE ( SELECT COUNT_BIG(*) FROM Production.TransactionHistory AS th WHERE th.ProductID = p.ProductID GROUP BY () ) < 10; APPLY SELECT p.Name FROM Production.Product AS p CROSS APPLY ( SELECT NULL FROM Production.TransactionHistory AS th WHERE th.ProductID = p.ProductID GROUP BY () HAVING COUNT_BIG(*) < 10 ) AS ca (dummy); FROM Clause SELECT q1.Name FROM ( SELECT p.Name, cnt = ( SELECT COUNT_BIG(*) FROM Production.TransactionHistory AS th WHERE th.ProductID = p.ProductID GROUP BY () ) FROM Production.Product AS p ) AS q1 WHERE q1.cnt < 10; This last example uses SUM(1) instead of COUNT and does not require a vector aggregate…you should be able to work out why :) SELECT q.Name FROM ( SELECT p.Name, cnt = ( SELECT SUM(1) FROM Production.TransactionHistory AS th WHERE th.ProductID = p.ProductID ) FROM Production.Product AS p ) AS q WHERE q.cnt < 10; The semantics of SQL aggregates are rather odd in places.  It definitely pays to get to know the rules, and to be careful to check whether your queries are using scalar or vector aggregates.  As we have seen, query plans do not show in which ‘mode’ an aggregate is running and getting it wrong can cause poor performance, wrong results, or both. © 2012 Paul White Twitter: @SQL_Kiwi email: [email protected]

    Read the article

  • Licensing issues with using code from samples coming with SDK

    - by Andrey
    Samples coming with SDK are intended to provide best practices. So logically it looks perfectly valid to take code from them. But usually samples come under licenses, for example a lot of samples from Microsoft are released under Microsoft Public License (MS-PL). Samples are usually published to provide best practices and common reusable code. But how can I use code from samples if they are under rather strict licenses?

    Read the article

  • What are some good debugging techniques [closed]

    - by Brad Bruce
    I frequently run into situations where I'm working with other programmers, helping out with debugging issues. Over the years, I've acquired my own techniques for logically breaking down a problem and tracing through it. I see several others who are great at writing programs, but freeze up when debugging. Are there any good resources I can point people to that describe some good debugging techniques?

    Read the article

  • connecting to server with multiple nics in other vlan

    - by Thierry
    I have a windows 2003 server with 3 nics on 3 vlan's (this is in domain 1). nic 1 has a default gateway to my router/firewall (sonicwall). In nic 2 and 3 I have left it empty, because it is advised like that everywhere. Within this domain and VLAN's 1-3 everything works fine. BUT... I have a second domain (domain 2) with a 4th Vlan (all 4 VLAN's connected to the same router/firewall) from which my clients need to access the 2003 server in domain 1 (it's my antivirus management console for both domains). when i ping the server from my vlan4 by it's FQDN, it randomly chooses ip from nic 1, 2 or 3 from my 2003 server. (logically because that server is know in DNS with it's 3 IP-addresses. And that is needed for my VLAN's 1-3) I don't really have a problem with that. BUT, I only get an answer of NIC1 (which sounds logically to me, because it's the only one with a gateway). It is not a router problem, because I'm testing in this phase and ping from vlan4 to any machine in vlan1, 2 or 3 that has 1 nic works just fine. If i add a gateway to nic2 and nic3, I get answer from all 3 nics and this works fine. But I know it's adviced to not do that. Can anyone give me advice in this particular case? Would it really be a problem to add a gateway to nic 2 and 3? They would be pointing to the same router/firewall (only with different ip-address, based on the vlan). Or is there another good solution to fix this problem? Thank's in advance, Thierry.

    Read the article

  • C#/.NET Little Wonders: The Predicate, Comparison, and Converter Generic Delegates

    - by James Michael Hare
    Once again, in this series of posts I look at the parts of the .NET Framework that may seem trivial, but can help improve your code by making it easier to write and maintain. The index of all my past little wonders posts can be found here. In the last three weeks, we examined the Action family of delegates (and delegates in general), the Func family of delegates, and the EventHandler family of delegates and how they can be used to support generic, reusable algorithms and classes. This week I will be completing my series on the generic delegates in the .NET Framework with a discussion of three more, somewhat less used, generic delegates: Predicate<T>, Comparison<T>, and Converter<TInput, TOutput>. These are older generic delegates that were introduced in .NET 2.0, mostly for use in the Array and List<T> classes.  Though older, it’s good to have an understanding of them and their intended purpose.  In addition, you can feel free to use them yourself, though obviously you can also use the equivalents from the Func family of delegates instead. Predicate<T> – delegate for determining matches The Predicate<T> delegate was a very early delegate developed in the .NET 2.0 Framework to determine if an item was a match for some condition in a List<T> or T[].  The methods that tend to use the Predicate<T> include: Find(), FindAll(), FindLast() Uses the Predicate<T> delegate to finds items, in a list/array of type T, that matches the given predicate. FindIndex(), FindLastIndex() Uses the Predicate<T> delegate to find the index of an item, of in a list/array of type T, that matches the given predicate. The signature of the Predicate<T> delegate (ignoring variance for the moment) is: 1: public delegate bool Predicate<T>(T obj); So, this is a delegate type that supports any method taking an item of type T and returning bool.  In addition, there is a semantic understanding that this predicate is supposed to be examining the item supplied to see if it matches a given criteria. 1: // finds first even number (2) 2: var firstEven = Array.Find(numbers, n => (n % 2) == 0); 3:  4: // finds all odd numbers (1, 3, 5, 7, 9) 5: var allEvens = Array.FindAll(numbers, n => (n % 2) == 1); 6:  7: // find index of first multiple of 5 (4) 8: var firstFiveMultiplePos = Array.FindIndex(numbers, n => (n % 5) == 0); This delegate has typically been succeeded in LINQ by the more general Func family, so that Predicate<T> and Func<T, bool> are logically identical.  Strictly speaking, though, they are different types, so a delegate reference of type Predicate<T> cannot be directly assigned to a delegate reference of type Func<T, bool>, though the same method can be assigned to both. 1: // SUCCESS: the same lambda can be assigned to either 2: Predicate<DateTime> isSameDayPred = dt => dt.Date == DateTime.Today; 3: Func<DateTime, bool> isSameDayFunc = dt => dt.Date == DateTime.Today; 4:  5: // ERROR: once they are assigned to a delegate type, they are strongly 6: // typed and cannot be directly assigned to other delegate types. 7: isSameDayPred = isSameDayFunc; When you assign a method to a delegate, all that is required is that the signature matches.  This is why the same method can be assigned to either delegate type since their signatures are the same.  However, once the method has been assigned to a delegate type, it is now a strongly-typed reference to that delegate type, and it cannot be assigned to a different delegate type (beyond the bounds of variance depending on Framework version, of course). Comparison<T> – delegate for determining order Just as the Predicate<T> generic delegate was birthed to give Array and List<T> the ability to perform type-safe matching, the Comparison<T> was birthed to give them the ability to perform type-safe ordering. The Comparison<T> is used in Array and List<T> for: Sort() A form of the Sort() method that takes a comparison delegate; this is an alternate way to custom sort a list/array from having to define custom IComparer<T> classes. The signature for the Comparison<T> delegate looks like (without variance): 1: public delegate int Comparison<T>(T lhs, T rhs); The goal of this delegate is to compare the left-hand-side to the right-hand-side and return a negative number if the lhs < rhs, zero if they are equal, and a positive number if the lhs > rhs.  Generally speaking, null is considered to be the smallest value of any reference type, so null should always be less than non-null, and two null values should be considered equal. In most sort/ordering methods, you must specify an IComparer<T> if you want to do custom sorting/ordering.  The Array and List<T> types, however, also allow for an alternative Comparison<T> delegate to be used instead, essentially, this lets you perform the custom sort without having to have the custom IComparer<T> class defined. It should be noted, however, that the LINQ OrderBy(), and ThenBy() family of methods do not support the Comparison<T> delegate (though one could easily add their own extension methods to create one, or create an IComparer() factory class that generates one from a Comparison<T>). So, given this delegate, we could use it to perform easy sorts on an Array or List<T> based on custom fields.  Say for example we have a data class called Employee with some basic employee information: 1: public sealed class Employee 2: { 3: public string Name { get; set; } 4: public int Id { get; set; } 5: public double Salary { get; set; } 6: } And say we had a List<Employee> that contained data, such as: 1: var employees = new List<Employee> 2: { 3: new Employee { Name = "John Smith", Id = 2, Salary = 37000.0 }, 4: new Employee { Name = "Jane Doe", Id = 1, Salary = 57000.0 }, 5: new Employee { Name = "John Doe", Id = 5, Salary = 60000.0 }, 6: new Employee { Name = "Jane Smith", Id = 3, Salary = 59000.0 } 7: }; Now, using the Comparison<T> delegate form of Sort() on the List<Employee>, we can sort our list many ways: 1: // sort based on employee ID 2: employees.Sort((lhs, rhs) => Comparer<int>.Default.Compare(lhs.Id, rhs.Id)); 3:  4: // sort based on employee name 5: employees.Sort((lhs, rhs) => string.Compare(lhs.Name, rhs.Name)); 6:  7: // sort based on salary, descending (note switched lhs/rhs order for descending) 8: employees.Sort((lhs, rhs) => Comparer<double>.Default.Compare(rhs.Salary, lhs.Salary)); So again, you could use this older delegate, which has a lot of logical meaning to it’s name, or use a generic delegate such as Func<T, T, int> to implement the same sort of behavior.  All this said, one of the reasons, in my opinion, that Comparison<T> isn’t used too often is that it tends to need complex lambdas, and the LINQ ability to order based on projections is much easier to use, though the Array and List<T> sorts tend to be more efficient if you want to perform in-place ordering. Converter<TInput, TOutput> – delegate to convert elements The Converter<TInput, TOutput> delegate is used by the Array and List<T> delegate to specify how to convert elements from an array/list of one type (TInput) to another type (TOutput).  It is used in an array/list for: ConvertAll() Converts all elements from a List<TInput> / TInput[] to a new List<TOutput> / TOutput[]. The delegate signature for Converter<TInput, TOutput> is very straightforward (ignoring variance): 1: public delegate TOutput Converter<TInput, TOutput>(TInput input); So, this delegate’s job is to taken an input item (of type TInput) and convert it to a return result (of type TOutput).  Again, this is logically equivalent to a newer Func delegate with a signature of Func<TInput, TOutput>.  In fact, the latter is how the LINQ conversion methods are defined. So, we could use the ConvertAll() syntax to convert a List<T> or T[] to different types, such as: 1: // get a list of just employee IDs 2: var empIds = employees.ConvertAll(emp => emp.Id); 3:  4: // get a list of all emp salaries, as int instead of double: 5: var empSalaries = employees.ConvertAll(emp => (int)emp.Salary); Note that the expressions above are logically equivalent to using LINQ’s Select() method, which gives you a lot more power: 1: // get a list of just employee IDs 2: var empIds = employees.Select(emp => emp.Id).ToList(); 3:  4: // get a list of all emp salaries, as int instead of double: 5: var empSalaries = employees.Select(emp => (int)emp.Salary).ToList(); The only difference with using LINQ is that many of the methods (including Select()) are deferred execution, which means that often times they will not perform the conversion for an item until it is requested.  This has both pros and cons in that you gain the benefit of not performing work until it is actually needed, but on the flip side if you want the results now, there is overhead in the behind-the-scenes work that support deferred execution (it’s supported by the yield return / yield break keywords in C# which define iterators that maintain current state information). In general, the new LINQ syntax is preferred, but the older Array and List<T> ConvertAll() methods are still around, as is the Converter<TInput, TOutput> delegate. Sidebar: Variance support update in .NET 4.0 Just like our descriptions of Func and Action, these three early generic delegates also support more variance in assignment as of .NET 4.0.  Their new signatures are: 1: // comparison is contravariant on type being compared 2: public delegate int Comparison<in T>(T lhs, T rhs); 3:  4: // converter is contravariant on input and covariant on output 5: public delegate TOutput Contravariant<in TInput, out TOutput>(TInput input); 6:  7: // predicate is contravariant on input 8: public delegate bool Predicate<in T>(T obj); Thus these delegates can now be assigned to delegates allowing for contravariance (going to a more derived type) or covariance (going to a less derived type) based on whether the parameters are input or output, respectively. Summary Today, we wrapped up our generic delegates discussion by looking at three lesser-used delegates: Predicate<T>, Comparison<T>, and Converter<TInput, TOutput>.  All three of these tend to be replaced by their more generic Func equivalents in LINQ, but that doesn’t mean you shouldn’t understand what they do or can’t use them for your own code, as they do contain semantic meanings in their names that sometimes get lost in the more generic Func name.   Tweet Technorati Tags: C#,CSharp,.NET,Little Wonders,delegates,generics,Predicate,Converter,Comparison

    Read the article

  • Xunit: Perform all 'Assert'ions in one test method?

    - by Jörg Battermann
    Is it possible to tell xUnit.net to perform all e.g. Assert.True() in one test method? Basically in some of our use/testcases all assertions belong logically to one and the same 'scope' of tests and I have e.g. something like this: [Fact(DisplayName = "Tr-MissImpl")] public void MissingImplementationTest() { // parse export.xml file var exportXml = Libraries.Utilities.XML.GenericClassDeserializer.DeserializeXmlFile<Libraries.MedTrace.ExportXml>( ExportXmlFile); // compare parsed results with expected ones Assert.True(exportXml.ContainsRequirementKeyWithError("PERS_154163", "E0032A")); Assert.True(exportXml.ContainsRequirementKeyWithError("PERS_155763", "E0032A")); Assert.True(exportXml.ContainsRequirementKeyWithError("PERS_155931", "E0032A")); Assert.True(exportXml.ContainsRequirementKeyWithError("PERS_157145", "E0032A")); Assert.True(exportXml.ContainsRequirementKeyWithError("s_sw_ers_req_A", "E0032A")); Assert.True(exportXml.ContainsRequirementKeyWithError("s_sw_ers_req_C", "E0032A")); Assert.True(exportXml.ContainsRequirementKeyWithError("s_sw_ers_req_D", "E0032A")); } Now if e.g. the first Assert.True(...) fails, the other ones are not executed/checked. I'd rather not break these seven Assertions up into separate methods, since these really do belong together logically (the TC only is 'passed' entirely if all seven are passing all together).

    Read the article

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