Search Results

Search found 765 results on 31 pages for 'discriminated union'.

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

  • Do you play Sudoku ?

    - by Gilles Haro
    Did you know that 11gR2 database could solve a Sudoku puzzle with a single query and, most of the time, and this in less than a second ? The following query shows you how ! Simply pass a flattened Sudoku grid to it a get the result instantaneously ! col "Solution" format a9 col "Problem" format a9 with Iteration( initialSudoku, Step, EmptyPosition ) as ( select initialSudoku, InitialSudoku, instr( InitialSudoku, '-' )        from ( select '--64----2--7-35--1--58-----27---3--4---------4--2---96-----27--7--58-6--3----18--' InitialSudoku from dual )    union all    select initialSudoku        , substr( Step, 1, EmptyPosition - 1 ) || OneDigit || substr( Step, EmptyPosition + 1 )         , instr( Step, '-', EmptyPosition + 1 )      from Iteration         , ( select to_char( rownum ) OneDigit from dual connect by rownum <= 9 ) OneDigit     where EmptyPosition > 0       and not exists          ( select null              from ( select rownum IsPossible from dual connect by rownum <= 9 )             where OneDigit = substr( Step, trunc( ( EmptyPosition - 1 ) / 9 ) * 9 + IsPossible, 1 )   -- One line must contain the 1-9 digits                or OneDigit = substr( Step, mod( EmptyPosition - 1, 9 ) - 8 + IsPossible * 9, 1 )      -- One row must contain the 1-9 digits                or OneDigit = substr( Step, mod( trunc( ( EmptyPosition - 1 ) / 3 ), 3 ) * 3           -- One square must contain the 1-9 digits                            + trunc( ( EmptyPosition - 1 ) / 27 ) * 27 + IsPossible                            + trunc( ( IsPossible - 1 ) / 3 ) * 6 , 1 )          ) ) select initialSudoku "Problem", Step "Solution"    from Iteration  where EmptyPosition = 0 ;   The Magic thing behind this is called Recursive Subquery Factoring. The Oracle documentation gives the following definition: If a subquery_factoring_clause refers to its own query_name in the subquery that defines it, then the subquery_factoring_clause is said to be recursive. A recursive subquery_factoring_clause must contain two query blocks: the first is the anchor member and the second is the recursive member. The anchor member must appear before the recursive member, and it cannot reference query_name. The anchor member can be composed of one or more query blocks combined by the set operators: UNION ALL, UNION, INTERSECT or MINUS. The recursive member must follow the anchor member and must reference query_name exactly once. You must combine the recursive member with the anchor member using the UNION ALL set operator. This new feature is a replacement of this old Hierarchical Query feature that exists in Oracle since the days of Aladdin (well, at least, release 2 of the database in 1977). Everyone remembers the old syntax : select empno, ename, job, mgr, level      from   emp      start with mgr is null      connect by prior empno = mgr; that could/should be rewritten (but not as often as it should) as withT_Emp (empno, name, level) as        ( select empno, ename, job, mgr, level             from   emp             start with mgr is null             connect by prior empno = mgr        ) select * from   T_Emp; which uses the "with" syntax, whose main advantage is to clarify the readability of the query. Although very efficient, this syntax had the disadvantage of being a Non-Ansi Sql Syntax. Ansi-Sql version of Hierarchical Query is called Recursive Subquery Factoring. As of 11gR2, Oracle got compliant with Ansi Sql and introduced Recursive Subquery Factoring. It is basically an extension of the "With" clause that enables recursion. Now, the new syntax for the query would be with T_Emp (empno, name, job, mgr, hierlevel) as       ( select E.empno, E.ename, E.job, E.mgr, 1 from emp E where E.mgr is null         union all         select E.empno, E.ename, E.job, E.mgr, T.hierlevel + 1from emp E                                                                                                            join T_Emp T on ( E.mgr = T.empno ) ) select * from   T_Emp; The anchor member is a replacement for the "start with" The recursive member is processed through iterations. It joins the Source table (EMP) with the result from the Recursive Query itself (T_Emp) Each iteration works with the results of all its preceding iterations.     Iteration 1 works on the results of the first query     Iteration 2 works on the results of Iteration 1 and first query     Iteration 3 works on the results of Iteration 1, Iteration 2 and first query. So, knowing that, the Sudoku query it self-explaining; The anchor member contains the "Problem" : The Initial Sudoku and the Position of the first "hole" in the grid. The recursive member tries to replace the considered hole with any of the 9 digit that would satisfy the 3 rules of sudoku Recursion progress through the grid until it is complete.   Another example :  Fibonaccy Numbers :  un = (un-1) + (un-2) with Fib (u1, u2, depth) as   (select 1, 1, 1 from dual    union all    select u1+u2, u1, depth+1 from Fib where depth<10) select u1 from Fib; Conclusion Oracle brings here a new feature (which, to be honest, already existed on other concurrent systems) and extends the power of the database to new boundaries. It’s now up to developers to try and test it and find more useful application than solving puzzles… But still, solving a Sudoku in less time it takes to say it remains impressive… Interesting links: You might be interested by the following links which cover different aspects of this feature Oracle Documentation Lucas Jellema 's Blog Fibonaci Numbers

    Read the article

  • SQL SERVER – Fix: Error: 8117: Operand data type bit is invalid for sum operator

    - by pinaldave
    Here is the very interesting error I received from a reader. He has very interesting question. He attempted to use BIT filed in the SUM aggregation function and he got following error. He went ahead with various different datatype (i.e. INT, TINYINT etc) and he was able to do the SUM but with BIT he faced the problem. Error Received: Msg 8117, Level 16, State 1, Line 1 Operand data type bit is invalid for sum operator. Reproduction of the error: Set up the environment USE tempdb GO -- Preparing Sample Data CREATE TABLE TestTable (ID INT, Flag BIT) GO INSERT INTO TestTable (ID, Flag) SELECT 1, 0 UNION ALL SELECT 2, 1 UNION ALL SELECT 3, 0 UNION ALL SELECT 4, 1 GO SELECT * FROM TestTable GO Following script will work fine: -- This will work fine SELECT SUM(ID) FROM TestTable GO However following generate error: -- This will generate error SELECT SUM(Flag) FROM TestTable GO The workaround is to convert or cast the BIT to INT: -- Workaround of error SELECT SUM(CONVERT(INT, Flag)) FROM TestTable GO Clean up the setup -- Clean up DROP TABLE TestTable GO Workaround: As mentioned in above script the workaround is to covert the bit datatype to another friendly data types like INT, TINYINT etc. Reference: Pinal Dave (http://blog.sqlauthority.com) Filed under: PostADay, SQL, SQL Authority, SQL Query, SQL Server, SQL Tips and Tricks, T SQL, Technology

    Read the article

  • C Language - \n - creating virus

    - by sagar
    #include<stdio.h> #include<conio.h> union abc { int a; int x; float g; }; struct pqr { int a; int x; float g; } ; void main() { union abc b; struct pqr c; clrscr(); b.a=10; textbackground(2); textcolor(6); cprintf(" A = %d",b.a); printf("\nUnion = %d",sizeof(b)); printf("\nStructure = %d",sizeof(c)); getch(); } Now, Save this program as virus.cpp ( or any name that you like ) I am using Turbo C comiler to complie this program & run from trubo c. ( Ctrl + F9 ) I don't know weather to ask this question at stack over flow or at super user. I am using Windows 7 & I have installed Avira AntiVir virus system. I am not here for any kind of advertisement of microsoft or antivirus system. I am just here for solution of my query. When I tried to run above program - It creates a worm (DOS/Candy). I believe there is nothing wrong in program. Oke.. Now here is something special. Execute the same program with following difference. Here the only difference is space between \n #include<stdio.h> #include<conio.h> union abc { int a; int x; float g; }; struct pqr { int a; int x; float g; } ; void main() { union abc b; struct pqr c; clrscr(); b.a=10; textbackground(2); textcolor(6); cprintf(" A = %d",b.a); printf("\n Union = %d",sizeof(b)); printf("\n Structure = %d",sizeof(c)); getch(); } The difference is only \n and space. Question is "Why my simple program is detected as virus?? " Thanks in advance for sharing your knowledge. Sagar.

    Read the article

  • I love it when a plan comes together

    - by DavidWimbush
    I'm currently working on an application so that our Marketing department can produce most of their own mailing lists without my having to get involved. It was all going well until I got stuck on the bit where the actual SQL query is generated but a rummage in Books Online revealed a very clean solution using some constructs that I had previously dismissed as pointless. Typically we want to email every customer who is in any of the following n groups. Experience shows that a group has the following definition: <people who have done A> [(AND <people who have done B>) | (OR <people who have done C>)] [APART FROM <people who have done D>] When doing these by hand I've been using INNER JOIN for the AND, UNION for the OR, and LEFT JOIN + WHERE D IS NULL for the APART FROM. This would produce two quite different queries: -- Old OR select  A.PersonID from  (   -- A   select  PersonID   from  ...   union  -- OR   -- C   select  PersonID   from  ...   ) AorC   left join  -- APART FROM   (   select  PersonID   from  ...   ) D on D.PersonID = AorC.PersonID where  D.PersonID is null -- Old AND select  distinct main.PersonID from  (   -- A   select  PersonID   from  ...   ) A   inner join  -- AND   (   -- B   select  PersonID   from  ...   ) B on B.PersonID = A.PersonID   left join  -- APART FROM   (   select  PersonID   from  ...   ) D on D.PersonID = A.PersonID where  D.PersonID is null But when I tried to write the code that can generate the SQL for any combination of those (along with all the variables controlling what each SELECT did and what was in all the optional bits of each WHERE clause) my brain started to hurt. Then I remembered reading about the (then new to me) keywords INTERSECT and EXCEPT. At the time I couldn't see what they added but I thought I would have a play and see if they might help. They were perfect for this. Here's the new query structure: -- The way forward select  PersonID from  (     (       (       -- A       select  PersonID       from  ...       )       union      -- OR        intersect  -- AND       (       -- B/C       select  PersonID       from  ...       )     )     except     (     -- D     select  PersonID     from  ...     )   ) x I can easily swap between between UNION and INTERSECT, and omit B, C, or D as necessary. Elegant, clean and readable - pick any 3! Sometimes it really pays to read the manual.

    Read the article

  • LINQ Normalizing data

    - by Brennan Mann
    I am using an OMS that stores up to three line items per record in the database. Below is an example of an order containing five line items. Order Header Order Detail Prod 1 Prod 2 Prod 3 Order Detail Prod 4 Prod 5 One order header record and two detail records. My goal is have a one to one relation for details records(i.e., one detail record per line item). In the past, I used an UNION ALL SQL statement to extract the data. Is there a better approcach to this problem using LINQ? Below is my first attempt at using LINQ. Any feedback, suggestions or recommendations would greatly be appreciated. For what I have read, an UNION statement can tax the process? var orderdetail = (from o in context.ORDERSUBHEADs select new { edpNo = o.EDPNOS_001, price = o.EXTPRICES_001, qty = o.ITEMQTYS_001 } ).Union(from o in context.ORDERSUBHEADs select new { edpNo = o.EDPNOS_002, price = o.EXTPRICES_002, qty = o.ITEMQTYS_002 } ).Union(from o in context.ORDERSUBHEADs select new { edpNo = o.EDPNOS_003, price = o.EXTPRICES_003, qty = o.ITEMQTYS_003 });

    Read the article

  • An implementation of Sharir's or Aurenhammer's deterministic algorithm for calculating the intersect

    - by RGrey
    The problem of finding the intersection/union of 'N' discs/circles on a flat plane was first proposed by M. I. Shamos in his 1978 thesis: Shamos, M. I. “Computational Geometry” Ph.D. thesis, Yale Univ., New Haven, CT 1978. Since then, in 1985, Micha Sharir presented an O(n log2n) time and O(n) space deterministic algorithm for the disc intersection/union problem (based on modified Voronoi diagrams): Sharir, M. Intersection and closest-pair problems for a set of planar discs. SIAM .J Comput. 14 (1985), pp. 448-468. In 1988, Franz Aurenhammer presented a more efficient O(n log n) time and O(n) space algorithm for circle intersection/union using power diagrams (generalizations of Voronoi diagrams): Aurenhammer, F. Improved algorithms for discs and balls using power diagrams. Journal of Algorithms 9 (1985), pp. 151-161. Earlier in 1983, Paul G. Spirakis also presented an O(n^2) time deterministic algorithm, and an O(n) probabilistic algorithm: Spirakis, P.G. Very Fast Algorithms for the Area of the Union of Many Circles. Rep. 98, Dept. Comput. Sci., Courant Institute, New York University, 1983. I've been searching for any implementations of the algorithms above, focusing on computational geometry packages, and I haven't found anything yet. As neither appear trivial to put into practice, it would be really neat if someone could point me in the right direction!

    Read the article

  • How to get max row from table

    - by Odette
    HI I have the following code and a massive problem: WITH CALC1 AS ( SELECT OTQUOT, OTIT01 AS ITEMS, ROUND(OQCQ01 * OVRC01,2) AS COST FROM @[email protected] WHERE OTIT01 <> '' UNION ALL SELECT OTQUOT, OTIT02 AS ITEMS, ROUND(OQCQ02 * OVRC02,2) AS COST FROM @[email protected] WHERE OTIT02 <> '' UNION ALL SELECT OTQUOT, OTIT03 AS ITEMS, ROUND(OQCQ03 * OVRC03,2) AS COST FROM @[email protected] WHERE OTIT03 <> '' UNION ALL SELECT OTQUOT, OTIT04 AS ITEMS, ROUND(OQCQ04 * OVRC04,2) AS COST FROM @[email protected] WHERE OTIT04 <> '' UNION ALL SELECT OTQUOT, OTIT05 AS ITEMS, ROUND(OQCQ05 * OVRC05,2) AS COST FROM @[email protected] WHERE OTIT05 <> '' ORDER BY OTQUOT ASC ) SELECT OTQUOT, ITEMS, MAX(COST) FROM CALC1 WHERE OTQUOT = '04886471' GROUP BY OTQUOT, ITEMS result: 04886471 FEPO5050WCGA24 13.21 04886471 GFRK1650SGL 36.21 04886471 FRA7500GA 12.6 04886471 CGIFESHAZ 11.02 04886471 CGIFESHPDPR 11.79 04886471 GFRK1350DBL 68.23 04886471 RET1.63825GP 32.55 04886471 FRSA 0.12 04886471 GFRK1350SGL 55.94 04886471 GFRK1650DBL 71.89 04886471 FEPO6565WCGA24 16.6 04886471 PCAP5050GA 0.28 04886471 FEPO6565NCPAG24 0.000000 How can I get the result of the row with the Itemcode that has the highest value? In this case I need the result: 04886471 GFRK1650DBL 71.89 but i dont know how to change my code to get that - can anybody please help me?

    Read the article

  • "select * from table" vs "select colA,colB,etc from table" interesting behaviour in SqlServer2005

    - by kristof
    Apology for a lengthy post but I needed to post some code to illustrate the problem. Inspired by the question What is the reason not to use select * ? posted a few minutes ago, I decided to point out some observations of the select * behaviour that I noticed some time ago. So let's the code speak for itself: IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[starTest]') AND type in (N'U')) DROP TABLE [dbo].[starTest] CREATE TABLE [dbo].[starTest]( [id] [int] IDENTITY(1,1) NOT NULL, [A] [varchar](50) NULL, [B] [varchar](50) NULL, [C] [varchar](50) NULL ) ON [PRIMARY] GO insert into dbo.starTest(a,b,c) select 'a1','b1','c1' union all select 'a2','b2','c2' union all select 'a3','b3','c3' go IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vStartest]')) DROP VIEW [dbo].[vStartest] go create view dbo.vStartest as select * from dbo.starTest go go IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vExplicittest]')) DROP VIEW [dbo].[vExplicittest] go create view dbo.[vExplicittest] as select a,b,c from dbo.starTest go select a,b,c from dbo.vStartest select a,b,c from dbo.vExplicitTest IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[starTest]') AND type in (N'U')) DROP TABLE [dbo].[starTest] CREATE TABLE [dbo].[starTest]( [id] [int] IDENTITY(1,1) NOT NULL, [A] [varchar](50) NULL, [B] [varchar](50) NULL, [D] [varchar](50) NULL, [C] [varchar](50) NULL ) ON [PRIMARY] GO insert into dbo.starTest(a,b,d,c) select 'a1','b1','d1','c1' union all select 'a2','b2','d2','c2' union all select 'a3','b3','d3','c3' select a,b,c from dbo.vExplicittest select a,b,c from dbo.vStartest If you execute the following query and look at the results of last 2 select statements, the results that you will see will be as follows: select a,b,c from dbo.vExplicittest a1 b1 c1 a2 b2 c2 a3 b3 c3 select a,b,c from dbo.vStartest a1 b1 d1 a2 b2 d2 a3 b3 d3 As you can see in the results of select a,b,c from dbo.vStartest the data of column c has been replaced with the data from colum d. I believe that is related to the way the views are compiled, my understanding is that the columns are mapped by column indexes (1,2,3,4) as apposed to names. I though I would post it as a warning for people using select * in their sql and experiencing unexpected behaviour. Note: If you rebuild the view that uses select * each time after you modify the table it will work as expected

    Read the article

  • SQL: Order randomly when inserting objects to a table

    - by Ekaterina
    I have an UDF that selects top 6 objects from a table (with a union - code below) and inserts it into another table. (btw SQL 2005) So I paste the UDF below and what the code does is: selects objects for a specific city and add a level to those (from table Europe) union that selection with a selection from the same table for objects that are from the same country and add a level to those From the union, selection is made to get top 6 objects, order by level, so the objects from the same city will be first, and if there aren't any available, then objects from the same country will be returned from the selection. And my problem is, that I want to make a random selection to get random objects from table Europe, but because I insert the result of my selection into a table, I can't use order by newid() or rand() function because they are time-dependent, so I get the following errors: Invalid use of side-effecting or time-dependent operator in 'newid' within a function. Invalid use of side-effecting or time-dependent operator in 'rand' within a function. UDF: ALTER FUNCTION [dbo].[Objects] (@id uniqueidentifier) RETURNS @objects TABLE ( ObjectId uniqueidentifier NOT NULL, InternalId uniqueidentifier NOT NULL ) AS BEGIN declare @city varchar(50) declare @country int select @city = city, @country = country from Europe where internalId = @id insert @objects select @id, internalId from ( select distinct top 6 [level], internalId from ( select top 6 1 as [level], internalId from Europe N4 where N4.city = @city and N4.internalId != @id union select top 6 2 as [level], internalId from Europe N5 where N5.countryId = @country and N5.internalId != @id ) as selection_1 order by [level] ) as selection_2 return END If you have fresh ideas, please share them with me. (Just please, don't suggest to order by newid() or to add a column rand() with seed DateTime (by ms or sthg), because that won't work.)

    Read the article

  • Is it possible to get the parsed text of a SqlCommand with SqlParameters?

    - by Burg
    What I am trying to do is create some arbitrary sql command with parameters, set the values and types of the parameters, and then return the parsed sql command - with parameters included. I will not be directly running this command against a sql database, so no connection should be necessary. So if I ran the example program below, I would hope to see the following text (or something similar): WITH SomeTable (SomeColumn) AS ( SELECT N':)' UNION ALL SELECT N'>:o' UNION ALL SELECT N'^_^' ) SELECT SomeColumn FROM SomeTable And the sample program is: using System; using System.Data; using System.Data.SqlClient; namespace DryEraseConsole { class Program { static void Main(string[] args) { const string COMMAND_TEXT = @" WITH SomeTable (SomeColumn) AS ( SELECT N':)' UNION ALL SELECT N'>:o' UNION ALL SELECT @Value ) SELECT SomeColumn FROM SomeTable "; SqlCommand cmd = new SqlCommand(COMMAND_TEXT); cmd.CommandText = COMMAND_TEXT; cmd.Parameters.Add(new SqlParameter { ParameterName = "@Value", Size = 128, SqlDbType = SqlDbType.NVarChar, Value = "^_^" }); Console.WriteLine(cmd.CommandText); Console.ReadKey(); } } } Is this something that is achievable using the .net standard libraries? Initial searching says no, but I hope I'm wrong.

    Read the article

  • Round date to 10 minutes interval

    - by Peter Lang
    I have a DATE column that I want to round to the next-lower 10 minute interval in a query (see example below). I managed to do it by truncating the seconds and then subtracting the last digit of minutes. WITH test_data AS ( SELECT TO_DATE('2010-01-01 10:00:00', 'YYYY-MM-DD HH24:MI:SS') d FROM dual UNION SELECT TO_DATE('2010-01-01 10:05:00', 'YYYY-MM-DD HH24:MI:SS') d FROM dual UNION SELECT TO_DATE('2010-01-01 10:09:59', 'YYYY-MM-DD HH24:MI:SS') d FROM dual UNION SELECT TO_DATE('2010-01-01 10:10:00', 'YYYY-MM-DD HH24:MI:SS') d FROM dual UNION SELECT TO_DATE('2099-01-01 10:00:33', 'YYYY-MM-DD HH24:MI:SS') d FROM dual ) -- #end of test-data SELECT d, TRUNC(d, 'MI') - MOD(TO_CHAR(d, 'MI'), 10) / (24 * 60) FROM test_data And here is the result: 01.01.2010 10:00:00    01.01.2010 10:00:00 01.01.2010 10:05:00    01.01.2010 10:00:00 01.01.2010 10:09:59    01.01.2010 10:00:00 01.01.2010 10:10:00    01.01.2010 10:10:00 01.01.2099 10:00:33    01.01.2099 10:00:00 Works as expected, but is there a better way? EDIT: I was curious about performance, so I did the following test with 500.000 rows and (not really) random dates. I am going to add the results as comments to the provided solutions. DECLARE t TIMESTAMP := SYSTIMESTAMP; BEGIN FOR i IN ( WITH test_data AS ( SELECT SYSDATE + ROWNUM / 5000 d FROM dual CONNECT BY ROWNUM <= 500000 ) SELECT TRUNC(d, 'MI') - MOD(TO_CHAR(d, 'MI'), 10) / (24 * 60) FROM test_data ) LOOP NULL; END LOOP; dbms_output.put_line( SYSTIMESTAMP - t ); END; This approach took 03.24 s.

    Read the article

  • c++ tables of unions and structures

    - by newbDeveloper
    I was told to write a program, that creates a union and structure, then creates two-element arrays of unions and structures and fills their fields. I have created a union and a structure, but how to fill their fields in arrays ? #include <iostream> #include <stdlib.h> #include <stdio.h> using namespace std; union complex; union complex{ int i1; long double ld1; } u; struct Person { char* name; int age; bool sex; void show(){ printf("name %s, age %2.0d, sex %1d\n", name , age, sex); }; } person; int main(void) { Person *o = new Person[2]; complex *un = new complex[2]; un[0]->i1=i; system("pause"); return 0; } I've tried un[0]-i1=i; but it's not the proper way to do this.

    Read the article

  • Multiple column sorting (SQL SERVER 2005)

    - by Newbie
    I have a table which looks like Col1 col2 col3 col4 col5 1 5 1 4 6 1 4 0 3 7 0 1 5 6 3 1 8 2 1 5 4 3 2 1 4 The script is declare @t table(col1 int, col2 int, col3 int,col4 int,col5 int) insert into @t select 1,5,1,4,6 union all select 1,4,0,3,7 union all select 0,1,5,6,3 union all select 1,8,2,1,5 union all select 4,3,2,1,4 I want the output to be every column being sorted in ascending order i.e. Col1 col2 col3 col4 col5 0 1 0 1 3 1 3 1 1 4 1 4 2 3 5 1 5 2 4 6 4 8 5 6 7 I already solved tye problem by the folowing program Select x1.col1 ,x2.col2 ,x3.col3 ,x4.col4 ,x5.col5 From (Select Row_Number() Over(Order By col1) rn1, col1 From @t)x1 Join(Select Row_Number() Over(Order By col2) rn2, col2 From @t)x2 On x1.rn1=x2.rn2 Join(Select Row_Number() Over(Order By col3) rn3, col3 From @t)x3 On x1.rn1=x3.rn3 Join(Select Row_Number() Over(Order By col4) rn4, col4 From @t)x4 On x1.rn1=x4.rn4 Join(Select Row_Number() Over(Order By col5) rn5, col5 From @t)x5 On x1.rn1=x5.rn5 But I am not happy with this solution. Is there any better way to achieve the same? (Using set based approach) If so, could any one please show an example. Thanks

    Read the article

  • Returning new object, overwrite the existing one in Java

    - by lupin
    Note: This is an assignment. Hi, Ok I have this method that will create a supposedly union of 2 sets. i mport java.io.*; class Set { public int numberOfElements; public String[] setElements; public int maxNumberOfElements; // constructor for our Set class public Set(int numberOfE, int setE, int maxNumberOfE) { this.numberOfElements = numberOfE; this.setElements = new String[setE]; this.maxNumberOfElements = maxNumberOfE; } // Helper method to shorten/remove element of array since we're using basic array instead of ArrayList or HashSet from collection interface :( static String[] removeAt(int k, String[] arr) { final int L = arr.length; String[] ret = new String[L - 1]; System.arraycopy(arr, 0, ret, 0, k); System.arraycopy(arr, k + 1, ret, k, L - k - 1); return ret; } int findElement(String element) { int retval = 0; for ( int i = 0; i < setElements.length; i++) { if ( setElements[i] != null && setElements[i].equals(element) ) { return retval = i; } retval = -1; } return retval; } void add(String newValue) { int elem = findElement(newValue); if( numberOfElements < maxNumberOfElements && elem == -1 ) { setElements[numberOfElements] = newValue; numberOfElements++; } } int getLength() { if ( setElements != null ) { return setElements.length; } else { return 0; } } String[] emptySet() { setElements = new String[0]; return setElements; } Boolean isFull() { Boolean True = new Boolean(true); Boolean False = new Boolean(false); if ( setElements.length == maxNumberOfElements ){ return True; } else { return False; } } Boolean isEmpty() { Boolean True = new Boolean(true); Boolean False = new Boolean(false); if ( setElements.length == 0 ) { return True; } else { return False; } } void remove(String newValue) { for ( int i = 0; i < setElements.length; i++) { if ( setElements[i] != null && setElements[i].equals(newValue) ) { setElements = removeAt(i,setElements); } } } int isAMember(String element) { int retval = -1; for ( int i = 0; i < setElements.length; i++ ) { if (setElements[i] != null && setElements[i].equals(element)) { return retval = i; } } return retval; } void printSet() { for ( int i = 0; i < setElements.length; i++) { if (setElements[i] != null) { System.out.println("Member elements on index: "+ i +" " + setElements[i]); } } } String[] getMember() { String[] tempArray = new String[setElements.length]; for ( int i = 0; i < setElements.length; i++) { if(setElements[i] != null) { tempArray[i] = setElements[i]; } } return tempArray; } Set union(Set x, Set y) { String[] newXtemparray = new String[x.getLength()]; String[] newYtemparray = new String[y.getLength()]; int len = newYtemparray.length + newXtemparray.length; Set temp = new Set(0,len,len); newXtemparray = x.getMember(); newYtemparray = x.getMember(); for(int i = 0; i < newYtemparray.length; i++) { temp.add(newYtemparray[i]); } for(int j = 0; j < newXtemparray.length; j++) { temp.add(newXtemparray[j]); } return temp; } Set difference(Set x, Set y) { String[] newXtemparray = new String[x.getLength()]; String[] newYtemparray = new String[y.getLength()]; int len = newYtemparray.length + newXtemparray.length; Set temp = new Set(0,len,len); newXtemparray = x.getMember(); newYtemparray = x.getMember(); for(int i = 0; i < newXtemparray.length; i++) { temp.add(newYtemparray[i]); } for(int j = 0; j < newYtemparray.length; j++) { int retval = temp.findElement(newYtemparray[j]); if( retval != -1 ) { temp.remove(newYtemparray[j]); } } return temp; } } // This is the SetDemo class that will make use of our Set class class SetDemo { public static void main(String[] args) { //get input from keyboard BufferedReader keyboard; InputStreamReader reader; String temp = ""; reader = new InputStreamReader(System.in); keyboard = new BufferedReader(reader); try { System.out.println("Enter string element to be added" ); temp = keyboard.readLine( ); System.out.println("You entered " + temp ); } catch (IOException IOerr) { System.out.println("There was an error during input"); } /* ************************************************************************** * Test cases for our new created Set class. * ************************************************************************** */ Set setA = new Set(0,10,10); setA.add(temp); setA.add("b"); setA.add("b"); setA.add("hello"); setA.add("world"); setA.add("six"); setA.add("seven"); setA.add("b"); int size = setA.getLength(); System.out.println("Set size is: " + size ); Boolean isempty = setA.isEmpty(); System.out.println("Set is empty? " + isempty ); int ismember = setA.isAMember("sixb"); System.out.println("Element sixb is member of setA? " + ismember ); Boolean output = setA.isFull(); System.out.println("Set is full? " + output ); //setA.printSet(); int index = setA.findElement("world"); System.out.println("Element b located on index: " + index ); setA.remove("b"); //setA.emptySet(); int resize = setA.getLength(); System.out.println("Set size is: " + resize ); //setA.printSet(); Set setB = new Set(0,10,10); setB.add("b"); setB.add("z"); setB.add("x"); setB.add("y"); Set setC = setA.union(setB,setA); System.out.println("Elements of setA"); setA.printSet(); System.out.println("Union of setA and setB"); setC.printSet(); } } The union method works a sense that somehow I can call another method on it but it doesn't do the job, i supposedly would create and union of all elements of setA and setB but it only return element of setB. Sample output follows: java SetDemo Enter string element to be added hello You entered hello Set size is: 10 Set is empty? false Element sixb is member of setA? -1 Set is full? true Element b located on index: 2 Set size is: 9 Elements of setA Member elements on index: 0 hello Member elements on index: 1 world Member elements on index: 2 six Member elements on index: 3 seven Union of setA and setB Member elements on index: 0 b Member elements on index: 1 z Member elements on index: 2 x Member elements on index: 3 y thanks, lupin

    Read the article

  • ms-access: DB engine cannot find input table or query

    - by every_answer_gets_a_point
    here's the query: SELECT * FROM (SELECT [Occurrence Number], [Occurrence Date], [1 0 Preanalytical (Before Testing)], [Cup Type], NULL as [2 0 Analytical (Testing Phase)], [2 0 Area], NULL as [3 0 Postanalytical ( After Testing)],NULL as [4 0 Other], [Practice Code], [Specimen ID #] FROM [Lab Occurrence Form] WHERE NOT ([1 0 Preanalytical (Before Testing)] IS NULL) UNION SELECT [Occurrence Number], [Occurrence Date],NULL, [Cup Type],[2 0 Analytical (Testing Phase)], [2 0 Area], NULL,NULL, [Practice Code], [Specimen ID #] FROM [Lab Occurrence Form] WHERE NOT ([2 0 Analytical (Testing Phase)] IS NULL) UNION SELECT [Occurrence Number], [Occurrence Date],NULL, [Cup Type],NULL, [2 0 Area], [3 0 Postanalytical ( After Testing)],NULL, [Practice Code], [Specimen ID #] FROM [Lab Occurrence Form] WHERE NOT ([3 0 Postanalytical ( After Testing)] IS NULL) UNION SELECT [Occurrence Number], [Occurrence Date],NULL, [Cup Type],NULL, [2 0 Area], NULL, [4 0 Other] FROM [Lab Occurrence Form], [Practice Code], [Specimen ID #] WHERE NOT ([4 0 Other] IS NULL) ) AS mySubQuery ORDER BY mySubQuery.[Occurrence Number]; for some reason it doesnt like [Practice Code]. it's definitely a column in the table so i dont understand the problem. the error is the microsoft office access database engine cannot find the input table or query 'Practice Code'........

    Read the article

  • Using set in Python inside a loop

    - by user210481
    I have the following list in Python: [[1, 2], [3, 4], [4, 6], [2, 7], [3, 9]] I want to group them into [[1,2,7],[3,4,6,7]] My code to do this looks like this: l=[[1, 2], [3, 4], [4, 6], [2, 7], [3, 9]] lf=[] for li in l: for lfi in lf: if lfi.intersection(set(li)): lfi=lfi.union(set(li)) break else: lf.append(set(li)) lf is my final list. I do a loop over l and lf and when I find an intersection between an element from l and another from lf, I would like to merge them (union) But I can't figure out why this is not working. The first to elements of the list l are being inserted with the append command, but the union is not working. My final list lf looks like [set([1, 2]), set([3, 4])] It seems to be something pretty basic, but I'm not familiar with sets. I appreciate any help Thanks

    Read the article

  • Does the optimizer filter subqueries with outer where clauses

    - by Mongus Pong
    Take the following query: select * from ( select a, b from c UNION select a, b from d ) where a = 'mung' Will the optimizer generally work out that I am filtering a on the value 'mung' and consequently filter mung on each of the queries in the subquery. OR will it run each query within the subquery union and return the results to the outer query for filtering (as the query would perhaps suggest) In which case the following query would perform better : select * from ( select a, b from c where a = 'mung' UNION select a, b from d where a = 'mung' ) Obviously query 1 is best for maintenance, but is it sacrificing much performace for this? Which is best?

    Read the article

  • customvalidator onServerValidate not firing

    - by Jamie
    I have a Radio button List and Text Box both with validation. <asp:RadioButtonList ID="member" runat="server" RepeatDirection="Horizontal"> <asp:ListItem>Yes</asp:ListItem> <asp:ListItem>No</asp:ListItem> </asp:RadioButtonList> <asp:requiredfieldvalidator id="unionvalidator" runat="server" controltovalidate="member" errormessage="Required" /> Required if member == "yes" <asp:TextBox runat="server" ID="union"></asp:TextBox> <asp:customvalidator ID="Customvalidator1" runat="server" ValidateEmptyText="true" onServerValidate="UnionValidate" errormessage="Your current union is required" /> My ServerValidate which doesn't fire at all. public void UnionValidate(object source, ServerValidateEventArgs args) { if (member.Text == "yes" && union.Text.Trim() == "") args.IsValid = false; }

    Read the article

  • "select * into table" Will it work for inserting data into existing table

    - by Shantanu Gupta
    I am trying to insert data from one of my existing table into another existing table. Is it possible to insert data into any existing table using select * into query. I think it can be done using union but in that case i need to record all data of my existing table into temporary table, then drop that table and finally than apply union to insert all records into same table eg. select * into #tblExisting from tblExisting drop table tblExisting select * into tblExisting from #tblExisting union tblActualData Here tblExisting is the table where I actually want to store all data tblActualData is the table from where data is to be appended to tblExisting. Is it right method. Do we have some other alternative ?

    Read the article

  • ms-access: missing operator in query expression

    - by every_answer_gets_a_point
    i have this sql statement in access: SELECT * FROM (SELECT [Occurrence Number], [1 0 Preanalytical (Before Testing)], NULL, NULL,NULL FROM [Lab Occurrence Form] WHERE NOT ([1 0 Preanalytical (Before Testing)] IS NULL) UNION SELECT [Occurrence Number], NULL, [2 0 Analytical (Testing Phase)], NULL,NULL FROM [Lab Occurrence Form] WHERE NOT ([2 0 Analytical (Testing Phase)] IS NULL) UNION SELECT [Occurrence Number], NULL, NULL, [3 0 Postanalytical ( After Testing)],NULL FROM [Lab Occurrence Form] WHERE NOT ([3 0 Postanalytical ( After Testing)] IS NULL) UNION SELECT [Occurrence Number], NULL, NULL,NULL [4 0 Other] FROM [Lab Occurrence Form] WHERE NOT ([4 0 Other] IS NULL) ) AS mySubQuery ORDER BY mySubQuery.[Occurrence Number]; everything was fine until i added the last line: SELECT [Occurrence Number], NULL, NULL,NULL [4 0 Other] FROM [Lab Occurrence Form] WHERE NOT ([4 0 Other] IS NULL) i get this error: syntax error (missing operator) in query expression 'NULL [4 0 Other]' anyone have any clues why i am getting this error?

    Read the article

  • How to easily get the unmatched condition in mysql

    - by leivli
    I have a "server" table which has a column named 'SN' in mysql, when do query to retrive servers with some sns from 'sn1' to 'sn10000', we can: select * from server where sn in ('sn1','sn2','sn3',...'sn10000'); If there is only one sn in 'sn1'-'sn10000' which not exists in database, then the query above will retrive 9999 rows of result. The question is how can I easily get which one in 'sn1'-'sn10000' is not exists in database except the additional work, such as handling the result with shell script etc. I have an ugly sql like below can use: select * from (select 'sn1' as sn union select 'sn2' union select 'sn3' .... union select 'sn10000') as SN where not exists (select id from server where server.sn=SN.sn); Is Anyone has other better methods? Thanks.

    Read the article

  • how to avoid sub-query to gain performance

    - by chun
    hi i have a reporting query which have 2 long sub-query SELECT r1.code_centre, r1.libelle_centre, r1.id_equipe, r1.equipe, r1.id_file_attente, r1.libelle_file_attente,r1.id_date, r1.tranche, r1.id_granularite_de_periode,r1.granularite, r1.ContactsTraites, r1.ContactsenParcage, r1.ContactsenComm, r1.DureeTraitementContacts, r1.DureeComm, r1.DureeParcage, r2.AgentsConnectes, r2.DureeConnexion, r2.DureeTraitementAgents, r2.DureePostTraitement FROM ( SELECT cc.id_centre_contact, cc.code_centre, cc.libelle_centre, a.id_equipe, a.equipe, a.id_file_attente, f.libelle_file_attente, a.id_date, g.tranche, g.id_granularite_de_periode, g.granularite, sum(Nb_Contacts_Traites) as ContactsTraites, sum(Nb_Contacts_en_Parcage) as ContactsenParcage, sum(Nb_Contacts_en_Communication) as ContactsenComm, sum(Duree_Traitement/1000) as DureeTraitementContacts, sum(Duree_Communication / 1000 + Duree_Conference / 1000 + Duree_Com_Interagent / 1000) as DureeComm, sum(Duree_Parcage/1000) as DureeParcage FROM agr_synthese_activite_media_fa_agent a, centre_contact cc, direction_contact dc, granularite_de_periode g, media m, file_attente f WHERE m.id_media = a.id_media AND cc.id_centre_contact = a.id_centre_contact AND a.id_direction_contact = dc.id_direction_contact AND dc.direction_contact ='INCOMING' AND a.id_file_attente = f.id_file_attente AND m.media = 'PHONE' AND ( ( g.valeur_min = date_format(a.id_date,'%d/%m') and g.granularite = 'Jour') or ( g.granularite = 'Heure' and a.id_th_heure = g.id_granularite_de_periode) ) GROUP by cc.id_centre_contact, a.id_equipe, a.id_file_attente, a.id_date, g.tranche, g.id_granularite_de_periode) r1, ( (SELECT cc.id_centre_contact,cc.code_centre, cc.libelle_centre, a.id_equipe, a.equipe, a.id_date, g.tranche, g.id_granularite_de_periode,g.granularite, count(distinct a.id_agent) as AgentsConnectes, sum(Duree_Connexion / 1000) as DureeConnexion, sum(Duree_en_Traitement / 1000) as DureeTraitementAgents, sum(Duree_en_PostTraitement / 1000) as DureePostTraitement FROM activite_agent a, centre_contact cc, granularite_de_periode g WHERE ( g.valeur_min = date_format(a.id_date,'%d/%m') and g.granularite = 'Jour') AND cc.id_centre_contact = a.id_centre_contact GROUP BY cc.id_centre_contact, a.id_equipe, a.id_date, g.tranche, g.id_granularite_de_periode ) UNION (SELECT cc.id_centre_contact,cc.code_centre, cc.libelle_centre, a.id_equipe, a.equipe, a.id_date, g.tranche, g.id_granularite_de_periode,g.granularite, count(distinct a.id_agent) as AgentsConnectes, sum(Duree_Connexion / 1000) as DureeConnexion, sum(Duree_en_Traitement / 1000) as DureeTraitementAgents, sum(Duree_en_PostTraitement / 1000) as DureePostTraitement FROM activite_agent a, centre_contact cc, granularite_de_periode g WHERE ( g.granularite = 'Heure' AND a.id_th_heure = g.id_granularite_de_periode) AND cc.id_centre_contact = a.id_centre_contact GROUP BY cc.id_centre_contact,a.id_equipe, a.id_date, g.tranche, g.id_granularite_de_periode) ) r2 WHERE r1.id_centre_contact = r2.id_centre_contact AND r1.id_equipe = r2.id_equipe AND r1.id_date = r2.id_date AND r1.tranche = r2.tranche AND r1.id_granularite_de_periode = r2.id_granularite_de_periode GROUP BY r1.id_centre_contact , r1.id_equipe, r1.id_file_attente, r1.id_date, r1.tranche, r1.id_granularite_de_periode ORDER BY r1.code_centre, r1.libelle_centre, r1.equipe, r1.libelle_file_attente, r1.id_date, r1.id_granularite_de_periode,r1.tranche the EXPLAIN shows | id | select_type | table | type| possible_keys | key | key_len | ref| rows | Extra | '1', 'PRIMARY', '<derived3>', 'ALL', NULL, NULL, NULL, NULL, '2520', 'Using temporary; Using filesort' '1', 'PRIMARY', '<derived2>', 'ALL', NULL, NULL, NULL, NULL, '4378', 'Using where; Using join buffer' '3', 'DERIVED', 'a', 'ALL', 'fk_Activite_Agent_centre_contact', NULL, NULL, NULL, '83433', 'Using temporary; Using filesort' '3', 'DERIVED', 'g', 'ref', 'Index_granularite,Index_Valeur_min', 'Index_Valeur_min', '23', 'func', '1', 'Using where' '3', 'DERIVED', 'cc', 'ALL', 'PRIMARY', NULL, NULL, NULL, '6', 'Using where; Using join buffer' '4', 'UNION', 'g', 'ref', 'PRIMARY,Index_granularite', 'Index_granularite', '23', '', '24', 'Using where; Using temporary; Using filesort' '4', 'UNION', 'a', 'ref', 'fk_Activite_Agent_centre_contact,fk_activite_agent_TH_heure', 'fk_activite_agent_TH_heure', '5', 'reporting_acd.g.Id_Granularite_de_periode', '2979', 'Using where' '4', 'UNION', 'cc', 'ALL', 'PRIMARY', NULL, NULL, NULL, '6', 'Using where; Using join buffer' NULL, 'UNION RESULT', '<union3,4>', 'ALL', NULL, NULL, NULL, NULL, NULL, '' '2', 'DERIVED', 'g', 'range', 'PRIMARY,Index_granularite,Index_Valeur_min', 'Index_granularite', '23', NULL, '389', 'Using where; Using temporary; Using filesort' '2', 'DERIVED', 'a', 'ALL', 'fk_agr_synthese_activite_media_fa_agent_centre_contact,fk_agr_synthese_activite_media_fa_agent_direction_contact,fk_agr_synthese_activite_media_fa_agent_file_attente,fk_agr_synthese_activite_media_fa_agent_media,fk_agr_synthese_activite_media_fa_agent_th_heure', NULL, NULL, NULL, '20903', 'Using where; Using join buffer' '2', 'DERIVED', 'cc', 'eq_ref', 'PRIMARY', 'PRIMARY', '4', 'reporting_acd.a.Id_Centre_Contact', '1', '' '2', 'DERIVED', 'f', 'eq_ref', 'PRIMARY', 'PRIMARY', '4', 'reporting_acd.a.Id_File_Attente', '1', '' '2', 'DERIVED', 'dc', 'eq_ref', 'PRIMARY', 'PRIMARY', '4', 'reporting_acd.a.Id_Direction_Contact', '1', 'Using where' '2', 'DERIVED', 'm', 'eq_ref', 'PRIMARY', 'PRIMARY', '4', 'reporting_acd.a.Id_Media', '1', 'Using where' don't know it very clear, but i think is the problem of seems it take full scaning than i change all the sub-query to views(create view as select sub-query), and the result is the same thanks for any advice

    Read the article

  • Efficiency of data structures in C99 (possibly affected by endianness)

    - by Ninefingers
    Hi All, I have a couple of questions that are all inter-related. Basically, in the algorithm I am implementing a word w is defined as four bytes, so it can be contained whole in a uint32_t. However, during the operation of the algorithm I often need to access the various parts of the word. Now, I can do this in two ways: uint32_t w = 0x11223344; uint8_t a = (w & 0xff000000) >> 24; uint8_t b = (w & 0x00ff0000) >> 16; uint8_t b = (w & 0x0000ff00) >> 8; uint8_t d = (w & 0x000000ff); However, part of me thinks that isn't particularly efficient. I thought a better way would be to use union representation like so: typedef union { struct { uint8_t d; uint8_t c; uint8_t b; uint8_t a; }; uint32_t n; } word32; Using this method I can assign word32 w = 0x11223344; then I can access the various parts as I require (w.a=11 in little endian). However, at this stage I come up against endianness issues, namely, in big endian systems my struct is defined incorrectly so I need to re-order the word prior to it being passed in. This I can do without too much difficulty. My question is, then, is the first part (various bitwise ands and shifts) efficient compared to the implementation using a union? Is there any difference between the two generally? Which way should I go on a modern, x86_64 processor? Is endianness just a red herring here? I could inspect the assembly output of course, but my knowledge of compilers is not brilliant. I would have thought a union would be more efficient as it would essentially convert to memory offsets, like so: mov eax, [r9+8] Would a compiler realise that is what happening in the bit-shift case above? If it matters, I'm using C99, specifically my compiler is clang (llvm). Thanks in advance.

    Read the article

  • Recursive SQL giving ORA-01790

    - by PenFold
    Using Oracle 11g release 2, the following query gives an ORA-01790: expression must have same datatype as corresponding expression: with intervals(time_interval) AS (select trunc(systimestamp) from dual union all select (time_interval + numtodsinterval(10, 'Minute')) from intervals where time_interval < systimestamp) select time_interval from intervals; The error suggests that the datatype of both subqueries of the UNION ALL are returning different datatypes. Even if I cast to TIMESTAMP in each of the subqueries, then I get the same error. What am I missing?

    Read the article

  • rewritten mysql query returning unexpected results, trying to figure out why

    - by dq
    I created a messy query in a hurry a while ago to get a list of product codes. I am now trying to clean up my tables and my code. I recently tried to rewrite the query in order for it to be easier to use and understand. The original query works great, but it requires multiple search strings in order to do one search because it uses UNIONS, and it has a few other issues. My newly modified query is easier to understand, and only requires one search string, but is returning different results. Basically the new query is leaving records out, and I would like to understand why, and how to fix it. Here are the two queries (search strings are all null): Original Query: $query = 'SELECT product_code FROM bus_warehouse_lots WHERE status=\'2\''.$search_string_1 .' UNION SELECT product_code FROM bus_po WHERE status=\'0\''.$search_string_2 .' UNION SELECT bus_warehouse_entries.new_product_code AS product_code FROM (bus_warehouse_entries LEFT JOIN bus_warehouse_transfers ON bus_warehouse_entries.picking_ticket_num=bus_warehouse_transfers.pt_number) LEFT JOIN bus_warehouse_lots ON bus_warehouse_entries.ebooks_lot_id=bus_warehouse_lots.id WHERE bus_warehouse_entries.type=\'6\' AND bus_warehouse_transfers.status=\'0\''.$search_string_3 .' UNION SELECT bus_contracts.main_product AS product_code FROM bus_contracts LEFT JOIN bus_warehouse_lots ON bus_contracts.main_product=bus_warehouse_lots.product_code WHERE bus_contracts.status=\'0\''.$search_string_4 .' UNION SELECT prod_id AS product_code FROM bus_products WHERE last_usage > \''.date('Y-m-d', strtotime('-12 months')).'\''.$search_string_5 .' ORDER BY product_code'; New Query: $query = 'SELECT bus_products.prod_id FROM bus_products' .' LEFT JOIN (bus_warehouse_lots, bus_po, bus_warehouse_entries, bus_contracts) ON (' .'bus_products.prod_id = bus_warehouse_lots.product_code' .' AND bus_products.prod_id = bus_po.product_code' .' AND bus_products.prod_id = bus_warehouse_entries.new_product_code' .' AND bus_products.prod_id = bus_contracts.main_product)' .' LEFT JOIN bus_warehouse_transfers ON' .' bus_warehouse_entries.picking_ticket_num = bus_warehouse_transfers.pt_number' .' WHERE (bus_products.last_usage > \''.date('Y-m-d', strtotime('-12 months')).'\'' .' OR bus_warehouse_lots.status = \'2\'' .' OR bus_po.status = \'0\'' .' OR (bus_warehouse_entries.type = \'6\' AND bus_warehouse_transfers.status = \'0\')' .' OR bus_contracts.status = \'0\')' .$search_string_6 .' GROUP BY bus_products.prod_id' .' ORDER BY bus_products.prod_id';

    Read the article

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