Search Results

Search found 8083 results on 324 pages for 'total newbie'.

Page 102/324 | < Previous Page | 98 99 100 101 102 103 104 105 106 107 108 109  | Next Page >

  • How do I break down an NSTimeInterval into year, months, days, hours, minutes and seconds on iPhone?

    - by willc2
    I have a time interval that spans years and I want all the time components from year down to seconds. My first thought is to integer divide the time interval by seconds in a year, subtract that from a running total of seconds, divide that by seconds in a month, subtract that from the running total and so on. That just seems convoluted and I've read that whenever you are doing something that looks convoluted, there is probably a built-in method. Is there? I integrated Alex's 2nd method into my code. It's in a method called by a UIDatePicker in my interface. NSDate *now = [NSDate date]; NSDate *then = self.datePicker.date; NSTimeInterval howLong = [now timeIntervalSinceDate:then]; NSDate *date = [NSDate dateWithTimeIntervalSince1970:howLong]; NSString *dateStr = [date description]; const char *dateStrPtr = [dateStr UTF8String]; int year, month, day, hour, minute, sec; sscanf(dateStrPtr, "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minute, &sec); year -= 1970; NSLog(@"%d years\n%d months\n%d days\n%d hours\n%d minutes\n%d seconds", year, month, day, hour, minute, sec); When I set the date picker to a date 1 year and 1 day in the past, I get: 1 years 1 months 1 days 16 hours 0 minutes 20 seconds which is 1 month and 16 hours off. If I set the date picker to 1 day in the past, I am off by the same amount. Update: I have an app that calculates your age in years, given your birthday (set from a UIDatePicker), yet it was often off. This proves there was an inaccuracy, but I can't figure out where it comes from, can you?

    Read the article

  • Is this mingw bug ?

    - by Debanjan
    Hi, I have been trying to execute this program on my migw ,through code::blocks, #include <string.h> #include <math.h> #include <stdio.h> #define N 100 int p[N / 64]; int pr[N]; int cnt; void sieve() { int i,j; for(i=0;i<N;i++) pr[i]=1; pr[0]=pr[1]=0; for(i=2;i<N;i++) if(pr[i]) { p[cnt]=i; cnt++; for(j=i+i;j<=N;j+=i) pr[j]=0; } } int main(){ sieve(); int i; for(i=0;i<cnt;i++) printf("%d ",p[i]); puts(""); printf("Total number of prime numbers : %d",cnt); return 0; } In My system the output is : 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 Total number of prime numbers : 22 Which is completely insane,since I am completely sure about the implementation of my algorithm. So I decided to try it in Ideone where it gives correct output.Can anybody point out the reason ?

    Read the article

  • How can I keep curl output out of mail from my cronjob?

    - by Russell C.
    I have written a Perl script that runs as a daily crontab job that uploads files to Amazon S3 via CURL. I want the output of the cron job emailed to me which works fine but I don't want that email to include messages related to the CURL upload (only those message my script is outputting). Here are the CURL related messages I'm seeing in the daily email right now: % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 230M 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0 0 230M 0 0 0 544k 0 1519k 0:02:35 --:--:-- 0:02:35 1807k 0 230M 0 0 0 1744k 0 1286k 0:03:03 0:00:01 0:03:02 1342k 1 230M 0 0 1 2880k 0 1219k 0:03:13 0:00:02 0:03:11 1250k 1 230M 0 0 1 4016k 0 1198k 0:03:17 0:00:03 0:03:14 1218k 2 230M 0 0 2 5168k 0 1186k 0:03:19 0:00:04 0:03:15 1202k 2 230M 0 0 2 6336k 0 1181k 0:03:19 0:00:05 0:03:14 1157k 3 230M 0 0 3 7488k 0 1177k 0:03:20 0:00:06 0:03:14 1147k 3 230M 0 0 3 8592k 0 1167k 0:03:22 0:00:07 0:03:15 1142k 4 230M 0 0 4 9744k 0 1166k 0:03:22 0:00:08 0:03:14 1145k 4 230M 0 0 4 10.6M 0 1163k 0:03:23 0:00:09 0:03:14 1142k 5 230M 0 0 5 11.7M 0 1161k 0:03:23 0:00:10 0:03:13 1140k 5 230M 0 0 5 12.8M 0 1158k 0:03:23 0:00:11 0:03:12 1133k 6 230M 0 0 6 13.9M 0 1155k 0:03:24 0:00:12 0:03:12 1138k 6 230M 0 0 6 15.0M 0 1155k 0:03:24 0:00:13 0:03:11 1138k 7 230M 0 0 7 16.1M 0 1152k 0:03:25 0:00:14 0:03:11 1131k 7 230M 0 0 7 17.2M 0 1152k 0:03:25 0:00:15 0:03:10 1132k 7 230M 0 0 7 18.4M 0 1152k 0:03:24 0:00:16 0:03:08 1140k I am using a simple Perl system() call to invoke CURL. Does anyone know what command line argument I can supply CURL to turn off the reporting of the upload progress?

    Read the article

  • What is a mantainable way of saving "star rating" in a database?

    - by Montecristo
    I'll use the jQuery plugin for presenting the user with a nice interface The request is to display 5 stars, up to a total score of 10 (2 points per star). By now I thought about using 7/10 as a format for that value, but what if at some point in the future I'll receive a request like We would like to give users more choice, let's increase the total score to 20 (so that each star contributes with a maximum of 4 points) I'll end up with a table with mixed values for the "star rating" column: some will be like 7/10 while others will be like 14/20. Is it ok for you to have this difference in the database and deal with it in the logic layer to have it consistent? Or is preferred another way so that querying the table will not result in inconsistent results outside the application? Maybe floating point values could help me, is it better to store that value as a number less than or equal to one? So in each of the two examples the resulting value stored in the database would be 0,7, as a number, not a varchar, which can be queried also outside the application. What do you think?

    Read the article

  • SQL Query to separate data into two fields

    - by Phillip
    I have data in one column that I want to separate into two columns. The data is separated by a comma if present. This field can have no data, only one set of data or two sets of data saperated by the comma. Currently I pull the data and save as a comma delimited file then use an FoxPro to load the data into a table then process the data as needed then I re-insert the data back into a different SQL table for my use. I would like to drop the FoxPro portion and have the SQL query saperate the data for me. Below is a sample of what the data looks like. Store Amount Discount 1 5.95 1 5.95 PO^-479^2 1 5.95 PO^-479^2 2 5.95 2 5.95 PO^-479^2 2 5.95 +CA8A09^-240^4,CORDRC^-239^7 3 5.95 3 5.95 +CA8A09^-240^4,CORDRC^-239^7 3 5.95 +CA8A09^-240^4,CORDRC^-239^7 In the data above I want to sum the data in the amount field to get a gross amount. Then pull out the specific discount amount which is located between the carat characters and sum it to get the total discount amount. Then add the two together and get the total net amount. The query I want to write will separate the discount field as needed, see store 2 line 3 for two discounts being applied, then pull out the value between carat characters.

    Read the article

  • Dividing numbers between rows in MySQL + PHP

    - by André Figueira
    Hi I am working on a kind of raffle system which divides 1 million random numbers into an x amount of tickets, e.g. 1 million random numbers to 10,000 tickets. Each ticket is a row in a database, we then have another table ticket numbers in which i need to give 100 numbers to each ticket they are related by the ticket id. So at the moment this is my code: //Amount of the 1 million tickets divided to the tickets $numbersPerTickets = $_POST['numbersPerTicket']; //The total cost of the property $propertyPrice = $_POST['propertyPrice']; //The total amount of tickets $totalTickets = NUMBER_CIELING / $numbersPerTickets; //The ticket price $ticketPrice = $propertyPrice / $totalTickets; //Generate array with random numbers up to 999,999 $randomTicketNumbers = createTicketNumbers(); //Creation loop counter $ticketCreationCount = 1; //Loop and create each ticket while($ticketCreationCount <= $totalTickets) { //Create a padded ticket number $ticketNumber = str_pad($ticketCreationCount, 6, 0, STR_PAD_LEFT); $query = ' INSERT INTO tickets( propertyID, ticketNumber, price ) VALUES( "'.$propertyID.'", "'.$ticketNumber.'", "'.$ticketPrice.'" ) '; $db->query($query); //Get the ID of the inserted ticket to use to insert the ticket numbers $ticketID = $db->insert_id; $loopBreak = $numbersPerTickets; $addedNumberCount = 1; foreach($randomTicketNumbers as $key => $value) { $query = ' INSERT INTO ticketNumbers( ticketID, number ) VALUES( "'.$ticketID.'", "'.$value.'" ) '; $db->query($query); unset($randomTicketNumbers[$key]); if($addedNumberCount == $loopBreak){ break; }else{ $addedNumberCount++; } } $ticketCreationCount++; } But this isn't working it adds the right amount of tickets, which in the case for testing is 10,000 but then adds far too many ticket numbers, it ends up exceeding the million numbers in the random tickets array, The random tickets array is just a simple 1 tier array with 1 million numbers sorted randomly.

    Read the article

  • ndarray field names for both row and column?

    - by Graham Mitchell
    I'm a computer science teacher trying to create a little gradebook for myself using NumPy. But I think it would make my code easier to write if I could create an ndarray that uses field names for both the rows and columns. Here's what I've got so far: import numpy as np num_stud = 23 num_assign = 2 grades = np.zeros(num_stud, dtype=[('assign 1','i2'), ('assign 2','i2')]) #etc gv = grades.view(dtype='i2').reshape(num_stud,num_assign) So, if my first student gets a 97 on 'assign 1', I can write either of: grades[0]['assign 1'] = 97 gv[0][0] = 97 Also, I can do the following: np.mean( grades['assign 1'] ) # class average for assignment 1 np.sum( gv[0] ) # total points for student 1 This all works. But what I can't figure out how to do is use a student id number to refer to a particular student (assume that two of my students have student ids as shown): grades['123456']['assign 2'] = 95 grades['314159']['assign 2'] = 83 ...or maybe create a second view with the different field names? np.sum( gview2['314159'] ) # total points for the student with the given id I know that I could create a dict mapping student ids to indices, but that seems fragile and crufty, and I'm hoping there's a better way than: id2i = { '123456': 0, '314159': 1 } np.sum( gv[ id2i['314159'] ] ) I'm also willing to re-architect things if there's a cleaner design. I'm new to NumPy, and I haven't written much code yet, so starting over isn't out of the question if I'm Doing It Wrong. I am going to be needing to sum all the assignment points for over a hundred students once a day, as well as run standard deviations and other stats. Plus, I'll be waiting on the results, so I'd like it to run in only a couple of seconds. Thanks in advance for any suggestions.

    Read the article

  • Use Linq to SQL to generate sales report

    - by Richard Reddy
    I currently have the following code to generate a sales report over the last 30 days. I'd like to know if it would be possible to use linq to generate this report in one step instead of the rather basic loop I have here. For my requirement, every day needs to return a value to me so if there are no sales for any day then a 0 is returned. Any of the Sum linq examples out there don't explain how it would be possible to include a where filter so I am confused on how to get the total amount per day, or a 0 if no sales, for the last days I pass through. Thanks for your help, Rich //setup date ranges to use DateTime startDate = DateTime.Now.AddDays(-29); DateTime endDate = DateTime.Now.AddDays(1); TimeSpan startTS = new TimeSpan(0, 0, 0); TimeSpan endTS = new TimeSpan(23, 59, 59); using (var dc = new DataContext()) { //get database sales from 29 days ago at midnight to the end of today var salesForDay = dc.Orders.Where(b => b.OrderDateTime > Convert.ToDateTime(startDate.Date + startTS) && b.OrderDateTime <= Convert.ToDateTime(endDate.Date + endTS)); //loop through each day and sum up the total orders, if none then set to 0 while (startDate != endDate) { decimal totalSales = 0m; DateTime startDay = startDate.Date + startTS; DateTime endDay = startDate.Date + endTS; foreach (var sale in salesForDay.Where(b => b.OrderDateTime > startDay && b.OrderDateTime <= endDay)) { totalSales += (decimal)sale.OrderPrice; } Response.Write("From Date: " + startDay + " - To Date: " + endDay + ". Sales: " + String.Format("{0:0.00}", totalSales) + "<br>"); //move to next day startDate = startDate.AddDays(1); } }

    Read the article

  • Java Days & Bookings

    - by sys_debug
    Ok this is an extension of a question I asked about earlier yet this is the next step that is unclear to me. Everything else will be ready and this part is driving me mad! some members provided great help and I already made progress with that info, but this is just another obstacle. I am creating a booking object (as was suggested) that will have a start date and end date. each booking will also have a number of seats associated with it (that I require to reserve). The total available number of seats any given day 46 (as the total capacity of the hall is 46 seats). so in assumption that I have a booking to be made in the system, and start date is 1st jan and end date is 10th jan. The question is how can I check the remaining seats in all those days between the range to see if requested number could be hosted or not? and then when the second booking is made, it will have to see that the days in this range already have less than 46 and decrement further if possible to host the reservation. one of the members, and I appreciate his effort, gladly contributed a method to compare if this booking is after or before the existing bookings. The code provided is here: public boolean overlapsWithExisting(Booking booking) { final Date early = booking.getStart(); final Date late = booking.getEnd(); for(Booking existing : existingBookings) { if(!(early.isAfter(existing.getEnd() || late.isBefore(existing.getStart())) return true; } return false; } I just want to know how to associate 46 with each day and keep record of days that are decremented by bookings. Thanks and reallllllly appreciated :D

    Read the article

  • Performing measures within the execution of a c++ code every t milliseconds

    - by user506901
    Given a while loop and the function ordering as follows: int k=0; int total=100; while(k<total){ doSomething(); if(approx. t milliseconds elapsed) { measure(); } ++k; } I want to perform 'measure' every t-th milliseconds. However, since 'doSomething' can be close to the t-th millisecond from the last execution, it is acceptable to perform the measure after approximately t milliseconds elapsed from the last measure. My question is: how could this be achieved? One solution would be to set timer to zero, and measure it after every 'doSomething'. When it is withing the acceptable range, I perform measures, and reset. However, I'm not which c++ function I should use for such a task. As I can see, there are certain functions, but the debate on which one is the most appropriate is outside of my understanding. Note that some of the functions actually take into account the time taken by some other processes, but I want my timer to only measure the time of the execution of my c++ code (I hope that is clear). Another thing is the resolution of the measurements, as pointed out below. Suppose the medium option of those suggested.

    Read the article

  • SQL Scenario of allocating ids to user

    - by Enjoy coding
    Hi, I have an sql scenario as follows which I have been trying to improve. There is a table 'Returns' which is having ids of the returned goods against a shop for an item. Its structure is as below. Returns ------------------------- Return ID | Shop | Item ------------------------- 1 Shop1 Item1 2 Shop1 Item1 3 Shop1 Item1 4 Shop1 Item1 5 Shop1 Item1 There is one more table Supplier with Shop, supplier and Item as shown below. Supplier --------------------------------- Supplier | Shop | Item | Volume --------------------------------- supp1 Shop1 Item1 20% supp2 Shop1 Item1 80% Now as you see supp1 is supplying 20 % of total item1 volume and supp2 is supplying 80% of Item1 to shop1. And there were 5 return of items against the same Item1 for same Shop1. Now I need to allocate any four return IDs to Supp1 and remaining one return Id to supp2. This allocation of numbers is based on the ratio of the supplied volume percentage of the supplier. This allocation varies depending on the ratio of volume of supplied items. Now I have tried a method of using RANKs as shown below by use of temp tables. temp table 1 will have Shop, Return Id, Item, Total count of return IDs and Rank of the return id. temp table 2 will have shop, Supplier, Item and his proportion and rank of proportion. Now I am facing the difficulty in allocating top return ids to top supplier as illustrated above. As SQL doesnt have loops how can I achieve this. I have been tying several ways of doing this. Please advice. My environment is Teradata (ANSI SQL is enough). Thanks in advance.

    Read the article

  • Optimizing a "set in a string list" to a "set as a matrix" operation

    - by Eric Fournier
    I have a set of strings which contain space-separated elements. I want to build a matrix which will tell me which elements were part of which strings. For example: "" "A B C" "D" "B D" Should give something like: A B C D 1 2 1 1 1 3 1 4 1 1 Now I've got a solution, but it runs slow as molasse, and I've run out of ideas on how to make it faster: reverseIn <- function(vector, value) { return(value %in% vector) } buildCategoryMatrix <- function(valueVector) { allClasses <- c() for(classVec in unique(valueVector)) { allClasses <- unique(c(allClasses, strsplit(classVec, " ", fixed=TRUE)[[1]])) } resMatrix <- matrix(ncol=0, nrow=length(valueVector)) splitValues <- strsplit(valueVector, " ", fixed=TRUE) for(cat in allClasses) { if(cat=="") { catIsPart <- (valueVector == "") } else { catIsPart <- sapply(splitValues, reverseIn, cat) } resMatrix <- cbind(resMatrix, catIsPart) } colnames(resMatrix) <- allClasses return(resMatrix) } Profiling the function gives me this: $by.self self.time self.pct total.time total.pct "match" 31.20 34.74 31.24 34.79 "FUN" 30.26 33.70 74.30 82.74 "lapply" 13.56 15.10 87.86 97.84 "%in%" 12.92 14.39 44.10 49.11 So my actual questions would be: - Where are the 33% spent in "FUN" coming from? - Would there be any way to speed up the %in% call? I tried turning the strings into factors prior to going into the loop so that I'd be matching numbers instead of strings, but that actually makes R crash. I've also tried going for partial matrix assignment (IE, resMatrix[i,x] <- 1) where i is the number of the string and x is the vector of factors. No dice there either, as it seems to keep on running infinitely.

    Read the article

  • gem install giving error that I can't change permissions.. chown and chmod not working

    - by user2321289
    so I am trying to install hmac gem install ruby-hmac -v 0.4.0 I am getting the following error message: You don't have write permissions into the /opt/rbenv/versions/1.9.3-p448/lib/ruby/gems/1.9.1 directory So the output from ls -l is as such: ubuntu@ip-10-38-121-211:~/workspace/cf-release$ sudo ls -l /opt/rbenv/versions/1.9.3-p448/lib/ruby/gems/ I perform a chown on this directory: sudo chown -R ubuntu:ubuntu /opt/rbenv/versions/1.9.3-p448/lib/ruby/gems/ Try to install the gem: ubuntu@ip-10-38-121-211:~/workspace/cf-release$ sudo chown -v ubuntu:ubuntu /opt/rbenv/versions/1.9.3-p448/lib/ruby/gems/ ownership of `/opt/rbenv/versions/1.9.3-p448/lib/ruby/gems/' retained as ubuntu:ubuntu I do another ls -l on the directory: ubuntu@ip-10-38-121-211:~/workspace/cf-release$ ls -l /opt/rbenv/versions/1.9.3-p448/lib/ruby/gems/ total 4 d--------- 8 ubuntu ubuntu 4096 Nov 1 20:43 1.9.1 Doing a chmod 777 to make the directory writeable: ubuntu@ip-10-38-121-211:~/workspace/cf-release$ sudo chmod -v 777 /opt/rbenv/versions/1.9.3-p448/lib/ruby/gems/ mode of `/opt/rbenv/versions/1.9.3-p448/lib/ruby/gems/' retained as 0777 (rwxrwxrwx) ubuntu@ip-10-38-121-211:~/workspace/cf-release$ ls -l /opt/rbenv/versions/1.9.3-p448/lib/ruby/gems/ total 4 d--------- 8 ubuntu ubuntu 4096 Nov 1 20:43 1.9.1 Any idea as to why this would be acting up like this? I am at a loss here.. any help appreciated

    Read the article

  • jquery fade an element in when a link is clicked and then swap the element when another link is clic

    - by Nik
    I have worked out how to fade an element in: Click here to view the page If you click on the heading Posture 1 : Standing Deep Breathing : you will notice the element fades in as it should. If you now click on posture 2 you will see the element fades in below posture 1. I need to be able to swap posture 1 with posture 2. I have a total of 26 postures that all have images that need to fade in and then be swapped with another image when another heading is clicked. $(document).ready(function(){ $('#section_Q_01,#section_Q_02').hide(); $('h5.trigger#Q_01').click(function(){ $('#section_Q_01').fadeIn(2000) ; }); $('h5.trigger#Q_02').click(function(){ $('#section_Q_02').fadeIn(5000) ; }); }); and the html <div id="section_Q_01" class="01"> <div class="pics"> <img src="../images/multi/poses/pose1/Pranayama._01.jpg"/> <img src="../images/multi/poses/pose1/Pranayama._02.jpg"/> <img src="../images/multi/poses/pose1/Pranayama._03.jpg"/> </div> </div> <div id="section_Q_02" class="02"> <div class="pics"> <img src="../images/multi/poses/pose2/Half_Moon_Pose_04.jpg" /> <img src="../images/multi/poses/pose2/Backward_Bending_05.jpg" /> <img src="../images/multi/poses/pose2/Hands_to_Feet_Pose_06.jpg" /> </div> </div> I need to be able to swap a total of 26 elements #section_Q_01 - #section_Q_26 Any help appreciated

    Read the article

  • Apache POI rows number

    - by sys_debug
    I am using Apache POI java and want to get the total number of rows which are not empty. I successfully processed a whole row with all its columns. Now I am assuming that I get an excel sheet with multiple rows and not a single row...so how to go about that? I was thinking of getting total number of rows (int n) and then loop until i<=n but not sure. Suggestions are most welcome :) Note: Apache POI version is 3.8. I am not dealing with Xlsx format...only xls. Yes I tried this code but got 20 in return....which is not possible given I have only 5 rows FileInputStream fileInputStream = new FileInputStream("COD.xls"); HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream); HSSFSheet worksheet = workbook.getSheet("COD"); HSSFRow row1 = worksheet.getRow(3); Iterator rows = worksheet.rowIterator(); int noOfRows = 0; while( rows.hasNext() ) { HSSFRow row = (HSSFRow) rows.next(); noOfRows++; } System.out.println("Number of Rows: " + noOfRows);

    Read the article

  • Generating random thumbnails with PHP+FFMPEG

    - by MrGhost
    I am trying to generate thumbnails from movies using FFMPEG and the FFMPEG-PHP extension. My script works OK however takes 20 minutes just to generate 5-10 thumbnails! The script works by generating random numbers which are used as frame numbers later. All numbers generated are within the movies frame count. Can you work out why this script is taking 20 mins to finish? <?php //Dont' timeout set_time_limit(0); //Load the file (This can be any file - still takes ages) $mov = new ffmpeg_movie('1486460.mp4'); //Get the total frames within the movie $total_frames = $mov->getFrameCount(); //Loop 5 times to generate random frame times for ($i = 1; $i <= 5; ) { // Generate a number within 200 and the total number of frames. $frame = mt_rand(200,$total_frames); $getframe = $mov->getFrame($frame); // Check if the frame exists within the movie // If it does, place the frame number inside an array and break the current loop if($getframe){ $frames[$frame] = $getframe ; $i++; } } //For each frame found generate a thumbnail foreach ($frames as $key => $getframe) { $gd_image = $getframe->toGDImage(); imagejpeg($gd_image, "images/shot_".$key.'.jpeg'); imagedestroy($gd_image); echo $key.'<br/>'; } ?> The script SHOULD be generating frame numbers which are valid? Anything within START - END should be valid frame numbers? Yet the loop takes ages!

    Read the article

  • QProgressBar problem with uploading

    - by rolanddd
    Hey all! I show my code first, then I explain my problem: ... // somewhere in the constructor progressBar = new QProgressBar(this); progressBar-setMinimum(0); progressBar-setMaximum(100); ... connect(&http, SIGNAL(dataSendProgress(int, int)), this, SLOT(updateProgressBar(int, int))); ... void MainWindow::updateProgressBar(int bytesSent, int total) { progressBar-setMaximum(total); progressBar-setValue(bytesSent); } So this is how I try to make my progressBar being updated when I upload a file. The problem is, it won't do the job. When it starts uploading, I set the value of the progress bar to 0, then (thanks to this slot) it won't actually show the progress, but will jump to 100% immediately (even before it finished uploading). I already checked the HTTP Client example, and copied the progress bar part, it is for downloading, and more or less is the same as for uploading but it uses the dataReadProgress signal (needed for downloading) AND it works perfectly. Does anybody know how to solve this for uploading?

    Read the article

  • CodeIgniter: help with this query

    - by iamjonesy
    Hi, I have just started my first CI app. I have a view that displays some posts. Each post can have multiple comments and I want to display the total number of comments next to each post. So far all my db call are in my controller (will be changing this). function index(){ $data['query'] = $this->db->get('posts'); $this->load->view('blog_view', $data); } In my view: <?php foreach($query->result() as $row): <div class="post-box"> <p><?php echo $row->body; ?><small>&nbsp;added by <?php echo $row->username; ?> on <?php echo date ('d/m/Y',strtotime($row->created)); ?>&nbsp;<a href="<?php echo base_url(); ?>blog/comments/<?php echo $row->id; ?>"><img src="<?php echo base_url(); ?>images/comments_icon.png" />&nbsp;0</a></small></p> </div> <?php endforeach; ?> I want to get the total number of comments where comment.post_id = the current record's id. and display it next to the comments icon. Any help with this most appreciated, Billy

    Read the article

  • how to insert excel-2003 values into SQL2005 database?

    - by vas
    Are there any rules / guidelines for DATA form XLS sheets to be inserted into SQL- DB? I have a group of Excel templates in 2005.Each concerned cell in Excel template is named. When Excel sheets are filled, saved and submitted , the values are transferred to the database. Excel sheets have names for various cells that are to b e filled by the user EX:- for the total number of Milk in the Beginning a given month , there is an Excel Cell Named "mtsBpiPTR180" Total number of Milk in the Ending a given month , there is an Excel Cell Named **"mtsEpiPTR180"** I have added 2 new cells , named "mtsBpiPTR180PA" and "mtsEpiPTR180PA". Now I try to upload the Excel File. But I AM UNABLE TO SEE MY FILLED DATA FROM "mtsBpiPTR180PA" and "mtsEpiPTR180PA" INTO THE RELATED DB/table. The above 2 are empty in the DB/table, even though I have filled them and successfully filed the Excel sheets Now no matter how much I search in the DB/stored procs i am unable to the ACTUAL STORED PROC or how the Data form Excel sheet is inserted into Tables WHERE DATA FROM XLS is inserted into DB. So was wondering:- Are there any rules / guidelines for DATA form XLS sheets to be inserted into SQL- DB?

    Read the article

  • SQL Server query

    - by carrot_programmer_3
    Hi, I have a SQL Server DB containing a registrations table that I need to plot on a graph over time. The issue is that I need to break this down by where the user registered from (e.g. website, wap site, or a mobile application). the resulting output data should look like this... [date] [num_reg_website] [num_reg_wap_site] [num_reg_mobileapp] 1 FEB 2010,24,35,64 2 FEB 2010,23,85,48 3 FEB 2010,29,37,79 etc... The source table is as follows... UUID(int), signupdate(datetime), requestsource(varchar(50)) some smple data in this table looks like this... 1001,2010-02-2:00:12:12,'website' 1002,2010-02-2:00:10:17,'app' 1003,2010-02-3:00:14:19,'website' 1004,2010-02-4:00:16:18,'wap' 1005,2010-02-4:00:18:16,'website' Running the following query returns one data column 'total registrations' for the website registrations but I'm not sure how to do this for multiple columns unfortunatly.... select CAST(FLOOR(CAST([signupdate]AS FLOAT ))AS DATETIME) as [signupdate], count(UUID) as 'total registrations' FROM [UserRegistrationRequests] WHERE requestsource = 'website' group by CAST(FLOOR(CAST([signupdate]AS FLOAT ))AS DATETIME)

    Read the article

  • VB.NET Button Issue

    - by Michael
    I am having problem with a button the code of my button is. Private Sub btnCalculateCosts_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculateCosts.Click it handles: ' This Calculate Costs button click event handler edits the ' registration(costs) form to ensure it contains valid data. ' Then, after passing control to the business class, it ' displays the registration cost. Dim objCourse As Course Dim objCourseCostsFile As Course Dim InputError As Boolean = False ' Is student ID entered properly If Me.txtCorporateID.MaskFull = False Then MessageBox.Show("Enter your Corporate ID in the Corporate ID box", _ "Error") Me.txtCorporateID.Clear() Me.txtCorporateID.Focus() InputError = True ' Is student name entered properly ElseIf Me.txtFirstName.TextLength < 1 Or _ Me.txtFirstName.Text < "A" Then MessageBox.Show("Please enter your first name in the First Name box", "Error") Me.txtFirstName.Clear() Me.txtFirstName.Focus() InputError = True ' Is number of units entered properly ElseIf Me.txtLastName.TextLength < 1 Or _ Me.txtLastName.Text < "A" Then MessageBox.Show("Please enter your last name in the Last Name box", "Error") Me.txtLastName.Clear() Me.txtLastName.Focus() InputError = True ' Is number of units entered properly ElseIf Not IsNumeric(Me.txtNumberOfDays.Text) Then MessageBox.Show("Enter the units in the Number of Units box", _ "Error") Me.txtNumberOfDays.Clear() Me.txtNumberOfDays.Focus() InputError = True ' Has 1-4 units been entered ElseIf Convert.ToInt32(Me.txtNumberOfDays.Text) < 1 _ Or Convert.ToInt32(Me.txtNumberOfDays.Text) > 4 Then MessageBox.Show("Units must be 1 - 4", "Error") Me.txtNumberOfDays.Clear() Me.txtNumberOfDays.Focus() InputError = True End If ' If no input error, process the registration costs If Not InputError Then If Me.radPreConferenceCourse.Checked = False Then objCourse = New Course(txtCorporateID.Text, txtFirstName.Text, txtLastName.Text, txtNumberOfDays.Text) Me.lblCosts.Visible = True Me.lblCosts.Text = "Total Conference Costs Are: " _ & (objCourse.ComputeCosts()).ToString("C2") Else objCourse = New Course(txtCorporateID.Text, txtFirstName.Text, txtLastName.Text, txtNumberOfDays.Text, g) Me.lblCosts.Visible = True Me.lblCosts.Text = "Total Conference Costs Are: " _ & (objCourse.ComputeCosts()).ToString("C2") Receiving the error: Handles clause requrieres a WithEvents variable defined in the containing type or one of its base types.

    Read the article

  • Limiting Row Selection in JTable

    - by Pat
    Is there an easy way to limit the total selection of rows in a JTable? I mean I'd like to allow the user to use shift and ctrl to select a maximum of X rows. If he clicks again on a row it would cancel out all the selections. Sort of how it currently behaves, but while limiting the total amount of selected rows. Here's my current implementation, I'm kind of clueless on how to limit the selection graphically. public class RoomsListView extends AbstractViewPanel { public RoomsListView(DefaultController controller) { this.controller = controller; initUI(); } private void initUI() { tableT = new JTable(RoomsModel.getInstance()); sorter = new TableRowSorter<RoomsModel>(RoomsModel.getInstance()); tableT.setRowSorter(sorter); tableT.setPreferredScrollableViewportSize(new Dimension(CUSTOM_TABLE_WIDTH, CUSTOM_TABLE_HEIGHT)); tableT.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { rowClickedPerformed(e); } }); } private void rowClickedPerformed(MouseEvent e) { } public void modelPropertyChange(PropertyChangeEvent evt) { } public JTable getTable() { return tableT; } private final int CUSTOM_TABLE_WIDTH = -1; private final int CUSTOM_TABLE_HEIGHT = 150; private JTable tableT; private DefaultController controller; private TableRowSorter<RoomsModel> sorter; }

    Read the article

  • how to run TimerTask off main UI thread?

    - by huskyd97
    I am having trouble with a TimerTask Interfering with In App Purchasing (Async Tasks). I am weak with Threads, so I believe it is running on the main UI thread, eating up resources. How can I run this outside the UI thread? I have searched, and tried some suggestions using handlers. but seems like I get the same result, app gets really laggy. when I don't run this task (refreshes every 500mS), the activity runs smoothly, and there are no hangs during In app purchases. Your help is appreciated, code snippet below: public class DummyButtonClickerActivity extends Activity { protected Timer timeTicker = new Timer("Ticker"); private Handler timerHandler = new Handler(); protected int timeTickDown = 20; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mainhd); // start money earned timer handler TimerTask tick = new TimerTask() { public void run() { myTickTask(); } }; timeTicker.scheduleAtFixedRate(tick, 0, 500); // 500 ms each } // End OnCreate protected void myTickTask() { if (timeTickDown == 0) { /// run my code here //total = total + _Rate; timerHandler.post(doUpdateTimeout); } else if(timeTickDown < 0) { // do nothing } timeTickDown--; } private Runnable doUpdateTimeout = new Runnable() { public void run() { updateTimeout(); } }; private void updateTimeout() { // reset tick timeTickDown = 2; // 2* 500ms == once a second } }

    Read the article

  • Optimizing near-duplicate value search

    - by GApple
    I'm trying to find near duplicate values in a set of fields in order to allow an administrator to clean them up. There are two criteria that I am matching on One string is wholly contained within the other, and is at least 1/4 of its length The strings have an edit distance less than 5% of the total length of the two strings The Pseudo-PHP code: foreach($values as $value){ foreach($values as $match){ if( ( $value['length'] < $match['length'] && $value['length'] * 4 > $match['length'] && stripos($match['value'], $value['value']) !== false ) || ( $match['length'] < $value['length'] && $match['length'] * 4 > $value['length'] && stripos($value['value'], $match['value']) !== false ) || ( abs($value['length'] - $match['length']) * 20 < ($value['length'] + $match['length']) && 0 < ($match['changes'] = levenshtein($value['value'], $match['value'])) && $match['changes'] * 20 <= ($value['length'] + $match['length']) ) ){ $matches[] = &$match; } } } I've tried to reduce calls to the comparatively expensive stripos and levenshtein functions where possible, which has reduced the execution time quite a bit. However, as an O(n^2) operation this just doesn't scale to the larger sets of values and it seems that a significant amount of the processing time is spent simply iterating through the arrays. Some properties of a few sets of values being operated on Total | Strings | # of matches per string | | Strings | With Matches | Average | Median | Max | Time (s) | --------+--------------+---------+--------+------+----------+ 844 | 413 | 1.8 | 1 | 58 | 140 | 593 | 156 | 1.2 | 1 | 5 | 62 | 272 | 168 | 3.2 | 2 | 26 | 10 | 157 | 47 | 1.5 | 1 | 4 | 3.2 | 106 | 48 | 1.8 | 1 | 8 | 1.3 | 62 | 47 | 2.9 | 2 | 16 | 0.4 | Are there any other things I can do to reduce the time to check criteria, and more importantly are there any ways for me to reduce the number of criteria checks required (for example, by pre-processing the input values), since there is such low selectivity?

    Read the article

  • Reporting Services Sum of Inner Group in Outer Group

    - by Spoonybard
    I have a report in Reporting Services 2008 using ASP.net 3.5 and SQL Server 2008. The report has 2 groupings and a detail row. This is the current format: Outer Group Inner Group Detail Row The Detail Row represents an item on a receipt and a receipt can have multiple items. Each receipt was paid with a certain payment method. So the Outer Group is grouped by payment type, the Inner Group is grouped by the receipt's ID, and the Detail Row is each item for the given receipt. My raw data result set has two important columns: The Amount Received and the Amount Applied. The Amount Received is how much money in total was collected for all the items on the receipt. The Amount Applied is how much money each item got from the total Amount Received. Sample Result Set: ReceiptID Item ItemID AmountReceived AmountApplied Payment Method ------------------------------------------------------------------------------------------ 1 Book 1 $200.00 $40.00 Cash 1 CD 2 $200.00 $20.00 Cash 1 Software 3 $200.00 $100.00 Cash 1 Backpack 4 $200.00 $40.00 Cash The Inner Group displays the AmountReceived correctly as $200. However, the Outer Group displays the AmountReceived as $800, because I believe that it is going off each detail row which in this case is a count of 4 items. What I want is to see in the Outer Group that the Amount Received is $200. I tried restricting the scope in my SUM function to be the Inner Group, but I get the error "The scope parameter must be set to a string constant that is equal to either the name of a containing group, the name of a containing data region, or the name of a dataset." Does anyone have any suggestions on how to solve this issue? Thanks.

    Read the article

< Previous Page | 98 99 100 101 102 103 104 105 106 107 108 109  | Next Page >