Search Results

Search found 95 results on 4 pages for 'newid'.

Page 2/4 | < Previous Page | 1 2 3 4  | Next Page >

  • mnesia primary key

    - by maryjanne
    Hi I have two tables one notes and one tag and I want to make the id from notes primary key to use it in the tag table, but I don't know where I do wrong. My notes id is generate from another table counter, with the function dirty_update_counter. My function for the id_notes from tag looks like this: Fun = fun() -> mnesia:write(#tag{ id_note =0}) end, mnesia:transaction(Fun). generate_Oid(TableName) when is_atom(TableName) -> F = fun() -> [Oid] = mnesia:read(tag, TableName, write), NewId = Oid#tag.id_note+1, New = Oid#tag{id_note = NewId}, mnesia:write(New), NewId end, mnesia:transaction(F). insert_n(N) when is_record(N, note) -> F = fun() -> {atomic, Id} = generate_Oid(note), New = N#note{id = Id}, mnesia:write(New), New end, mnesia:transaction(F). find_n(Id) when is_integer(Id) -> {atomic, [N]} = mnesia:transaction(fun() -> mnesia:read({note, Id}) end), N. But this function don't increment my field id_note from the table tag, despite the fact that in my note table, my id field is incremented from counter table. Thanks in advance for any help.

    Read the article

  • Best way to randomly select rows *per* column in SQL Server

    - by LesterDove
    A search of SO yields many results describing how to select random rows of data from a database table. My requirement is a bit different, though, in that I'd like to select individual columns from across random rows in the most efficient/random/interesting way possible. To better illustrate: I have a large Customers table, and from that I'd like to generate a bunch of fictitious demo Customer records that aren't real people. I'm thinking of just querying randomly from the Customers table, and then randomly pairing FirstNames with LastNames, Address, City, State, etc. So if this is my real Customer data (simplified): FirstName LastName State ========================== Sally Simpson SD Will Warren WI Mike Malone MN Kelly Kline KS Then I'd generate several records that look like this: FirstName LastName State ========================== Sally Warren MN Kelly Malone SD Etc. My initial approach works, but it lacks the elegance that I'm hoping the final answer will provide. (I'm particularly unhappy with the repetitiveness of the subqueries, and the fact that this solution requires a known/fixed number of fields and therefore isn't reusable.) SELECT FirstName = (SELECT TOP 1 FirstName FROM Customer ORDER BY newid()), LastName= (SELECT TOP 1 LastNameFROM Customer ORDER BY newid()), State = (SELECT TOP 1 State FROM Customer ORDER BY newid()) Thanks!

    Read the article

  • Java appending XML data

    - by Travis
    I've already read through a few of the answers on this site but none of them worked for me. I have an XML file like this: <root> <character> <name>Volstvok</name> <charID>(omitted)</charID> <userID>(omitted)</userID> <apiKey>(omitted)</apiKey> </character> </root> I need to add another <character> somehow. I'm trying this but it does not work: public void addCharacter(String name, int id, int userID, String apiKey){ Element newCharacter = doc.createElement("character"); Element newName = doc.createElement("name"); newName.setTextContent(name); Element newID = doc.createElement("charID"); newID.setTextContent(Integer.toString(id)); Element newUserID = doc.createElement("userID"); newUserID.setTextContent(Integer.toString(userID)); Element newApiKey = doc.createElement("apiKey"); newApiKey.setTextContent(apiKey); //Setup and write newCharacter.appendChild(newName); newCharacter.appendChild(newID); newCharacter.appendChild(newUserID); newCharacter.appendChild(newApiKey); doc.getDocumentElement().appendChild(newCharacter); }

    Read the article

  • Best way to randomly select columns from random rows of SQL results.

    - by LesterDove
    A search of SO yields many results describing how to select random rows of data from a database table. My requirement is a bit different, though, in that I'd like to select individual columns from across random rows in the most efficient/random/interesting way possible. To better illustrate: I have a large Customers table, and from that I'd like to generate a bunch of fictitious demo Customer records that aren't real people. I'm thinking of just querying randomly from the Customers table, and then randomly pairing FirstNames with LastNames, Address, City, State, etc. So if this is my real Customer data (simplified): FirstName LastName State ========================== Sally Simpson SD Will Warren WI Mike Malone MN Kelly Kline KS Then I'd generate several records that look like this: FirstName LastName State ========================== Sally Warren MN Kelly Malone SD Etc. My initial approach works, but it lacks the elegance that I'm hoping the final answer will provide. (I'm particularly unhappy with the repetitiveness of the subqueries, and the fact that this solution requires a known/fixed number of fields and therefore isn't reusable.) SELECT FirstName = (SELECT TOP 1 FirstName FROM Customer ORDER BY newid()), LastName= (SELECT TOP 1 LastNameFROM Customer ORDER BY newid()), State = (SELECT TOP 1 State FROM Customer ORDER BY newid()) Thanks!

    Read the article

  • Jquery draggable not working in chrome/safari

    - by jbatson
    I have created a page that uses ajax calls to load product images. The jquery code for drag, drop and clone would not work when in the index.php page so I moved it to the page that gets called to request the products as each product has drag, drop code created for it. Works fine in FF, even IE but not in Safari or Chrome. Below is the jquery code in load_products.php that gets created when the ajax call is made to load the products. http://tandyleatherfactory.net/ Anyone have any idea why wouldn't work in Safari? $(function() {$("#concho_4_2").draggable({ helper: 'clone', cursor: 'pointer', zIndex: '1001', stop: function(event, ui) { offsetElement = $(ui.helper).offset(); offNewContainer = $('#belts').offset(); var dataId = $(ui.helper).attr('id'); ajaxRequest('http://tandyleatherfactory.net/includes/ahah/add_product.php', 'product=4', '#conchos'); var randomnumber = Math.floor(Math.random()*1000000); var newId = 'concho_4_2_'+randomnumber; $(ui.helper).clone(true).removeAttr('id').attr('id',newId).css("left", offsetElement.left-offNewContainer.left-10).css("top", offsetElement.top-offNewContainer.top-10).appendTo('#belts'); $('#'+newId).draggable(); } });

    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

  • SQL Server: preventing dirty reads in a stored procedure

    - by pcampbell
    Consider a SQL Server database and its two stored procs: *1. A proc that performs 3 important things in a transaction: Create a customer, call a sproc to perform another insert, and conditionally insert a third record with the new identity. BEGIN TRAN INSERT INTO Customer(CustName) (@CustomerName) SELECT @NewID = SCOPE_IDENTITY() EXEC CreateNewCustomerAccount @NewID, @CustomerPhoneNumber IF @InvoiceTotal > 100000 INSERT INTO PreferredCust(InvoiceTotal, CustID) VALUES (@InvoiceTotal, @NewID) COMMIT TRAN *2. A stored proc which polls the Customer table for new entries that don't have a related PreferredCust entry. The client app performs the polling by calling this stored proc every 500ms. A problem has arisen where the polling stored procedure has found an entry in the Customer table, and returned it as part of its results. The problem was that it has picked up that record, I am assuming, as part of a dirty read. The record ended up having an entry in PreferredCust later, and ended up creating a problem downstream. Question How can you explicitly prevent dirty reads by that second stored proc? The environment is SQL Server 2005 with the default configuration out of the box. No other locking hits are given in either of these stored procedures.

    Read the article

  • wxPython - ListCrtl and SQLite3

    - by Dunwitch
    I'm trying to get a SQLite3 DB to populate a wx.ListCrtl. I can get it to print to stdout/stderr without any problem. I just can't seem to figure out how to display the data in the DataWindow/DataList? I'm sure I've made some code mistakes, so any help is appreciated. Main.py import wx import wx.lib.mixins.listctrl as listmix from database import * import sys class DataWindow(wx.Frame): def __init__(self, parent = None): wx.Frame.__init__(self, parent, -1, 'DataList', size=(640,480)) self.win = DataList(self) self.Center() self.Show(True) class DataList(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin, listmix.ColumnSorterMixin): def __init__(self, parent = DataWindow): wx.ListCtrl.__init__( self, parent, -1, style=wx.LC_REPORT|wx.LC_VIRTUAL|wx.LC_HRULES|wx.LC_VRULES) #building the columns self.InsertColumn(0, "Location") self.InsertColumn(1, "Address") self.InsertColumn(2, "Subnet") self.InsertColumn(3, "Gateway") self.SetColumnWidth(0, 100) self.SetColumnWidth(1, 150) self.SetColumnWidth(2, 150) self.SetColumnWidth(3, 150) class MainWindow(wx.Frame): def __init__(self, parent = None, id = -1, title = "MainWindow"): wx.Frame.__init__(self, parent, id, title, size = (800,600), style = wx.DEFAULT_FRAME_STYLE ^ (wx.RESIZE_BORDER)) # StatusBar self.CreateStatusBar() # Filemenu filemenu = wx.Menu() # Filemenu - About menuitem = filemenu.Append(-1, "&About", "Information about this application") self.Bind(wx.EVT_MENU, self.onAbout, menuitem) #Filemenu - Data menuitem = filemenu.Append(-1, "&Data", "Get data") self.Bind(wx.EVT_MENU, self.onData, menuitem) # Filemenu - Seperator filemenu.AppendSeparator() #Filemenu - Exit menuitem = filemenu.Append(-1, "&Exit", "Exit the application") self.Bind(wx.EVT_MENU, self.onExit, menuitem) # Menubar menubar = wx.MenuBar() menubar.Append(filemenu, "&File") self.SetMenuBar(menubar) # Show self.Show(True) self.Center() def onAbout(self, event): pass def onData(self, event): DataWindow(self) callDb = Database() sql = "SELECT rowid, address, subnet, gateway FROM pod1" records = callDb.select(sql) for v in records: print "How do I get the records on the DataList?" #print "%s%s%s" % (v[1],v[2],v[3]) #for v in records: #DataList.InsertStringItem("%s") % (v[0], v[1], v[2]) def onExit(self, event): self.Close() self.Destroy() def onSave(self, event): pass if __name__ == '__main__': app = wx.App() frame = MainWindow(None, -1) frame.Show() app.MainLoop() database.py import os import sqlite3 class Database(object): def __init__(self, db_file="data/data.sqlite"): database_allready_exists = os.path.exists(db_file) self.db = sqlite3.connect(db_file) if not database_allready_exists: self.setupDefaultData() def select(self,sql): cursor = self.db.cursor() cursor.execute(sql) records = cursor.fetchall() cursor.close return records def insert(self,sql): newID = 0 cursor = self.db.cursor() cursor.execute(sql) newID = cursor.lastrowid self.db.commit() cursor.close() return newID def save(self,sql): cursor = self.db.cursor() cursor.execute(sql) self.db.commit() cursor.close() def setupDefaultData(self): pass

    Read the article

  • jQuery/Asp.Net mvc username lookup

    - by MD_Oppenheimer
    OK, for the life of me I can't uderstand why the follwing code is always returning false?? I have debugged with firefox to see what going on, but the function seems to always return false even when the condition username taken is 0(false), here is the jquery code: function CheckAvailability() { showLoader(); $.post("/Account/CheckUsernameAvailability", { userName: $(profile_username).val() }, function(data) { var myObject = eval('(' + data + ')'); var newid = myObject; if (newid == 0) { profile_username_error.removeClass("field_not_valid"); profile_username_error.addClass("field_valid"); $("#validUserName_msg").html("<font color='green'>Available</font>") return true; } else { profile_username_error.addClass("field_not_valid"); profile_username_error.removeClass("field_valid"); $("#validUserName_msg").html("<font color='red'>Taken</font>") return false; } }); } I'm using the /Account/CheckUsernameAvailability to check if a given name is take or not, it not taken(0) should return true, false otherwise.

    Read the article

  • NHibernate Many to Many delete all my data in the table

    - by Daoming Yang
    I would love to thank @Stefan Steinegger and @David helped me out yesterday with many-to-many mapping. I have 3 tables which are "News", "Tags" and "News_Tags" with Many-To-Many relationship and the "News_Tags" is the link table. If I delete one of the news records, the following mappings will delete all my news records which have the same tags. One thing I need to notice, I only allowed unique tag stored in the "Tag" table. This mapping make sense for me, it will delete the tag and related News records, but how can I implement a tagging system with NHibernate? Can anyone give me some suggestion? Many thanks. Daoming. News Mapping: <class name="New" table="News" lazy="false"> <id name="NewID"> <generator class="identity" /> </id> <property name="Title" type="String"></property> <property name="Description" type="String"></property> <set name="TagsList" table="New_Tags" lazy="false" inverse="true" cascade="all"> <key column="NewID" /> <many-to-many class="Tag" column="TagID" /> </set> </class> Tag Mapping: <class name="Tag" table="Tags" lazy="false"> <id name="TagID"> <generator class="identity" /> </id> <property name="TagName" type="String"></property> <property name="DateCreated" type="DateTime"></property> <!--inverse="true" has been defined in the "News mapping"--> <set name="NewsList" table="New_Tags" lazy="false" cascade="all"> <key column="TagID" /> <many-to-many class="New" column="NewID" /> </set> </class>

    Read the article

  • wxpython PyGridTableBase

    - by nozkan
    Hi, I want to use editable choice editor with PyGridTableBase. When I edit a cell it is crashing What is error in my code? My python code: import wx import wx.grid as gridlib class MyTableBase(gridlib.PyGridTableBase): def __init__(self): gridlib.PyGridTableBase.__init__(self) self.data = {0:["value 1", "value 2"], 1:["value 3", "value 4", "value 5"]} self.column_labels = [unicode(u"Label 1"), unicode(u"Label 2"), unicode(u"Label 3")] self._rows = self.GetNumberRows() self._cols = self.GetNumberCols() def GetColLabelValue(self, col): return self.column_labels[col] def GetNumberRows(self): return len(self.data.keys()) def GetNumberCols(self): return len(self.column_labels) def GetValue(self, row, col): try: if col > self.GetNumberCols(): raise IndexError return self.data[row][col] except IndexError: return None def IsEmptyCell(self, row, col): if self.data[row][col] is not None: return True else: return False def GetAttr(self, row, col, kind): attr = gridlib.GridCellAttr() editor = gridlib.GridCellChoiceEditor(["xxx", "yyy", "zzz"], allowOthers = True) attr.SetEditor(editor) attr.IncRef() return attr class MyDataGrid(gridlib.Grid): def __init__(self, parent): gridlib.Grid.__init__(self, parent, wx.NewId()) self.base_table = MyTableBase() self.SetTable(self.base_table) if __name__ == '__main__': app = wx.App(redirect = False) frame = wx.Frame(None, wx.NewId(), title = u"Test") grid_ = MyDataGrid(frame) frame.Show() app.MainLoop()

    Read the article

  • Consolidating values in a junction table

    - by senloe
    I have the following schema: Parcels Segments SegmentsParcels ========= ========== ================= ParcelID SegmentID ParcelID ... Name SegmentID ... id A user of the data wants to consolidate Segments.Names and gave me a list of current Segment.Names mapped to new Segment.Names (all of which currently exist). So now I have this list in a temporary table with the currentID and newID to map to. What I want to do is update the SegmentID in SegmentsParcels based on this map. I could use the statement: update SegmentParcels set segmentID = [newID] from newsegments where segmentID = currentid but this will create some duplicates I have a unique constraint on ParcelID and SegmentID in SegmentParcels. What is the best way to go about this? I considered removing the constraint and then dealing with removing the duplicates (which I did at one point and could probably do again) but I was hoping there was a simpler way.

    Read the article

  • using NEWSEQUENTIALID() with UPDATE Trigger

    - by Ram
    I am adding a new GUID/Uniqueidentifier column to my table. ALTER TABLE table_name ADD VersionNumber UNIQUEIDENTIFIER UNIQUE NOT NULL DEFAULT NEWSEQUENTIALID() GO And when ever a record is updated in the table, I would want to update this column "VersionNumber". So I create a new trigger CREATE TRIGGER [DBO].[TR_TABLE_NAMWE] ON [DBO].[TABLE_NAME] AFTER UPDATE AS BEGIN UPDATE TABLE_NAME SET VERSIONNUMBER=NEWSEQUENTIALID() FROM TABLE_NAME D JOIN INSERTED I ON D.ID=I.ID/* some ID which is used to join*/ END GO But just realized that NEWSEQUENTIALID() can only be used with CREATE TABLE or ALTER TABLE. I got this error The newsequentialid() built-in function can only be used in a DEFAULT expression for a column of type 'uniqueidentifier' in a CREATE TABLE or ALTER TABLE statement. It cannot be combined with other operators to form a complex scalar expression. Is there a workaround for this ? Edit1: Changing NEWSEQUENTIALID() to NEWID() in the trigger solves this, but I am indexing this column and using NEWID() would be sub-optimal

    Read the article

  • How does Contract.Exists add value?

    - by Scott Bilas
    I am just starting to learn about the code contracts library that comes standard with VS2010. One thing I am running into right away is what some of the contract clauses really mean. For example, how are these two statements different? Contract.Requires(!mycollection.Any(a => a.ID == newID)); Contract.Requires(!Contract.Exists(mycollection, a => a.ID == newID)); In other words, what does Contract.Exists do in practical purposes, either for a developer using my function, or for the static code analysis system?

    Read the article

  • PHP: Redirect to the same page, changing $_GET.

    - by Jonathan
    Hi, I have this PHP piece of code that gets $_GET['id'] (a number) and do some stuff with this. When its finished I need to increase that number ($_GET['id']) and redirect to the same page but with the new number (also using $_GET['id']). I am doing something like this: $ID = $_GET['id']; // Some stuff here // and then: $newID = $ID++; header('Location: http://localhost/something/something.php?id='.$newID); exit; The problem here is that the browser stop me from doing it and I get this error from the browser (Firefox) : "The page isn't redirecting properly. Firefox has detected that the server is redirecting the request for this address in a way that will never complete." Some help here please!

    Read the article

  • Sets, Surrogates, Normalisation, Referential Integrity - the Theory with example Scaling considerati

    - by tonyrogerson
    The Slides and Demo's for the SQLBits session I did today at SQL Bits in London are attached. The Agenda was... Thinking in Sets Surrogate Keys ú What they are ú Comparison NEWID, NEWSEQUENTIALID, IDENTITY ú Fragmenation Normalisation ú An introduction – what is it? Why use it? ú Joins – Pre-filter problems, index intersection ú Fragmentation again Referential Integrity ú Optimiser -> Query rewrite ú Locking considerations around Foreign Keys and Declarative RI (using Triggers)...(read more)

    Read the article

  • SQL Server Transaction Marks: Restoring multiple databases to a common relative point

    - by Mladen Prajdic
    We’re all familiar with the ability to restore a database to point in time using the RESTORE WITH STOPAT statement. But what if we have multiple databases that are accessed from one application or are modifying each other? And over multiple instances? And all databases have different workloads? And we want to restore all of the databases to some known common relative point? The catch here is that this common relative point isn’t the same point in time for all databases. This common relative point in time might be now in DB1, now-1 hour in DB2 and yesterday in DB3. And we don’t know the exact times. Let me introduce you to Transaction Marks. When we run a marked transaction using the WITH MARK option a flag is set in the transaction log and a row is added to msdb..logmarkhistory table. When restoring a transaction log backup we can restore to either before or after that marked transaction. The best thing is that we don’t even need to have one database modifying another database. All we have to do is use a marked transaction with the same name in different database. Let’s see how this works with an example. The code comments say what’s going on. USE master GOCREATE DATABASE TestTxMark1GOUSE TestTxMark1GOCREATE TABLE TestTable1( ID INT, VALUE UNIQUEIDENTIFIER) -- insert some data into the table so we can have a starting pointINSERT INTO TestTable1SELECT ROW_NUMBER() OVER(ORDER BY number) AS RN, NULLFROM master..spt_valuesORDER BY RNSELECT *FROM TestTable1GO-- TAKE A FULL BACKUP of the databseBACKUP DATABASE TestTxMark1 TO DISK = 'c:\TestTxMark1.bak'GO USE master GOCREATE DATABASE TestTxMark2GOUSE TestTxMark2GOCREATE TABLE TestTable2( ID INT, VALUE UNIQUEIDENTIFIER)-- insert some data into the table so we can have a starting pointINSERT INTO TestTable2SELECT ROW_NUMBER() OVER(ORDER BY number) AS RN, NEWID()FROM master..spt_valuesORDER BY RNSELECT *FROM TestTable2GO-- TAKE A FULL BACKUP of our databseBACKUP DATABASE TestTxMark2 TO DISK = 'c:\TestTxMark2.bak'GO -- start a marked transaction that modifies both databasesBEGIN TRAN TxDb WITH MARK -- update values from NULL to random value UPDATE TestTable1 SET VALUE = NEWID(); -- update first 100 values from random value -- to NULL in different DB UPDATE TestTxMark2.dbo.TestTable2 SET VALUE = NULL WHERE ID <= 100;COMMITGO     -- some time goes by here -- with various database activity... -- We see two entries for marks in each database. -- This is just informational and has no bearing on the restore itself.SELECT * FROM msdb..logmarkhistory USE masterGO-- create a log backup to restore to mark pointBACKUP LOG TestTxMark1 TO DISK = 'c:\TestTxMark1.trn'GO-- drop the database so we can restore it backDROP DATABASE TestTxMark1GO USE masterGO-- create a log backup to restore to mark pointBACKUP LOG TestTxMark2 TO DISK = 'c:\TestTxMark2.trn'GO-- drop the database so we can restore it backDROP DATABASE TestTxMark2GO -- RESTORE THE DATABASE BACK BEFORE OUR TRANSACTION-- restore the full backup RESTORE DATABASE TestTxMark1 FROM DISK = 'c:\TestTxMark1.bak' WITH NORECOVERY;-- restore the log backup to the transaction markRESTORE LOG TestTxMark1 FROM DISK = 'c:\TestTxMark1.trn' WITH RECOVERY, -- recover to state before the transaction STOPBEFOREMARK = 'TxDb'; -- recover to state after the transaction -- STOPATMARK = 'TxDb';GO -- RESTORE THE DATABASE BACK BEFORE OUR TRANSACTION-- restore the full backup RESTORE DATABASE TestTxMark2 FROM DISK = 'c:\TestTxMark2.bak' WITH NORECOVERY;-- restore the log backup to the transaction markRESTORE LOG TestTxMark2 FROM DISK = 'c:\TestTxMark2.trn' WITH RECOVERY, -- recover to state before the transaction STOPBEFOREMARK = 'TxDb'; -- recover to state after the transaction -- STOPATMARK = 'TxDb';GO USE TestTxMark1-- we restored to time before the transaction -- so we have NULL values in our tableSELECT * FROM TestTable1 USE TestTxMark2-- we restored to time before the transaction -- so we DON'T have NULL values in our tableSELECT * FROM TestTable2   Transaction marks can be used like a crude sync mechanism for cross database operations. With them we can mark our databases with a common “restore to” point so we know we have a valid state between all databases to restore to.

    Read the article

  • SQL to select random mix of rows fairly [migrated]

    - by Matt Sieker
    Here's my problem: I have a set of tables in a database populated with data from a client that contains product information. In addition to the basic product information, there is also information about the manufacturer, and categories for those products (a product can be in one or more categories). These categories are then referred to as "Product Categories", and which stores these products are available at. These tables are updated once a week from a feed from the customer. Since for our purposes, some of the product categories are the same, or closely related for our purposes, there is another level of categories called "General Categories", a general category can have one or more product categories. For the scope of these tables, here's some rough numbers: Data Tables: Products: 475,000 Manufacturers: 1300 Stores: 150 General Categories: 245 Product Categories: 500 Mapping Tables: Product Category -> Product: 655,000 Stores -> Products: 50,000,000 Now, for the actual problem: As part of our software, we need to select n random products, given a store and a general category. However, we also need to ensure a good mix of manufacturers, as in some categories, a single manufacturer dominates the results, and selecting rows at random causes the results to strongly favor that manufacturer. The solution that is currently in place, works for most cases, involves selecting all of the rows that match the store and category criteria, partition them on manufacturer, and include their row number from within their partition, then select from that where the row number for that manufacturer is less than n, and use ROWCOUNT to clamp the total rows returned to n. This query looks something like this: SET ROWCOUNT 6 select p.Id, GeneralCategory_Id, Product_Id, ISNULL(m.DisplayName, m.Name) AS Vendor, MSRP, MemberPrice, FamilyImageName from (select p.Id, gc.Id GeneralCategory_Id, p.Id Product_Id, ctp.Store_id, Manufacturer_id, ROW_NUMBER() OVER (PARTITION BY Manufacturer_id ORDER BY NEWID()) AS 'VendorOrder', MSRP, MemberPrice, FamilyImageName from GeneralCategory gc inner join GeneralCategoriesToProductCategories gctpc ON gc.Id=gctpc.GeneralCategory_Id inner join ProductCategoryToProduct pctp on gctpc.ProductCategory_Id = pctp.ProductCategory_Id inner join Product p on p.Id = pctp.Product_Id inner join StoreToProduct ctp on p.Id = ctp.Product_id where gc.Id = @GeneralCategory and ctp.Store_id=@StoreId and p.Active=1 and p.MemberPrice >0) p inner join Manufacturer m on m.Id = p.Manufacturer_id where VendorOrder <=6 order by NEWID() SET ROWCOUNT 0 (I've tried to somewhat format it to make it cleaner, but I don't think it really helps) Running this query with an execution plan shows that for the majority of these tables, it's doing a Clustered Index Seek. There are two operations that take up roughly 90% of the time: Index Seek (Nonclustered) on StoreToProduct: 17%. This table just contains the key of the store, and the key of the product. It seems that NHibernate decided not to make a composite key when making this table, but I'm not concerned about this at this point, as compared to the other seek... Clustered Index Seek on Product: 69%. I really have no clue how I could make this one more performant. On categories without a lot of products, performance is acceptable (<50ms), however larger categories can take a few hundred ms, with the largest category taking 3s (which has about 170k products). It seems I have two ways to go from this point: Somehow optimize the existing query and table indices to lower the query time. As almost every expensive operation is already a clustered index scan, I don't know what could be done there. The inner query could be tuned to not return all of the possible rows for that category, but I am unsure how to do this, and maintain the requirements (random products, with a good mix of manufacturers) Denormalize this data for the purpose of this query when doing the once a week import. However, I am unsure how to do this and maintain the requirements. Does anyone have any input on either of these items?

    Read the article

  • Subsonic 3 ActiveRecord nested select for NotIn bug?

    - by Junto
    I have the following Subsonic 3.0 query, which contains a nested NotIn query: public List<Order> GetRandomOrdersForNoReason(int shopId, int typeId) { // build query var q = new SubSonic.Query.Select().Top("1") .From("Order") .Where("ShopId") .IsEqualTo(shopId) .And(OrderTable.CustomerId).NotIn( new Subsonic.Query.Select("CustomerId") .From("Customer") .Where("TypeId") .IsNotEqualTo(typeId)) .OrderDesc("NewId()"); // Output query Debug.WriteLine(q.ToString()); // returned typed list return q.ExecuteTypedList<Order>(); } The internal query appears to be incorrect: SELECT TOP 1 * FROM [Order] WHERE ShopId = @0 AND CustomerId NOT IN (SELECT CustomerId FROM [Customer] WHERE TypeId = @0) ORDER BY NewId() ASC You'll notice that both parameters are @0. I'm assuming that the parameters are enumerated (starting at zero), for each "new" Select query. However, in this case where the two Select queries are nested, I would have expected the output to have two parameters named @0 and @1. My query is based on one that Rob Conery gave on his blog as a preview of the "Pakala" query tool that became Subsonic 3. His example was: int records = new Select(Northwind.Product.Schema) .Where("productid") .In( new Select("productid").From(Northwind.Product.Schema) .Where("categoryid").IsEqualTo(5) ) .GetRecordCount(); Has anyone else seen this behavior? Is it a bug, or is this an error or my part? Since I'm new to Subsonic I'm guessing that this probably programmer error on my part but I'd like confirmation if possible.

    Read the article

  • C# - Class Type as Parameter in methods

    - by Claudio
    Hi guys, I'm using SQLite.cs wrapper for helping me with the database and I have this method for create XML from a table, that is working fine. public void GenerateInvoiceXML(string filePath) { var invoices = app.db.Table<Invoice>().ToList(); XmlSerializer serializer = new XmlSerializer( typeof(List<Invoice>) ); TextWriter writer = new StreamWriter(filePath); serializer.Serialize(writer,invoices); writer.Close(); } All tables that I have are defined like this: [Serializable] public class Invoice { [PrimaryKey, AutoIncrement] public int Id { get; set; } public string Supplier {get; set;} public string Date {get; set;} public string PaymentMethod {get; set;} public string Notes {get; set;} public Invoice(int newID) { Id = newID; } public Invoice() { } } But I want to change this method for something like this: public void GenerateInvoiceXML(string filePath, Type table) { var dataForXML = app.db.Table<table>().ToList(); XmlSerializer serializer = new XmlSerializer( typeof(List<table>) ); TextWriter writer = new StreamWriter(filePath); serializer.Serialize(writer,dataForXML); writer.Close(); } Does anybody have an idea how to do it? Kind Regards, Claudio

    Read the article

  • Jquery drag /drop and clone

    - by Sajeev
    Hi I need to achive this .. I have a set of droppable items ( basically I am droping designs on a apparel ) and I am dropping a clone.. If I don't like the dropped object (designs) - I want to delete that by doing something like hidden . But I am unable to do that. Please help me.. here is the code var clone; $(document).ready(function(){ $(".items").draggable({helper: 'clone',cursor: 'hand'}); $(".droparea").droppable({ accept: ".items", hoverClass: 'dropareahover', tolerance: 'pointer', drop: function(ev, ui) { var dropElemId = ui.draggable.attr("id"); var dropElem = ui.draggable.html(); clone = $(dropElem).clone(); // clone it and hold onto the jquery object clone.id="newId"; clone.css("position", "absolute"); clone.css("top", ui.absolutePosition.top); clone.css("left", ui.absolutePosition.left); clone.draggable({ containment: 'parent' ,cursor: 'crosshair'}); $(this).append(clone); alert("done dragging "); /lets assume I have a delete button when I click that clone should dissapear so that I can drop another design - but the following code has no effect //and the item is still visible , how to make it dissapear ? $('#newId').css("visibility","hidden"); } }); });

    Read the article

  • How to use Comparator in Java to sort

    - by Dan
    I learned how to use the comparable but I'm having difficulty with the Comparator. I am having a error in my code: Exception in thread "main" java.lang.ClassCastException: New.People cannot be cast to java.lang.Comparable at java.util.Arrays.mergeSort(Unknown Source) at java.util.Arrays.sort(Unknown Source) at java.util.Collections.sort(Unknown Source) at New.TestPeople.main(TestPeople.java:18) Here is my code: import java.util.Comparator; public class People implements Comparator{ private int id; private String info; private double price; public People(int newid, String newinfo, double newprice){ setid(newid); setinfo(newinfo); setprice(newprice); } public int getid() { return id; } public void setid(int id) { this.id = id; } public String getinfo() { return info; } public void setinfo(String info) { this.info = info; } public double getprice() { return price; } public void setprice(double price) { this.price = price; } public int compare(Object obj1, Object obj2) { Integer p1 = ((People)obj1).getid(); Integer p2 = ((People)obj2).getid(); if (p1 p2 ){ return 1; } else if (p1 < p2){ return -1; } else return 0; } } import java.util.ArrayList; import java.util.Collections; public class TestPeople { public static void main(String[] args) { ArrayList peps = new ArrayList(); peps.add(new People(123, "M", 14.25)); peps.add(new People(234, "M", 6.21)); peps.add(new People(362, "F", 9.23)); peps.add(new People(111, "M", 65.99)); peps.add(new People(535, "F", 9.23)); Collections.sort(peps); for(int i=0;i I believe it has to do something with the casting in the compare method but I was playing around with it and still could not find the solution

    Read the article

  • How to change value inside a JSON string.

    - by Jeremy Roy
    I have a JSON string array of objects like this. [{"id":"4","rank":"adm","title":"title 1"}, {"id":"2","rank":"mod","title":"title 2"}, {"id":"5","rank":"das","title":"title 3"}, {"id":"1","rank":"usr","title":"title 4"}, {"id":"3","rank":"ref","title":"title 5"}] I want to change the title value of it, once the id is matching. So if my variable myID is 5, I want to change the title "title 5" to new title, and so on. And then I get the new JSON array to $("#rangArray").val(jsonStr); Something like $.each(jsonStr, function(k,v) { if (v==myID) { this.title='new title'; $("#myTextArea").val(jsonStr); } }); Here is the full code. $('img.delete').click(function() { var deltid = $(this).attr("id").split('_'); var newID = deltid[1]; var jsonStr = JSON.stringify(myArray); $.each(jsonStr, function(k,v) { if (v==newID) { // how to change the title jsonStr[k].title = 'new title'; alert(jsonStr); $("#rangArray").val(jsonStr); } }); }); The above is not working. Any help please?

    Read the article

  • Capture and handling the tab/Textchanged event in a textbox in asp.net MVC

    - by Icerman
    I have the following code th handle a user name validation on the server side. But the event seems not firing since break points in js or C# code didn't hit. Can anyone point out where I did wrong? Here is the user control which has a user name textbox: <%: Html.TextBox("UserName", Model.Username, new { maxlength = "40", size = "20", tabindex = "1", @onchange = "CheckAvailability()" })% CheckAvailability() is defined in the User.Validation.js and included in the above user control: $(document).ready(function () { function CheckAvailability() { $.post("/Home/Survey/CheckAvailability", { Username: $("#UserName").val() }, function (data) { var myObject = eval('(' + data + ')'); var newid = myObject; if (newid == 0) { $("#usernamelookupresult").html("<font color='green'>Available :-D</font>") } else { $("#usernamelookupresult").html("<font color='red'>Taken :-(</font>") } }); } }); Here is the survey controller function which will have server side validation: [HttpPost] public ActionResult CheckAvailability(string Username) { int Taken = 0; // This is where you add your database lookup if (Username == "abc") { Taken = 1; } return Json(Taken); }

    Read the article

  • Issue with changing an attribute with jquery

    - by rshivers
    Hello, I'm having an issue with changing the attribute for an id and can't seem to figure out what I'm doing wrong. I guess it doesn't help that I'm new to this also. I have a function that tests to make sure that I am pulling the correct id from the row in my form that I have dynamically created. It goes something like this: myFunction() { var id = $(id).attr("id"); alert("This is my id " + id); } This works with no problem and when I click the button assigned to alert me of my id it will give give me the id of the dynamic row in my form. The issue is now when I try to change the id with this: changeId() { var newId = $(id).attr("id", "x"); alert("This is my new id " + newId); } What happens in this case is that it will alert saying "This is my new id [object Object]" instead of giving me the new id. Any suggestions? I'd really appreciate any help with this.

    Read the article

< Previous Page | 1 2 3 4  | Next Page >