Search Results

Search found 137 results on 6 pages for 'ceil'.

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

  • plpgsql function to generate random readable strings

    - by Peter
    Hi I have written the following function but it's isn't returning anything when I run it. Can somebody help identify the issue? CREATE OR REPLACE FUNCTION GenerateReadableRandomString ( len INT ) RETURNS varchar AS $$ DECLARE validchars VARCHAR; randomstr VARCHAR; randint INT; i INT; BEGIN validchars := 'ABCEFHJKLMNPRTWXY3478'; i := 0; LOOP randint := ceil(random() * char_length(validchars)); randomstr := randomstr || substring(validchars from randint for 1); i := i + 1; EXIT WHEN i = len; END LOOP; RETURN randomstr; END; $$ LANGUAGE plpgsql;

    Read the article

  • custom tabbars and make them circulate

    - by pengwang
    i want to custom tabbars and want to circulate slide,default tab bar only have 5 items show at the same time,it not meet me,i have 11 items,so i want to make 3 tabbars ,every have 5 items,for example A(0-4)--B(5-9)--C(10)--A--B--C--A. at print i only finish A(0-4)--B(5-9)--C(10),how to make them circulate? my code : .h file #import <UIKit/UIKit.h> @protocol InfiniTabBarDelegate; @interface InfiniTabBar : UIScrollView <UIScrollViewDelegate, UITabBarDelegate> { __weak id <InfiniTabBarDelegate> infiniTabBarDelegate; NSMutableArray *tabBars; UITabBar *aTabBar; UITabBar *bTabBar; } @property (nonatomic, weak) id infiniTabBarDelegate; @property (strong,nonatomic) NSMutableArray *tabBars; @property (strong,nonatomic) UITabBar *aTabBar; @property (strong,nonatomic) UITabBar *bTabBar; - (id)initWithItems:(NSArray *)items; - (void)setBounces:(BOOL)bounces; // Don't set more items than initially - (void)setItems:(NSArray *)items animated:(BOOL)animated; - (int)currentTabBarTag; - (int)selectedItemTag; - (BOOL)scrollToTabBarWithTag:(int)tag animated:(BOOL)animated; - (BOOL)selectItemWithTag:(int)tag; @end @protocol InfiniTabBarDelegate <NSObject> - (void)infiniTabBar:(InfiniTabBar *)tabBar didScrollToTabBarWithTag:(int)tag; - (void)infiniTabBar:(InfiniTabBar *)tabBar didSelectItemWithTag:(int)tag; @end .m file @implementation InfiniTabBar @synthesize infiniTabBarDelegate; @synthesize tabBars; @synthesize aTabBar; @synthesize bTabBar; - (id)initWithItems:(NSArray *)items { self = [super initWithFrame:CGRectMake(0.0, 411.0, 320.0, 49.0)]; // TODO: //self = [super initWithFrame:CGRectMake(self.superview.frame.origin.x + self.superview.frame.size.width - 320.0, self.superview.frame.origin.y + self.superview.frame.size.height - 49.0, 320.0, 49.0)]; // Doesn't work. self is nil at this point. if (self) { self.pagingEnabled = YES; self.delegate = self; self.tabBars = [[NSMutableArray alloc] init]; float x = 0.0; for (double d = 0; d < ceil(items.count / 5.0); d ++) { UITabBar *tabBar = [[UITabBar alloc] initWithFrame:CGRectMake(x, 0.0, 320.0, 49.0)]; tabBar.delegate = self; int len = 0; for (int i = d * 5; i < d * 5 + 5; i ++) if (i < items.count) len ++; tabBar.items = [items objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(d * 5, len)]]; // NSLog(@"####%@",NSMakeRange(d * 5, len)); [self.tabBars addObject:tabBar]; [self addSubview:tabBar]; x += 320.0; } self.contentSize = CGSizeMake(x, 49.0); } return self; } - (void)setBounces:(BOOL)bounces { if (bounces) { int count = self.tabBars.count; if (count > 0) { if (self.aTabBar == nil) self.aTabBar = [[UITabBar alloc] initWithFrame:CGRectMake(-320.0, 0.0, 320.0, 49.0)]; [self addSubview:self.aTabBar]; if (self.bTabBar == nil) self.bTabBar = [[UITabBar alloc] initWithFrame:CGRectMake(count * 320.0, 0.0, 320.0, 49.0)]; [self addSubview:self.bTabBar]; } } else { [self.aTabBar removeFromSuperview]; [self.bTabBar removeFromSuperview]; } [super setBounces:bounces]; } - (void)setItems:(NSArray *)items animated:(BOOL)animated { for (UITabBar *tabBar in self.tabBars) { int len = 0; for (int i = [self.tabBars indexOfObject:tabBar] * 5; i < [self.tabBars indexOfObject:tabBar] * 5 + 5; i ++) if (i < items.count) len ++; [tabBar setItems:[items objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange([self.tabBars indexOfObject:tabBar] * 5, len)]] animated:animated]; } self.contentSize = CGSizeMake(ceil(items.count / 5.0) * 320.0, 49.0); } - (int)currentTabBarTag { return self.contentOffset.x / 320.0; } - (int)selectedItemTag { for (UITabBar *tabBar in self.tabBars) if (tabBar.selectedItem != nil) return tabBar.selectedItem.tag; // No item selected return 0; } - (BOOL)scrollToTabBarWithTag:(int)tag animated:(BOOL)animated { for (UITabBar *tabBar in self.tabBars) if ([self.tabBars indexOfObject:tabBar] == tag) { UITabBar *tabBar = [self.tabBars objectAtIndex:tag]; [self scrollRectToVisible:tabBar.frame animated:animated]; if (animated == NO) [self scrollViewDidEndDecelerating:self]; return YES; } return NO; } - (BOOL)selectItemWithTag:(int)tag { for (UITabBar *tabBar in self.tabBars) for (UITabBarItem *item in tabBar.items) if (item.tag == tag) { tabBar.selectedItem = item; [self tabBar:tabBar didSelectItem:item]; return YES; } return NO; } - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { [infiniTabBarDelegate infiniTabBar:self didScrollToTabBarWithTag:scrollView.contentOffset.x / 320.0]; } - (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView { [self scrollViewDidEndDecelerating:scrollView]; } - (void)tabBar:(UITabBar *)cTabBar didSelectItem:(UITabBarItem *)item { // Act like a single tab bar for (UITabBar *tabBar in self.tabBars) if (tabBar != cTabBar) tabBar.selectedItem = nil; [infiniTabBarDelegate infiniTabBar:self didSelectItemWithTag:item.tag]; } @end

    Read the article

  • Memory assignment of local variables

    - by Mask
    void function(int a, int b, int c) { char buffer1[5]; char buffer2[10]; } We must remember that memory can only be addressed in multiples of the word size. A word in our case is 4 bytes, or 32 bits. So our 5 byte buffer is really going to take 8 bytes (2 words) of memory, and our 10 byte buffer is going to take 12 bytes (3 words) of memory. That is why SP is being subtracted by 20. Why it's not ceil((5+10)/4)*4=16?

    Read the article

  • SQL: select random row from table where the ID of the row isn't in another table?

    - by johnrl
    I've been looking at fast ways to select a random row from a table and have found the following site: http://74.125.77.132/search?q=cache:http://jan.kneschke.de/projects/mysql/order-by-rand/&hl=en&strip=1 What I want to do is to select a random url from my table 'urls' that I DON'T have in my other table 'urlinfo'.The query I am using now selects a random url from 'urls' but I need it modified to only return a random url that is NOT in the 'urlinfo' table. Heres the query: SELECT url FROM urls JOIN (SELECT CEIL(RAND() * (SELECT MAX(urlid) FROM urls ) ) AS urlid ) AS r2 USING(urlid); And the two tables: CREATE TABLE urls ( urlid INT NOT NULL AUTO_INCREMENT PRIMARY KEY, url VARCHAR(255) NOT NULL, ) ENGINE=INNODB; CREATE TABLE urlinfo ( urlid INT NOT NULL PRIMARY KEY, urlinfo VARCHAR(10000), FOREIGN KEY (urlid) REFERENCES urls (urlid) ) ENGINE=INNODB;

    Read the article

  • Change Layout Of Text Created In Java [Android]

    - by Dan
    Ok right , i asked how to create a random number from 1-100 for android and i came to this TextView tv = new TextView(this); int random = (int)Math.ceil(Math.random()*101); tv.setText("Your Number Is..."+ random ); What this does is create the default kinda "hello world" style text view and says "Your Number Is.... [Then Random Number] My problem is that i cant change the layout of this text , because it is not defined in XML, if someone could tell me how to change the style , or like make the random number into a string so i could use it for any Textview layout that would be great .. Thanks :)

    Read the article

  • How would you sample a real-time stream of coordinates to create a Speed Graph?

    - by Andrew Johnson
    I have a GPS device, and I am receiving continuous points, which I store in an array. These points are time stamped. I would like to graph distance/time (speed) vs. distance in real-time; however, I can only plot 50 of the points because of hardware constraints. How would you select points from the array to graph? For example, one algorithm might be to select every Nth point from the array, where N results in 50 points total. Code: float indexModifier = 1; if (MIN(50,track.lastPointIndex) == 50) { indexModifier = track.lastPointIndex/50.0f; } index = ceil(index*indexModifier); Another algorithm might be to keep an array of 50 points, and throw out the point with the least speed change each time you get a new point.

    Read the article

  • Ruby Built In Method to Create Multidimensional Array From Single Dimensioned Array

    - by Ell
    If I have an array like this: [0, 1, 2, 3, 4, 5], is there a built in method to create this: [[0, 1, 2], [3, 4, 5]] given a width of 3? If there is no built in method, how could I improve on this? def multi_to_single(array, width) return [].tap{|md_array| (array.length.to_f / width).ceil.times {|y| row = (array[(y*width), width]) md_array.push( row + Array.new(width - row.length)) } } end I feel like I have missed something obvious because I haven't programmed ruby in a while! Thanks in advance, ell. EDIT: It needs to be in the core library, so no ruby on rails or anything.

    Read the article

  • Super Noob C++ variable help

    - by julian
    Ok, I must preface this by stating that I know so so little about c++ and am hoping someone can just help me out... I have the below code: string GoogleMapControl::CreatePolyLine(RideItem *ride) { std::vector<RideFilePoint> intervalPoints; ostringstream oss; int cp; int intervalTime = 30; // 30 seconds int zone =ride->zoneRange(); if(zone >= 0) { cp = 300; // default cp to 300 watts } else { cp = ride->zones->getCP(zone); } foreach(RideFilePoint* rfp, ride->ride()->dataPoints()) { intervalPoints.push_back(*rfp); if((intervalPoints.back().secs - intervalPoints.front().secs) > intervalTime) { // find the avg power and color code it and create a polyline... AvgPower avgPower = for_each(intervalPoints.begin(), intervalPoints.end(), AvgPower()); // find the color QColor color = GetColor(cp,avgPower); // create the polyline CreateSubPolyLine(intervalPoints,oss,color); intervalPoints.clear(); intervalPoints.push_back(*rfp); } } return oss.str(); } void GoogleMapControl::CreateSubPolyLine(const std::vector<RideFilePoint> &points, std::ostringstream &oss, QColor color) { oss.precision(6); QString colorstr = color.name(); oss.setf(ios::fixed,ios::floatfield); oss << "var polyline = new GPolyline(["; BOOST_FOREACH(RideFilePoint rfp, points) { if (ceil(rfp.lat) != 180 && ceil(rfp.lon) != 180) { oss << "new GLatLng(" << rfp.lat << "," << rfp.lon << ")," << endl; } } oss << "],\"" << colorstr.toStdString() << "\",4);"; oss << "GEvent.addListener(polyline, 'mouseover', function() {" << endl << "var tooltip_text = 'Avg watts:" << avgPower <<" <br> Avg Speed: <br> Color: "<< colorstr.toStdString() <<"';" << endl << "var ss={'weight':8};" << endl << "this.setStrokeStyle(ss);" << endl << "this.overlay = new MapTooltip(this,tooltip_text);" << endl << "map.addOverlay(this.overlay);" << endl << "});" << endl << "GEvent.addListener(polyline, 'mouseout', function() {" << endl << "map.removeOverlay(this.overlay);" << endl << "var ss={'weight':5};" << endl << "this.setStrokeStyle(ss);" << endl << "});" << endl; oss << "map.addOverlay (polyline);" << endl; } And I'm trying to get the avgPower from this part: AvgPower avgPower = for_each(intervalPoints.begin(), intervalPoints.end(), AvgPower()); the first part to cary over to the second part: << "var tooltip_text = 'Avg watts:" << avgPower <<" <br> Avg Speed: <br> Color: "<< colorstr.toStdString() <<"';" << endl But of course I haven't the slightest clue how to do it... anyone feeling generous today? Thanks in advance

    Read the article

  • Split a map using Groovy

    - by Tihom
    I want to split up a map into an array of maps. For example, if there is a map with 25 key/value pairs. I want an array of maps with no more than 10 elements in each map. How would I do this in groovy? I have a solution which I am not excited about, is there better groovy version: static def splitMap(m, count){ if (!m) return def keys = m.keySet().toList() def result = [] def num = Math.ceil(m?.size() / count) (1..num).each { def min = (it - 1) * count def max = it * count > keys.size() ? keys.size() - 1 : it * count - 1 result[it - 1] = [:] keys[min..max].each {k -> result[it - 1][k] = m[k] } } result } m is the map. Count is the max number of elements within the map.

    Read the article

  • NSTableView - Trying to fit exactly 9 rows

    - by Justin808
    Hi, I'm trying to size the rows of a NSTableView to exactly 9 rows fit. I've tried [menuTableView setRowHeight:floor(menuRect.size.height / 9)]; and I've tried [menuTableView setRowHeight:(menuRect.size.height / 9)]; and [menuTableView setRowHeight:ceil(menuRect.size.height / 9)]; but all of them have the same issue, if I've selected row 0 then row 9 is clipped at the bottom and if I select row 9 then row 0 is clipped at the top. How can I set up a NSTableView to show 9 full rows so no matter what there is never a partial row visible? Thanks, edit: Yes menuRect is the frame for the menuTableView

    Read the article

  • list images from directory by function

    - by osc2nuke
    i'm using this function: function getmyimages($qid){ $imgdir = 'modules/Projects/uploaded_project_images/'. $qid .''; // the directory, where your images are stored $allowed_types = array('png','jpg','jpeg','gif'); // list of filetypes you want to show $dimg = opendir($imgdir); while($imgfile = readdir($dimg)) { if(in_array(strtolower(substr($imgfile,-3)),$allowed_types)) { $a_img[] = $imgfile; sort($a_img); reset ($a_img); } } $totimg = count($a_img); // total image number for($x=0; $x < $totimg; $x++) { $size = getimagesize($imgdir.'/'.$a_img[$x]); // do whatever $halfwidth = ceil($size[0]/2); $halfheight = ceil($size[1]/2); $mytest = 'name: '.$a_img[$x].' width: '.$size[0].' height: '.$size[1].'<br /><a href="'. $imgdir .'/'.$a_img[$x].'">'. $a_img[$x]. '</a>'; } return $mytest; } And i call this function between a while row as: $sql_select = $db->sql_query('SELECT * from '.$prefix.'_projects WHERE topic=\''.$cid.'\''); OpenTable(); while ($row2 = $db->sql_fetchrow($sql_select)){ $qid = $row2['qid']; $project_query = $db->sql_query('SELECT p.uid, p.uname, p.subject, p.story, p.storyext, p.date, p.topic, p.pdate, p.materials, p.bidoptions, p.projectduration, pd.id_duration, pm.material_id, pbo.bidid, pc.cid FROM ' . $prefix . '_projects p, ' . $prefix . '_projects_duration pd, ' . $prefix . '_project_materials pm, ' . $prefix . '_project_bid_options pbo, ' . $prefix . '_project_categories pc WHERE p.topic=\''.$cid.'\' and p.qid=\''.$qid.'\' and p.bidoptions=pbo.bidid and p.materials=pm.material_id and p.projectduration=pd.id_duration'); while ($project_row = $db->sql_fetchrow($project_query)) { //$qid = $project_row['qid']; $uid = $project_row['uid']; $uname = $project_row['uname']; $subject = $project_row['subject']; $story = $project_row['story']; $storyext = $project_row['storyext']; $date = $project_row['date']; $topic = $project_row['topic']; $pdate = $project_row['pdate']; $materials = $project_row['materials']; $bidoptions = $project_row['bidoptions']; $projectduration = $project_row['projectduration']; //Get the topic name $topic_query = $db->sql_query('SELECT cid,title from '.$prefix.'_project_categories WHERE cid =\''.$cid.'\''); while ($topic_row = $db->sql_fetchrow($topic_query)) { $topic_id = $topic_row['cid']; $topic_title = $topic_row['title']; } //Get the material text $material_query = $db->sql_query('SELECT material_id,material_name from '.$prefix.'_project_materials WHERE material_id =\''.$materials.'\''); while ($material_row = $db->sql_fetchrow($material_query)) { $material_id = $material_row['material_id']; $material_name = $material_row['material_name']; } //Get the bid methode $bid_query = $db->sql_query('SELECT bidid,bidname from '.$prefix.'_project_bid_options WHERE bidid =\''.$bidoptions.'\''); while ($bid_row = $db->sql_fetchrow($bid_query)) { $bidid = $bid_row['bidid']; $bidname = $bid_row['bidname']; } //Get the project duration $duration_query = $db->sql_query('SELECT id_duration,duration_value,duration_alias from '.$prefix.'_projects_duration WHERE id_duration =\''.$projectduration.'\''); while ($duration_row = $db->sql_fetchrow($duration_query)) { $id_duration = $duration_row['id_duration']; $duration_value = $duration_row['duration_value']; $duration_alias = $duration_row['duration_alias']; } } echo '<br/><b>id</b>--->' .$qid. '<br/><b>uid</b>--->' .$uid. '<br/><b>username</b>--->' .$uname. '<br/><b>subject</b>--->'.$subject. '<br/><b>story1</b>--->'.$story. '<br/><b>story2</b>--->'.$storyext. '<br/><b>postdate</b>--->'.$date. '<br/><b>categorie</b>--->'.$topic_title . '<br/><b>project start</b>--->'.$pdate. '<br/><b>materials</b>--->'.$material_name. '<br/><b>bid methode</b>--->'.$bidname. '<br/><b>project duration</b>--->'.$duration_alias.'<br /><br /><br/><b>image url</b>--->'.getmyimages($qid).'<br /><br />'; } CloseTable(); the result outputs only the "last" file from the directories. if i do a echo instead of a return $mytest; it read the whole directory but ruïns the output.

    Read the article

  • Wordpress SQL_CALC fix causes PHP error

    - by ok1ha
    I'm looking for some followup on an older topic for Wordpress where SQL_CALC was found to slow things down when you have a large DB in Wordpress. I have been using the code, at the bottom of this post, to get around it but it does generate an error in my error log. How would I prevent this error? PHP Warning: Division by zero in /var/www/vhosts/domain.com/httpdocs/wp-content/themes/greatTheme/functions.php on line 19 The original thread: http://wordpress.org/support/topic/slow-queries-sql_calc_found_rows-bringing-down-site?replies=25 The code in my functions.php: add_filter('pre_get_posts', 'optimized_get_posts', 100); function optimized_get_posts() { global $wp_query, $wpdb; $wp_query->query_vars['no_found_rows'] = 1; $wp_query->found_posts = $wpdb->get_var( "SELECT COUNT(*) FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private')" ); $wp_query->found_posts = apply_filters_ref_array( 'found_posts', array( $wp_query->found_posts, &$wp_query ) ); $wp_query->max_num_pages = ceil($wp_query->found_posts / $wp_query->query_vars['posts_per_page']); return $wp_query; }

    Read the article

  • Adding Content to a Randomized Background

    - by user2903815
    On refresh my background image changes. I need to add a header to change with each background. How would I add an h1 tag to the php. I am unfamiliar with php but I feel like this should be an easy fix. Here's my script: <script type="text/javascript"> var bgcount = 3; function changebg() { var num = Math.ceil( Math.random() * bgcount ); document.body.background = 'bgs/'+num+'.jpg'; document.body.style.backgroundRepeat = "no-repeat"; document.body.style.backgroundAttachment = "fixed"; document.body.style.backgroundSize = "cover"; } </script> Thanks!

    Read the article

  • Resolving "not found" messages after doing ./configure building node.js

    - by duke
    Hello I am trying to install node.js on debian AMD64. I got node.js from git. When I do ./configure a bunch of "checking for program" messages say "not found". I want to resolve all these and ensure everything needed is present. Can anyone suggest what I need to do to resolve the "not found" messages? Thanks heaps. server:/devel/node# ./configure Checking for program g++ or c++ : /usr/bin/g++ Checking for program cpp : /usr/bin/cpp Checking for program ar : /usr/bin/ar Checking for program ranlib : /usr/bin/ranlib Checking for g++ : ok Checking for program gcc or cc : /usr/bin/gcc Checking for gcc : ok Checking for library dl : yes Checking for library execinfo : not found Checking for openssl : not found Checking for function SSL_library_init : yes Checking for header openssl/crypto.h : yes Checking for library rt : yes --- libeio --- Checking for library pthread : yes Checking for function pthread_create : yes Checking for function pthread_atfork : yes Checking for futimes(2) : yes Checking for readahead(2) : yes Checking for fdatasync(2) : yes Checking for pread(2) and pwrite(2) : yes Checking for sendfile(2) : yes Checking for sync_file_range(2) : yes --- libev --- Checking for header sys/inotify.h : yes Checking for function inotify_init : yes Checking for header sys/epoll.h : yes Checking for function epoll_ctl : yes Checking for header port.h : not found Checking for header poll.h : yes Checking for function poll : yes Checking for header sys/event.h : not found Checking for header sys/queue.h : yes Checking for function kqueue : not found Checking for header sys/select.h : yes Checking for function select : yes Checking for header sys/eventfd.h : not found Checking for SYS_clock_gettime : yes Checking for library rt : yes Checking for function clock_gettime : yes Checking for function nanosleep : yes Checking for function ceil : yes Checking for fdatasync(2) with c++ : yes 'configure' finished successfully (1.479s) server:/devel/node#

    Read the article

  • What cause high CPU usage on the server during file upload

    - by bosiang
    When I try to upload a huge file size (approx 2GB), the server cpu usage goes really high. What should I do to fix this? I just use standard html form and php, for file upload. I'm sorry if I post on the wrong forum. Please point me to the right direction here is the result of "top" command during uploading 4 files (18mb, 38mb, 60mb, 33mb) 1904 apache 20 0 33504 5740 1952 R 28.3 0.2 0:02.19 httpd 1905 apache 20 0 33504 5740 1952 R 28.3 0.2 0:01.99 httpd 1903 apache 20 0 33232 6968 3060 R 28.0 0.2 0:01.98 httpd 1910 apache 20 0 33240 6020 2248 S 11.5 0.2 0:02.85 httpd 2133 root 20 0 2656 1124 896 R 1.6 0.0 0:00.71 top 1 root 20 0 2864 1404 1188 S 0.0 0.0 0:03.99 init the code for chunking, although eventhough I don't use this code (just simple file upload), it still cause that high cpu usage function sendRequest() { //clean the screen //bars.innerHTML = ''; var file = document.getElementById('fileToUpload'); for(var i = 0; i < file.files.length; i++) { var blob = file.files[i]; var originalFileName = blob.name; var filePart = 0 const BYTES_PER_CHUNK = 100 * 1024 * 1024; // 10MB chunk sizes. var realFileSize = blob.size; var start = 0; var end = BYTES_PER_CHUNK; totalChunks = Math.ceil(realFileSize / BYTES_PER_CHUNK); alert(realFileSize); while( start < realFileSize ) { if (blob.webkitSlice) { //for Google Chrome var chunk = blob.webkitSlice(start, end); } else if (blob.mozSlice) { //for Mozilla Firefox var chunk = blob.mozSlice(start, end); } uploadFile(chunk, originalFileName, filePart, totalChunks, i); filePart++; start = end; end = start + BYTES_PER_CHUNK; } } }

    Read the article

  • Js (+Mootools) - Why my script use over 60% of processor?

    - by Misiur
    On this site - LINK - i need to use 3 banner scrollers (2x vertical + 1x horizontal). I've tried to do it in flash, but then everyone web browsers shut down, or suspended. Now i want to do it in JS (i use mootools). All data come from MySQL. Here's the complete code (even if you don't know mootools, You should understand it) global $wpdb; $table = $wpdb->prefix.'part'; $sql = "SELECT * FROM $table"; $q = $wpdb->get_results($sql); $g = 0; if($wpdb->num_rows > 0) { ?> <script type="text/javascript"> window.addEvent('load', function(){ var totall = 0; var totalr = 0; $$('#leftCont0 .contElement').each(function(el){ var img = new Asset.image(el.getFirst('a').getFirst('img').get('src')); totall += img.height; }); $$('#rightCont0 .contElement').each(function(el){ var img = new Asset.image(el.getFirst('a').getFirst('img').get('src')); totalr += img.height; }); $$('.leftCont').each(function(el){ var h = parseInt(el.get('id').substr(8)); el.setStyle('top', h * totall); }); $$('.rightCont').each(function(el){ var h = parseInt(el.get('id').substr(9)); el.setStyle('top', h * totalr); }); var total = new Array(totall, totalr); move.periodical(30, null, total); }); function move(num, num2) { var h = 0; var da = false; var target = null; $$('.leftCont').each(function(el){ var act = el.getStyle('top'); var n = parseInt(act)+1; el.setStyle('top', n+"px"); if(el.getStyle('top') < h) { h = parseInt(el.getStyle('top')); alert(h); } if(parseInt(el.getStyle('top')) > 400) { da = true; target = el; } }); if(da) { var n = h - num; target.setStyle('top', n+'px'); } h = 0; da = false; $$('.rightCont').each(function(el){ var act = el.getStyle('top'); var n = parseInt(act)+1; el.setStyle('top', n+"px"); if(el.getStyle('top') < h) { h = parseInt(el.getStyle('top')); alert(h); } if(parseInt(el.getStyle('top')) > 400) { da = true; target = el; } }); if(da) { var n = h - num2; target.setStyle('top', n+'px'); } } </script> <?php $g = 0; $l = 0; $r = 0; $leftContent = array(); $rightContent = array(); $leftHeight = 0; $rightHeight = 0; foreach($q as $q) { if(($g % 2) == 0) { $leftContent[$l] = '<div class="contElement"> <a href="'.$q->aurl.'"><img src="'.$q->imgurl.'" alt="Partner" /></a> </div>'; $lHeight = getimagesize($q->imgurl); $leftHeight .= $lHeight[1]; $l++; } else { $rightContent[$r] = '<div class="contElement"> <a href="'.$q->aurl.'"><img src="'.$q->imgurl.'" alt="Partner" /></a> </div>'; $rHeight = getimagesize($q->imgurl); $rightHeight .= $rHeight[1]; $r++; } $g++; } $quantity = ceil(400 / $leftHeight) + 1; for($i = 0; $i < $quantity; $i++) { $str = ""; for($j = 0; $j < sizeof($leftContent); $j++) { $str .= $leftContent[$j]; } $leftContainer[$i] = '<div class="leftCont" id="leftCont'.$i.'">'.$str.'</div>'; } $quantity = ceil(400 / $rightHeight) + 1; for($i = 0; $i < $quantity; $i++) { $str = ""; for($j = 0; $j < sizeof($rightContent); $j++) { $str .= $rightContent[$j]; } $rightContainer[$i] = '<div class="rightCont" id="rightCont'.$i.'">'.$str.'</div>'; } ?> <div id="pcl"> <?php for($i = 0; $i < sizeof($leftContainer); $i++) { echo $leftContainer[$i]; } ?> </div> <div id="pcr"> <?php for($i = 0; $i < sizeof($rightContainer); $i++) { echo $rightContainer[$i]; } ?> </div> <?php }

    Read the article

  • Changing text of TextView -- old text doesn't go away (Android 4.1.2)

    - by Jason Costabile
    I'm pretty new to Android development. Trying to accomplish something fairly simple -- change some displayed text when a timer ticks. Here's the potentially relevant code: CountDownTimer currentTimer; Resources res; TextView timerText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_exercise); res = getResources(); timerText = (TextView) findViewById(R.id.timer_text); } @Override protected void onStart() { super.onStart(); //"Get ready" countdown currentTimer = new CountDownTimer(5000, 1000) { @Override public void onTick(long millisUntilFinished) { timerText.setText("" + (int)Math.ceil(millisUntilFinished / 1000.0)); } @Override public void onFinish() { ... } }; currentTimer.start(); } This works fine on an emulated 4.2.2 device, but on a 4.1.2 device (both physical and emulated), the changed TextView appears as such while the countdown proceeds: If you can't tell, that's the numbers 5,4,3 overlayed. So, when I set a new string for the TextView, the new string is displayed but without replacing the old string. Any other TextViews used in my app behave in the same way. Any ideas what the problem is and how to fix it? Edit: From the XML layout file: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" tools:context=".ExerciseActivity" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:keepScreenOn="true" android:orientation="vertical" > ... <TextView android:id="@+id/timer_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:textIsSelectable="false" android:hint="@string/timer_default" /> ... </LinearLayout> That's all that could be relevant.

    Read the article

  • Connecting repeatable and non-repeatble backgrounds without a seam

    - by Stiggler
    I have a 700x300 background repeating seamlessly inside of the main content-div. Now I'd like to attach a div at the bottom of the content-div, containing a different background image that isn't repeatable, connecting seamlessly with the repeatable background above it. Essentially, the non-repeatable image will look like the end piece of the repeatable image. Due to the nature of the pattern, unless the full 300px height of the background image is visible in the last repeat of the content-div's backround, the background in the div below won't seamlessly connect. Basically, I need the content div's height to be a multiple of 300px under all circumstances. What's a good approach to this sort of problem? I've tried resizing the content-div on loading the page, but this only works as long as the content div doesn't contain any resizing, dynamic content, which is not my case: function adjustContentHeight() { // Setting content div's height to nearest upper multiple of column backgrounds height, // forcing it not to be cut-off when repeated. var contentBgHeight = 300; var contentHeight = $("#content").height(); var adjustedHeight = Math.ceil(contentHeight / contentBgHeight); $("#content").height(adjustedHeight * contentBgHeight); } $(document).ready(adjustContentHeight); What I'm looking for there is a way to respond to a div resizing event, but there doesn't seem to be such a thing. Also, please assume I have no access to the JS controlling the resizing of content in the content-div, though this is potentially a way of solving the problem. Another potential solution I was thinking off was to offset the background image in the bottom div by a certain amount depending on the height of the content-div. Again, the missing piece seems to be the ability to respond to a resize event.

    Read the article

  • MIDP 2.0 version issues: $method is undefined for $type

    - by Kilnr
    Hi, I've written a MIDlet that does several "advanced" things: fetching images from the web, resizing them, saving them on the phone, displaying them. This all works perfectly in the Nokia S60 3rd Edition FP1 emulator. This device has MIDP 2.0 and CLDC 1.1 support (also JSR75, which I need in order to save files). It also works as it should on the Nokia E71 (physical device). I then tried to run the MIDlet on several other emulators. One of them, the DefaultCldcJtwiPhone2 from the Java ME SDK 3.0, also claims MIDP 2.0 and CLDC 1.1 support. It doesn't have JSR75, which explains why "FileConnection can not be resolved to a type". This does not, however, explain why List.deleteAll(), String.equalsIgnoreCase(String) and a few others are undefined. The actual errors that I get: The method ceil(double) is undefined for the type Math The method deleteAll() is undefined for the type List The method equalsIgnoreCase(String) is undefined for the type String The method getWidth() is undefined for the type Displayable When I look at the MIDP 2.0 (i.e. JSR118) API (http://java.sun.com/javame/reference/apis/jsr118/), I can clearly see all of these methods being present, with the "since" tag being either MIDP 2.0 or CLDC 1.1. My question: why doesn't an emulator with MIDP 2.0 support have access to all MIDP 2.0 methods? Or alternatively, what am I doing wrong?

    Read the article

  • javascript: what does this syntax means?

    - by user1067138
    it is like this: (function () { //codes here })(); here is an example: (function () { var D = TED.EditorCore, E = TED.extend, A = TED.EditorInstanceManager, B = TED.augmentObject; window.TED["SimpleEditor"] = C; function C(F) { C.superclass.call(this, F) } C.defaultConfig = { height: "100px", width: "400px", //blablabla... flashNumLimit: 10, didaDelay: 300, imageWidthLimit: 570 }; E(C, D, { getContentLength: function () { return Math.ceil(this.filteHTML(this.editArea.innerHTML, ["img", "br"]).replace(/<img[^>]*>/gi, "mm").replace(/<br[^>]*>/gi, "m").replace(/&nbsp;/gi, "m").replace(/[^\x00-\xff]/g, "mm").length / 2) }, filteEditHTML: function () { return html = this.editArea.innerHTML.replace(/_moz_dirty=""/gi, "").replace(/\[/g, "[[-").replace(/\]/g, "-]]").replace(new RegExp("<\\/?(?:br[^>]*)>", "gi"), "[$1]").replace(new RegExp('<span([^>]*class="?at"?[^>]*)>', "gi"), "[span$1]").replace(new RegExp('<img([^>]*class="?(?:' + this.config.emptyClassName + "|" + this.config.smileyClassName + ')"?[^>]*)>', "gi"), "[img$1]").replace(/<[^>]*>/g, "").replace(/\[\[\-/g, "[").replace(/\-\]\]/g, "]").replace(new RegExp("\\[(/?(?:br|img|span)[^\\]]*)\\]", "gi"), "<$1>") }, filteSubmitHTML: function () { this.reLayout(); var G = this.editArea.innerHTML.replace(/_moz_dirty=""/gi, "").replace(/\[/g, "[[-").replace(/\]/g, "-]]").replace(new RegExp("<(/?(?:" + this.submitValidHTML.join("|") + ")[^>]*)>", "gi"), "[$1]").replace(new RegExp('<img([^>]*class="?(?:' + this.config.imageClassName + "|" + this.config.smileyClassName + "|" + this.config.flashClassName + "|" + this.config.musicClassName + ')"?[^>]*)>', "gi"), "[img$1]").replace(/<[^>]*>/g, "").replace(/\[\[\-/g, "[").replace(/\-\]\]/g, "]").replace(new RegExp("\\[(/?(?:" + this.submitValidHTML.join("|") + "|img)[^\\]]*)\\]", "gi"), "<$1>"); var F = document.createElement("div"); F.innerHTML = G; this.parseURL(F); return F.innerHTML } }); B(C, A) })(); what exactly does (funtion (){})(); do?

    Read the article

  • Rails: link_to_remote prototype helper with :with option

    - by Syed Aslam
    I am trying to grab the current value of a drop down list with Prototype and passing it along using :with like this <%= link_to_remote "today", :update => "choices", :url => { :action => "check_availability" } , :with => "'practitioner='+$F('practitioner')&'clinic='+$F('clinic')&'when=today'", :loading => "spinner.show(); $('submit').disable();", :complete => "spinner.hide(); $('submit').enable();" %> However, this is not working as expected. I am unable to access parameters in the controller as the link_to_remote helper is sending parameters like this: Parameters: {"succ"=>"function () {\n return this + 1;\n}", "action"=>"check_availability", "round"=>"function () {\n return __method.apply(null, [this].concat($A(arguments)));\n}", "ceil"=>"function () {\n return __method.apply(null, [this].concat($A(arguments)));\n}", "floor"=>"function () {\n return __method.apply(null, [this].concat($A(arguments)));\n}", "times"=>"function (iterator, context) {\n $R(0, this, true).each(iterator, context);\n return this;\n}", "toPaddedString"=>"function (length, radix) {\n var string = this.toString(radix || 10);\n return \"0\".times(length - string.length) + string;\n}", "toColorPart"=>"function () {\n return this.toPaddedString(2, 16);\n}", "abs"=>"function () {\n return __method.apply(null, [this].concat($A(arguments)));\n}", "controller"=>"main"} Where am I going wrong? Is there a better way to do this?

    Read the article

  • AS3 using PrintJob to print a MovieClip

    - by Chris Waugh
    Hello, I am currently trying to create a function which will allow me to pass in a movieclip and print it. Here is the simplified version of the function: function printMovieClip(clip:MovieClip) { var printJob:PrintJob = new PrintJob(); var numPages:int = 0; var printY:int = 0; var printHeight:Number; if ( printJob.start() ) { /* Resize movie clip to fit within page width */ if (clip.width > printJob.pageWidth) { clip.width = printJob.pageWidth; clip.scaleY = clip.scaleX; } numPages = Math.ceil(clip.height / printJob.pageHeight); /* Add pages to print job */ for (var i:int = 0; i < numPages; i++) { printJob.addPage(clip, new Rectangle(0, printY, printJob.pageWidth, printJob.pageHeight)); printY += printJob.pageHeight; } /* Send print job to printer */ printJob.send(); /* Delete job from memory */ printJob = null; } } printMovieClip( testMC ); Unfortunately this is not working as expected i.e. printing the full width of the Movieclip and doing page breaks on the length. Any help with this would be greatly appreciated. Many thanks, Chris

    Read the article

  • Display image background fully for last repeat in a div

    - by Stiggler
    I have a 700x300 background repeating seamlessly under the main content-div. Now I'd like to attach a div at the bottom of the content-div, containing a continuation-to-end of the background image, connecting seamlessly with the background above it. Due to the nature of the pattern, unless the full 300px height of the background image is visible in the last repeat of the content-div's backround, the background in the div below won't seamlessly connect. Basically, I need the content div's height to be a multiple of 300px under all circumstances. What's a good approach to this sort of problem? I've tried resizing the content-div on loading the page, but this only works as long as the content div doesn't contain any resizing, dynamic content, which is not my case: function adjustContentHeight() { // Setting content div's height to nearest upper multiple of column backgrounds height, // forcing it not to be cut-off when repeated. var contentBgHeight = 300; var contentHeight = $("#content").height(); var adjustedHeight = Math.ceil(contentHeight / contentBgHeight); $("#content").height(adjustedHeight * contentBgHeight); } $(document).ready(adjustContentHeight); What I'm looking for there is a way to respond to a div resizing event, but there doesn't seem to be such a thing. Also, please assume I have no access to the JS controlling the resizing of content in the content-div, though this is potentially a way of solving the problem. Another potential solution I was thinking off was to offset the background image in the bottom div by a certain amount depending on the height of the content-div. Again, the missing piece seems to be the ability to respond to a resize event.

    Read the article

  • function php with parameter 0

    - by Arnaud Ncy
    I have a function like this public function get_page($position) { switch ($position) { case "current": echo "current"; return $this->current_page; break; case "first": echo "first"; return $this->current_page >= 3 ? 1 : false; break; case "last": echo "last"; return $this->current_page <= $this->total_pages() - 2 ? ceil($this->count / $this->nb_items_to_show) : false; break; case "previous": echo "previous"; return $this->current_page - 1 >= 1 ? $this->current_page - 1 : false; break; case "next": echo "next"; return $this->current_page + 1 <= $this->total_pages() ? $this->current_page + 1 : false; break; case is_int($position): echo "int"; if ($position >= 1 && $position <= $this->total_pages()) { return $position; } else { return false; } break; default: echo "default"; return false; break; } } When I call the function, it works for every parameters except 0 and goes in "current" case in the switch. $paginator->get_page(0); If I call the function with quotes "0", it works. But the function could be called like this $paginator->get_page($paginator->get_page("current") - 2); How can I call the function with parameter 0 ?

    Read the article

  • How to handle pagination queries properly with mongodb and php?

    - by luckytaxi
    Am I doing this right? I went to look at some old PHP code w/ MySQL and I've managed to get it to work, however I'm wondering if there's a much "cleaner" and "faster" way of accomplishing this. First I would need to get the total number of "documents" $total_documents = $collection->find(array("tags" => $tag, "seeking" => $this->session->userdata('gender'), "gender" => $this->session->userdata('seeking')))->count(); $skip = (int)($docs_per_page * ($page - 1)); $limit = $docs_per_page; $total_pages = ceil($total_documents / $limit); // Query to populate array so I can display with pagination $data['result'] = $collection->find(array("tags" => $tag, "seeking" => $this->session->userdata('gender'), "gender" => $this->session->userdata('seeking')))->limit($limit)->skip($skip)->sort(array("_id" => -1)); My question is, can I run the query in one shot? I'm basically running the same query twice, except the second time I'm passing the value to skip between records.

    Read the article

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