Search Results

Search found 7311 results on 293 pages for 'rows'.

Page 17/293 | < Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >

  • 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

  • Display shift when adding rows to UITableView

    - by Kamchatka
    Hello, I have a UITableView displaying an underlying NSFetchedResultsController. When the fetchedResultsController is updated, - (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath { is called. And the following is executed: case NSFetchedResultsChangeInsert: [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:shiftedIndexPath] withRowAnimation:UITableViewRowAnimationFade]; break; The cellForRowAtIndexPath is only called for the new line (which is logical) The problem is however that all the values displayed in the rows of the table view are shifted down. The first row displays its title. The second rows displays the first row's title. The third row the second row's title etc. If I repeat that, the third row will display the second's row title, the fourth the third row's title etc. I don't understand what can happen, especially because cellForRowAtIndexPath is only called for the new line (which is logical) and not for all these lines. Additionally, if I click on these lines which have the wrong title, it opens the right document (didSelectRowAtIndexPath works correctly with the indexPath) Any clue of what could happen? Thanks!

    Read the article

  • R selecting duplicate rows

    - by Matt
    Okay, I'm fairly new to R and I've tried to search the documentation for what I need to do but here is the problem. I have a data.frame called heeds.data in the following form (some columns omitted for simplicity) eval.num, eval.count, ... fitness, fitness.mean, green.h.0, green.v.0, offset.0, green.h.1, green.v.1,...green.h.7, green.v.7, offset.7... And I have selected a row meeting the following criteria: best.fitness <- min(heeds.data$fitness.mean[heeds.data$eval.count = 10]) best.row <- heeds.data[heeds.data$fitness.mean == best.fitness] Now, what I want are all of the other rows with that have columns green.h.0 to offset.7 (a contiguous section of columns) equal to the best.row Basically I'm looking for rows that have some of the conditions the same as the "best" row. I thought I could just do this, heeds.best <- heeds.data$fitness[ heeds.data$green.h.0 == best.row$green.h.0 & ... ] But with 24 columns it seems like a stupid method. Looking for something a bit simpler with less manual typing. Thanks!

    Read the article

  • jQuery dynamically created table rows not responding to events

    - by mithunmo
    I have a table with one row in my HTML file. Now in jQuery I append lot of rows based on the data in the database. But the anchor tag which is created dynamically doesn't respond to events. How do I make this anchor tag respond to events? jQuery part //Appending rows from the Database $('<tr> <td> </td> <td id="log'+i+'"><a href="viewlog.php" target="_blank">log</a></td></tr> ').appendTo('#container'); Event part in jQuery Now when I write a line of code like this it does not respond. $('#container a ').click(function() { alert("Coming here "); }); //HTML <html> <table id="container"> <tr> <td> Name </td> <td> Link </td> </tr> </table> </html>

    Read the article

  • Modify MySQL INSERT statement to omit the insertion of certain rows

    - by dave
    I'm trying to expand a little on a statement that I received help with last week. As you can see, I'm setting up a temporary table and inserting rows of student data from a recently administered test for a few dozen schools. When the rows are inserted, they are sorted by the score (totpct_stu, high to low) and the row_number is added, with 1 representing the highest score, etc. I've learned that there were some problems at school #9999 in SMITH's class (every student made a perfect score and they were the only students in the district to do so). So, I do not want to import SMITH's class. As you can see, I DELETED SMITH's class, but this messed up the row numbering for the remainder of student at the school (e.g., high score row_number is now 20, not 1). How can I modify the INSERT statement so as to not insert this class? Thanks! DROP TEMPORARY TABLE IF EXISTS avgpct ; CREATE TEMPORARY TABLE avgpct_1 ( sch_code VARCHAR(3), schabbrev VARCHAR(75), teachername VARCHAR(75), totpct_stu DECIMAL(5,1), row_number SMALLINT, dummy VARCHAR(75) ); -- ---------------------------------------- INSERT INTO avgpct SELECT sch_code , schabbrev , teachername , totpct_stu , @num := IF( @GROUP = schabbrev, @num + 1, 1 ) AS row_number , @GROUP := schabbrev AS dummy FROM sci_rpt WHERE grade = '05' AND totpct_stu >= 1 -- has a valid score ORDER BY sch_code, totpct_stu DESC ; -- --------------------------------------- -- select * from avgpct ; -- --------------------------------------- DELETE FROM avgpct_1 WHERE sch_code = '9999' AND teachername = 'SMITH' ;

    Read the article

  • how to number t-rows ,when table generated using nested forloop in django templates

    - by stackover
    Hi, This part is from views.py results=[(A,[stuObj1,stuObj2,stuObj3]),(B,[stuObj4,stuObj5,stuObj6]),(C,[stuObj7,stuObj8])] for tup in results: total = tot+len(tup[1]) render_to_response(url,{'results':res , 'total':str(tot),}) this is template code: <th class="name">Name</th> <th class="id">Student ID</th> <th class="grade">Grade</th> {% for tup in results %} {% for student in tup|last %} {% with forloop.parentloop.counter as parentid%} {% with forloop.counter as centerid%} <tbody class="results-body"> <tr> <td>{{student.fname|lower|capfirst}} {{student.lname|lower|capfirst}}</td> <td>{{student.id}}</td> <td>{{tup|first}}</td> </tr> {% endfor %} {% endfor %} Now the problems am having are 1. numbering the rows. Here my problem is am not sure if i can do things like total=total-1 in the templates to get the numbered rows like <td>{{total}}</td> 2.applying css to tr:ever or odd. Whats happening in this case is everytime the loop is running the odd/even ordering is lost. these seems related problems. Any ideas would be great :)

    Read the article

  • Get count of rows in each table while having more than 1 tables

    - by sneha khan
    I have more then one tables on same page and want to add a line show count of each table as below. I tried something but it gives sum of count of all table rows. <table> <tr> <td>Some data</td> <td>More data</td> </tr> <tr> <td>Some data</td> <td>More data</td> </tr> </table> <table> <tr> <td>Some data</td> <td>More data</td> </tr> <tr> <td>Some data</td> <td>More data</td> </tr> </table> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $().ready(function(){ //I want to add a line after each table showing each table row count $("table").after(??? + " rows found."); }); </script>

    Read the article

  • copy rows before updating them to preserve archive in Postgres

    - by punkish
    I am experimenting with creating a table that keeps a version of every row. The idea is to be able to query for how the rows were at any point in time even if the query has JOINs. Consider a system where the primary resource is books, that is, books are queried for, and author info comes along for the ride CREATE TABLE authors ( author_id INTEGER NOT NULL, version INTEGER NOT NULL CHECK (version > 0), author_name TEXT, is_active BOOLEAN DEFAULT '1', modified_on TIMESTAMP DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (author_id, version) ) INSERT INTO authors (author_id, version, author_name) VALUES (1, 1, 'John'), (2, 1, 'Jack'), (3, 1, 'Ernest'); I would like to be able to update the above like so UPDATE authors SET author_name = 'Jack K' WHERE author_id = 1; and end up with 2, 1, Jack, t, 2012-03-29 21:35:00 2, 2, Jack K, t, 2012-03-29 21:37:40 which I can then query with SELECT author_name, modified_on FROM authors WHERE author_id = 2 AND modified_on < '2012-03-29 21:37:00' ORDER BY version DESC LIMIT 1; to get 2, 1, Jack, t, 2012-03-29 21:35:00 Something like the following doesn't really work CREATE OR REPLACE FUNCTION archive_authors() RETURNS TRIGGER AS $archive_author$ BEGIN IF (TG_OP = 'UPDATE') THEN -- The following fails because author_id,version PK already exists INSERT INTO authors (author_id, version, author_name) VALUES (OLD.author_id, OLD.version, OLD.author_name); UPDATE authors SET version = OLD.version + 1 WHERE author_id = OLD.author_id AND version = OLD.version; RETURN NEW; END IF; RETURN NULL; -- result is ignored since this is an AFTER trigger END; $archive_author$ LANGUAGE plpgsql; CREATE TRIGGER archive_author AFTER UPDATE OR DELETE ON authors FOR EACH ROW EXECUTE PROCEDURE archive_authors(); How can I achieve the above? Or, is there a better way to accomplish this? Ideally, I would prefer to not create a shadow table to store the archived rows.

    Read the article

  • Operating on rows and then on columns of a matrix produces code duplication

    - by Chetan
    I have the following (Python) code to check if there are any rows or columns that contain the same value: # Test rows -> # Check each row for a win for i in range(self.height): # For each row ... firstValue = None # Initialize first value placeholder for j in range(self.width): # For each value in the row if (j == 0): # If it's the first value ... firstValue = b[i][j] # Remember it else: # Otherwise ... if b[i][j] != firstValue: # If this is not the same as the first value ... firstValue = None # Reset first value break # Stop checking this row, there's no win here if (firstValue != None): # If first value has been set # First value placeholder now holds the winning player's code return firstValue # Return it # Test columns -> # Check each column for a win for i in range(self.width): # For each column ... firstValue = None # Initialize first value placeholder for j in range(self.height): # For each value in the column if (j == 0): # If it's the first value ... firstValue = b[j][i] # Remember it else: # Otherwise ... if b[j][i] != firstValue: # If this is not the same as the first value ... firstValue = None # Reset first value break # Stop checking this column, there's no win here if (firstValue != None): # If first value has been set # First value placeholder now holds the winning player's code return firstValue # Return it Clearly, there is a lot of code duplication here. How do I refactor this code? Thanks!

    Read the article

  • Cant display button on specific rows of UITableView properly for iPhone

    - by varunwg
    Hi, I am trying to have a button for selected rows of my table. Here is the example code I am using: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *ControlRowIdentifier = @"ControlRowIdentifier"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ControlRowIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ControlRowIdentifier] autorelease]; } if ([indexPath row] > 5) { UIImage *buttonUpImage = [UIImage imageNamed:@"button_up.png"]; UIImage *buttonDownImage = [UIImage imageNamed:@"button_down.png"]; UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; button.frame = CGRectMake(0.0, 0.0, buttonUpImage.size.width, buttonUpImage.size.height); [button setBackgroundImage:buttonUpImage forState:UIControlStateNormal]; [button setBackgroundImage:buttonDownImage forState:UIControlStateHighlighted]; [button setTitle:@"Tap" forState:UIControlStateNormal]; [button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside]; cell.accessoryView = button; } NSUInteger row = [indexPath row]; NSString *rowTitle = [list objectAtIndex:row]; cell.textLabel.text = rowTitle; return cell; } This code works absolutely fine when loaded for 1st time. So, as per the logic it shows 'Tap' button for all rows greater than 5. Problem occurs when I scroll up and down. Once I do that it just starts putting that button at any random row. I dont understand why it does that and it'll be really helpful if someone can give some tips on this. Thanks.

    Read the article

  • Codeigniter Inserting Multidimensional Array as rows in MySQL

    - by RisingSun
    Please Refer to this question I asked Codeigniter Insert Multiple Rows in SQL To restate <tr> <td><input type="text" name="user[0][name]" value=""></td> <td><input type="text" name="user[0][address]" value=""><br></td> <td><input type="text" name="user[0][age]" value=""></td> <td><input type="text" name="user[0][email]" value=""></td> </tr> <tr> <td><input type="text" name="user[1][name]" value=""></td> <td><input type="text" name="user[1][address]" value=""><br></td> <td><input type="text" name="user[1][age]" value=""></td> <td><input type="text" name="user[1][email]" value=""></td> </tr> .......... Can Be Inserted into MySQL as this foreach($_POST['user'] as $user) { $this->db->insert('mytable', $user); } This results in multiple MySQL queries. Is it possible to optimise it further, so that the insert occurs in one query Something like this insert multiple rows via a php array into mysql but taking advantage of codeigniters simpler syntax. Thanks

    Read the article

  • WPF DataGrid populating blank rows on TreeView's SelectedItemChanged

    - by jes9582
    When my DataGrid populates on the TreeView's SelectedItemChanged event it finds the objects and creates the rows accordingly but the rows populate with no text or are just blank. So I know it is finding my objects but it is not displaying them properly. Does anyone see where I made an error or suggest any changes or fixes? Thank you in advance! Here is the CSharp code that is setting the DataGrid's ItemsSource (I am using .dbml and LINQ with Lambda expressions): dgSystemSettings.ItemsSource = (tvSystemConfiguration.SelectedItem as SYSTEM_SETTINGS_GROUP).SYSTEM_SETTINGS_NAMEs.Join(ssdc.SYSTEM_SETTINGS_VALUEs, x => x.SSN_ID, y => y.SSV_SSN_ID, (x, y) => new { SYSTEM_SETTINGS_NAME = x, SYSTEM_SETTINGS_VALUE = y }); And here is the .xaml: <DataGrid Name="dgSystemSettings" AutoGenerateColumns="False" Height="447" Width="513" DockPanel.Dock="Right" ItemsSource="{Binding}" VerticalAlignment="Top" Margin="10,10,0,0"> <DataGrid.Columns> <DataGridTextColumn x:Name="colDisplayName" Header="Name" Binding="{Binding SSN_DISPLAY_NAME}"></DataGridTextColumn> <DataGridTextColumn x:Name="colValue" Header="Value" Binding="{Binding SSV_VALUE}"></DataGridTextColumn> </DataGrid.Columns> </DataGrid>

    Read the article

  • How to delete duplicate/aggregate rows faster in a file using Java (no DB)

    - by S. Singh
    I have a 2GB big text file, it has 5 columns delimited by tab. A row will be called duplicate only if 4 out of 5 columns matches. Right now, I am doing dduping by first loading each coloumn in separate List , then iterating through lists, deleting the duplicate rows as it encountered and aggregating. The problem: it is taking more than 20 hours to process one file. I have 25 such files to process. Can anyone please share their experience, how they would go about doing such dduping? This dduping will be a throw away code. So, I was looking for some quick/dirty solution, to get job done as soon as possible. Here is my pseudo code (roughly) Iterate over the rows i=current_row_no. Iterate over the row no. i+1 to last_row if(col1 matches //find duplicate && col2 matches && col3 matches && col4 matches) { col5List.set(i,get col5); //aggregate } Duplicate example A and B will be duplicate A=(1,1,1,1,1), B=(1,1,1,1,2), C=(2,1,1,1,1) and output would be A=(1,1,1,1,1+2) C=(2,1,1,1,1) [notice that B has been kicked out]

    Read the article

  • jQuery hide all table rows which contain a hidden field matching a value

    - by Famous Nerd
    Though I don't doubt this has been answered I cannot find a great match for my question. I have a table for which I'd like to filter rows based on whether or not they contain a hidden field matching a value. I understand that the technique tends to be "show all rows", "filter the set", "show/hide that filtered set" I have the following jquery but I'm aweful with filter and my filtered set seems to always contain no elements. my table is the usual <table> <tr><td>header></td><td>&nbsp;</tr> <tr> <td>a visible cell</td><td><input type='hidden' id='big-asp.net-id' value='what-im-filtering-on' /> </td> </tr> </table> My goal is to be able to match on tr who's descendent contains a hidden input containing either true or false. this is how I've tried the selector (variations of this) and I'm not even testing for the value yet. function OnFilterChanged(e){ //debugger; var checkedVal = $("#filters input[type='radio']:checked").val(); var allRows = $("#match-grid-container .tabular-data tr"); if(checkedVal=="all"){ allRows.show(); } else if(checkedVal=="matched"){ allRows.show(); allRows.filter(function(){$(this).find("input[type='hidden'][id~='IsAutoMatchHiddenField']")}).hide(); } else if(checkedVal=="unmatched"){ } } Am I way off with the filter? is the $(this) required in the filter so that i can do the descendant searching? Thanks kindly

    Read the article

  • Set the amount of rows JList show (Java)

    - by Alex Cheng
    Hi all. Problem: I have a method that creates a list from the parsed ArrayList. I manage to show the list in the GUI, without scrollbar. However, I am having problem setting it to show only the size of ArrayList. Meaning, say if the size is 6, there should only be 6 rows in the shown List. Below is the code that I am using. I tried setting the visibleRowCount as below but it does not work. I tried printing out the result and it shows that the change is made. private void createSuggestionList(ArrayList<String> str) { int visibleRowCount = str.size(); System.out.println("visibleRowCount " + visibleRowCount); listForSuggestion = new JList(str.toArray()); listForSuggestion.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); listForSuggestion.setSelectedIndex(0); listForSuggestion.setVisibleRowCount(visibleRowCount); System.out.println(listForSuggestion.getVisibleRowCount()); listScrollPane = new JScrollPane(listForSuggestion); MouseListener mouseListener = new MouseAdapter() { @Override public void mouseClicked(MouseEvent mouseEvent) { JList theList = (JList) mouseEvent.getSource(); if (mouseEvent.getClickCount() == 2) { int index = theList.locationToIndex(mouseEvent.getPoint()); if (index >= 0) { Object o = theList.getModel().getElementAt(index); System.out.println("Double-clicked on: " + o.toString()); } } } }; listForSuggestion.addMouseListener(mouseListener); textPane.add(listScrollPane); repaint(); } To summarize: I want the JList to show as many rows as the size of the parsed ArrayList, without a scrollbar. Any ideas? Please help. Thanks. Please let me know if a picture of the problem is needed in case I did not phrase my question correctly.

    Read the article

  • iPhone: Same Rows Repeated in Each Section of Grouped UITableview

    - by Rank Beginner
    I have an app that is a list of tasks, like a to do list. The user configures the tasks and that goes to the SQLite db. The list is displayed in a tableview. The SQL table in question consists of a taskid int, groupname varchar, taskname varchar, lastcompleted datetime, nextdue datetime, weighting integer. I currently have it working by creating an array from each column in the SQL table. In the tableView:cellForRowAtIndexPath: method, I create the controls for each task by binding their values to the array for each column. I want to add configurable task groups that should display as the section titles. I got the task groups to display as the section headers. My problem is that all the task rows are repeated in each group under each header. How do I get the correct rows to show up only under the correct section? I'm really new to development period and took on a hobby of trying to teach myself how to develop iphone apps. So, pretty please, be a little more detailed than you normally would with a professional developer. :)

    Read the article

  • How To Add/Remove Multi Rows In jQuery And Wordpress

    - by SUBSWISS
    Hey All I'm making a wordpress theme options page, and one of the options I want to make is how to add/removes dynamic rows by that the user can make it when he want to add a block. something like this <table id="block" width="350px" border="0"> <tr> <td> 1 </td><!--Nomber of the row--> <td><input type="text" /><br /><label>Title</label></td><!--Title of the row--> <td><input type="text" /><br /><label>IMG Link</label></td><!--Image of the row--> <td><textarea type="textarea" cols="40" rows="2"></textarea><br /><label>Description</label></td> </tr> </table> and the result will be something like this : Please Click Here To See The Image Beside I want to make it saved to wordpress when updating are saved . Thank you. Karar

    Read the article

  • SELECT Statement without duplicate rows on the multiple join tables

    - by theBo
    I have 4 tables built with JOINS and I would like to SELECT DISTINCT rows on the setsTbl.s_id so they always show regardless if there's relational data against them or not!. This is what I have at present which displays the data but doesn't display all of but not the entire distinct row! SELECT setsTbl.s_id, setsTbl.setName, userProfilesTbl.no + ' ' + userProfilesTbl.surname AS Name, trainingTbl.t_date, userAssessmentTbl.o_id FROM userProfilesTbl LEFT OUTER JOIN userAssessmentTbl ON userProfilesTbl.UserId = userAssessmentTbl.UserId FULL OUTER JOIN trainingTbl ON userAssessmentTbl.tt_id = trainingTbl.tt_id RIGHT OUTER JOIN setsTbl ON trainingTbl.s_id = setsTbl.s_id WHERE (userProfilesTbl.st_id=@st_id AND userProfilesTbl.sh_id=@sh_id) AND (DATEPART(yyyy,t_date) = @y_date ) OR (userAssessmentTbl.o_id IS NULL) ORDER BY setName ASC, t_date ASC With this statement I get some of the rows (the ones with data against them) but as stated the s_id field does not return distinct. This following inner select statement works in part when used in SQL Query analyzer and returns pretty much the data i require s_id setName Name o_id ----- ----- ----- ------ 1 100 Barnes 2 2 100 Beardsley 3 3 101 Aldridge 1 4 102 Molby 2 5 102 Whelan 3 but not when used outside of that environment. select * from ( SELECT userProfilesTbl.serviceNo + ' ' + userProfilesTbl.surname AS Name, userProfilesTbl.st_id, userProfilesTbl.sh_id, userAssessmentTbl.o_id, setsTbl.s_id, setsTbl.setName, row_number() over ( partition by setsTbl.s_id order by setsTbl.s_id ) r FROM userProfilesTbl LEFT OUTER JOIN userAssessmentTbl ON userProfilesTbl.UserId = userAssessmentTbl.UserId FULL OUTER JOIN trainingTbl ON userAssessmentTbl.tt_id = trainingTbl.tt_id RIGHT OUTER JOIN setsTbl ON trainingTbl.s_id = setsTbl.s_id ) x where x.r = 1 Not receiving any errors just not displaying the data?

    Read the article

  • faster way to compare rows in a data frame

    - by aguiar
    Consider the data frame below. I want to compare each row with rows below and then take the rows that are equal in more than 3 values. I wrote the code below, but it is very slow if you have a large data frame. How could I do that faster? data <- as.data.frame(matrix(c(10,11,10,13,9,10,11,10,14,9,10,10,8,12,9,10,11,10,13,9,13,13,10,13,9), nrow=5, byrow=T)) rownames(data)<-c("sample_1","sample_2","sample_3","sample_4","sample_5") >data V1 V2 V3 V4 V5 sample_1 10 11 10 13 9 sample_2 10 11 10 14 9 sample_3 10 10 8 12 9 sample_4 10 11 10 13 9 sample_5 13 13 10 13 9 tab <- data.frame(sample = NA, duplicate = NA, matches = NA) dfrow <- 1 for(i in 1:nrow(data)) { sample <- data[i, ] for(j in (i+1):nrow(data)) if(i+1 <= nrow(data)) { matches <- 0 for(V in 1:ncol(data)) { if(data[j,V] == sample[,V]) { matches <- matches + 1 } } if(matches > 3) { duplicate <- data[j, ] pair <- cbind(rownames(sample), rownames(duplicate), matches) tab[dfrow, ] <- pair dfrow <- dfrow + 1 } } } >tab sample duplicate matches 1 sample_1 sample_2 4 2 sample_1 sample_4 5 3 sample_2 sample_4 4

    Read the article

  • Sorting a file with 55K rows and varying Columns

    - by Prasad
    Hi I want to find a programmatic solution using C++. I have a 900 files each of 27MB size. (just to inform about the enormity ). Each file has 55K rows and Varying columns. But the header indicates the columns I want to sort the rows in an order w.r.t to a Column Value. I wrote the sorting algorithm for this (definitely my newbie attempts, you may say). This algorithm is working for few numbers, but fails for larger numbers. Here is the code for the same: basic functions I defined to use inside the main code: int getNumberOfColumns(const string& aline) { int ncols=0; istringstream ss(aline); string s1; while(ss>>s1) ncols++; return ncols; } vector<string> getWordsFromSentence(const string& aline) { vector<string>words; istringstream ss(aline); string tstr; while(ss>>tstr) words.push_back(tstr); return words; } bool findColumnName(vector<string> vs, const string& colName) { vector<string>::iterator it = find(vs.begin(), vs.end(), colName); if ( it != vs.end()) return true; else return false; } int getIndexForColumnName(vector<string> vs, const string& colName) { if ( !findColumnName(vs,colName) ) return -1; else { vector<string>::iterator it = find(vs.begin(), vs.end(), colName); return it - vs.begin(); } } ////////// I like the Recurssive functions - I tried to create a recursive function ///here. This worked for small values , say 20 rows. But for 55K - core dumps void sort2D(vector<string>vn, vector<string> &srt, int columnIndex) { vector<double> pVals; for ( int i = 0; i < vn.size(); i++) { vector<string>meancols = getWordsFromSentence(vn[i]); pVals.push_back(stringToDouble(meancols[columnIndex])); } srt.push_back(vn[max_element(pVals.begin(), pVals.end())-pVals.begin()]); if (vn.size() > 1 ) { vn.erase(vn.begin()+(max_element(pVals.begin(), pVals.end())-pVals.begin()) ); vector<string> vn2 = vn; //cout<<srt[srt.size() -1 ]<<endl; sort2D(vn2 , srt, columnIndex); } } Now the main code: for ( int i = 0; i < TissueNames.size() -1; i++) { for ( int j = i+1; j < TissueNames.size(); j++) { //string fname = path+"/gse7307_Female_rma"+TissueNames[i]+"_"+TissueNames[j]+".txt"; //string fname2 = sortpath2+"/gse7307_Female_rma"+TissueNames[i]+"_"+TissueNames[j]+"Sorted.txt"; string fname = path+"/gse7307_Male_rma"+TissueNames[i]+"_"+TissueNames[j]+".txt"; string fname2 = sortpath2+"/gse7307_Male_rma"+TissueNames[i]+"_"+TissueNames[j]+"4Columns.txt"; //vector<string>AllLinesInFile; BioInputStream fin(fname); string aline; getline(fin,aline); replace (aline.begin(), aline.end(), '"',' '); string headerline = aline; vector<string> header = getWordsFromSentence(aline); int pindex = getIndexForColumnName(header,"p-raw"); int xcindex = getIndexForColumnName(header,"xC"); int xeindex = getIndexForColumnName(header,"xE"); int prbindex = getIndexForColumnName(header,"X"); string newheaderline = "X\txC\txE\tp-raw"; BioOutputStream fsrt(fname2); fsrt<<newheaderline<<endl; int newpindex=3; while ( getline(fin, aline) ){ replace (aline.begin(), aline.end(), '"',' '); istringstream ss2(aline); string tstr; ss2>>tstr; tstr = ss2.str().substr(tstr.length()+1); vector<string> words = getWordsFromSentence(tstr); string values = words[prbindex]+"\t"+words[xcindex]+"\t"+words[xeindex]+"\t"+words[pindex]; AllLinesInFile.push_back(values); } vector<string>SortedLines; sort2D(AllLinesInFile, SortedLines,newpindex); for ( int si = 0; si < SortedLines.size(); si++) fsrt<<SortedLines[si]<<endl; cout<<"["<<i<<","<<j<<"] = "<<SortedLines.size()<<endl; } } can some one suggest me a better way of doing this? why it is failing for larger values. ? The primary function of interest for this query is Sort2D function. thanks for the time and patience. prasad.

    Read the article

  • Update table rows in a non-sequential way using the output of a php script

    - by moviemaniac
    Good evening everybody, this is my very first question and I hope I've done my search in stack's archive at best!!! I need to monitor several devices by querying theyr mysql database and gather some informations. Then these informations are presented to the operator in an html table. I have wrote a php script wich loads devices from a multidimensional array, loops through the array and gather data and create the table. The table structure is the following: <table id="monitoring" class="rt cf"> <thead class="cf"> <tr> <th>Device</th> <th>Company</th> <th>Data1</th> <th>Data2</th> <th>Data3</th> <th>Data4</th> <th>Data5</th> <th>Data6</th> <th>Data7</th> <th>Data8</th> <th>Data9</th> </tr> </thead> <tbody> <tr id="Device1"> <td>Devide 1 name</td> <td>xx</td> <td><img src="/path_to_images/ajax_loader.gif" width="24px" /></td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr id="Device2"> <td>Devide 1 name</td> <td>xx</td> <td><img src="/path_to_images/ajax_loader.gif" width="24px" /></td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr id="DeviceN"> <td>Devide 1 name</td> <td>xx</td> <td><img src="/path_to_images/ajax_loader.gif" width="24px" /></td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> </tbody> </table> The above table is directly populated when I first load the page; then, with a very simple function, i update this table every minute without reloading the page: <script> var auto_refresh = setInterval( function() { jQuery("#monitoring").load('/overview.php').fadeIn("slow"); var UpdateTime= new Date(); var StrUpdateTime; StrUpdateTime= ('0' + UpdateTime.getHours()).slice(-2) + ':' + ('0' + UpdateTime.getMinutes()).slice(-2) + ':' + ('0' + UpdateTime.getSeconds()).slice(-2); jQuery("#progress").text("Updated on: " + StrUpdateTime); }, 60000); </script> The above code runs in a wordpress environment. It comes out that when devices are too much and internet connection is not that fast, the script times out, even if i dramatically increase the timeout period. So it is impossible even to load the page the first time... Therefore I would like to change my code so that I can handle each row as a single entity, with its own refresh period. So when the user first loads the page, he sees n rows (one per device) with the ajax loader image... then an update cycle should start independently for each row, so that the user sees data gathered from each database... then ajax loader when the script is trying to retrieve data, then the gathered data once it has been collected or an error message stating that it is not possible to gather data since hour xx:yy:zz. So rows updating should be somewhat independent from the others, like if each row updating was a single closed process. So that rows updating is not done sequentially from the first row to the last. I hope I've sufficiently detailed my problem. Currently I feel like I am at a dead-end. Could someone please show me somewhere to start from?

    Read the article

  • SQL: Using a CASE Statement to update 1000 rows at once

    - by SoLoGHoST
    Ok, I would like to use a CASE STATEMENT for this, but I am lost with this. Basically, I need to update a ton of rows, but just on the "position" column. I need to update all "position" values from 0 - count(position) for each id_layout_position column per id_layout column. OK, here is a pic of what the table looks like: Now let's say I delete the circled row, this will remove position = 2 and give me: 0, 1, 3, 5, 6, 7, and 4. But I want to add something at the end now and make sure that it has the last possible position, but the positions are already messed up, so I need to reorder them like so before I insert the new row: 0, 1, 2, 3, 4, 5, 6. But it must be ordered by lowest first. So 0 stays at 0, 1 stays at 1, 3 gets changed to 2, the 4 at the end gets changed to a 3, 5 gets changed to 4, 6 gets changed to 5, and 7 gets changed to 6. Hopefully you guys get the picture now. I'm completely lost here. Also, note, this table is tiny compared to how fast it can grow in size, so it needs to be able to do this FAST, thus I was thinking on the CASE STATEMENT for an UPDATE QUERY. Here's what I got for a regular update, but I don't wanna throw this into a foreach loop, as it would take forever to do it. I'm using SMF (Simple Machines Forums), so it might look a little different, but the idea is the same, and CASE statements are supported... $smcFunc['db_query']('', ' UPDATE {db_prefix}dp_positions SET position = {int:position} WHERE id_layout_position = {int:id_layout_position} AND id_layout = {int:id_layout}', array( 'position' => $position++, 'id_layout_position' => (int) $id_layout_position, 'id_layout' => (int) $id_layout, ) ); Anyways, I need to apply some sort of CASE on this so that I can auto-increment by 1 all values that it finds and update to the next possible value. I know I'm doing this wrong, even in this QUERY. But I'm totally lost when it comes to CASES. Here's an example of a CASE being used within SMF, so you can see this and hopefully relate: $conditions = ''; foreach ($postgroups as $id => $min_posts) { $conditions .= ' WHEN posts >= ' . $min_posts . (!empty($lastMin) ? ' AND posts <= ' . $lastMin : '') . ' THEN ' . $id; $lastMin = $min_posts; } // A big fat CASE WHEN... END is faster than a zillion UPDATE's ;). $smcFunc['db_query']('', ' UPDATE {db_prefix}members SET id_post_group = CASE ' . $conditions . ' ELSE 0 END' . ($parameter1 != null ? ' WHERE ' . (is_array($parameter1) ? 'id_member IN ({array_int:members})' : 'id_member = {int:members}') : ''), array( 'members' => $parameter1, ) ); Before I do the update, I actually have a SELECT which throws everything I need into arrays like so: $disabled_sections = array(); $positions = array(); while ($row = $smcFunc['db_fetch_assoc']($request)) { if (!isset($disabled_sections[$row['id_group']][$row['id_layout']])) $disabled_sections[$row['id_group']][$row['id_layout']] = array( 'info' => $module_info[$name], 'id_layout_position' => $row['id_layout_position'] ); // Increment the positions... if (!is_null($row['position'])) { if (!isset($positions[$row['id_layout']][$row['id_layout_position']])) $positions[$row['id_layout']][$row['id_layout_position']] = 1; else $positions[$row['id_layout']][$row['id_layout_position']]++; } else $positions[$row['id_layout']][$row['id_layout_position']] = 0; } Thanks, I know if anyone can help me here it's definitely you guys and gals... Anyways, here is my question: How do I use a CASE statement in the first code example, so that I can update all of the rows in the position column from 0 - total # of rows found, that have that id_layout value and that id_layout_position value, and continue this for all different id_layout values in that table? Can I use the arrays above somehow? I'm sure I'll have to use the id_layout and id_layout_position values for this right? But how can I do this? Ok, guy, I get an error, saying "Hacking Attempt" with the following code: // Updating all positions in here. $smcFunc['db_query']('', ' SET @pos = 0; UPDATE {db_prefix}dp_positions SET position=@pos:=@pos+1 ORDER BY id_layout_position, position', array( ) ); Am I doing something wrong? Perhaps SMF has safeguards against this approach?? Perhaps I need to use a CASE STATEMENT instead?

    Read the article

  • Random select rows via JPA

    - by Ke
    In Mysql, SELECT id FROM table ORDER BY RANDOM() LIMIT 5 this sql can select 5 random rows. How to do this via JPA Query (Hibernate as provider, Mysql database)? Thanks.

    Read the article

  • Android: ViewHolder pattern and different types of rows?

    - by tomash
    ViewHolder pattern improves ListView scrolling framerate, as seen in following example: http://developer.android.com/intl/de/resources/samples/ApiDemos/src/com/example/android/apis/view/List14.html Is it possible to keep this pattern while using different kind of Views for different rows? In other words, is it possible to do something like: public View getView(int position, View view, ViewGroup parent) { // calculate viewID here if (view == null || *view is not null but was created from different XML than viewID* ) { view = mInflater.inflate(viewId, null);

    Read the article

< Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >