Posts

Showing posts from August, 2015

mysql - Php select from two tables not working correctly -

hello have 2 tables seo_settings | cat_id | cat_fullname | | 971 | catname 1 | | 443 | catname 2 | jcategories_to_hcategories | jcategory_id | hcategory_id | | 1 | 971 | | 2 | 443 | | 3 | 443 | and want cat_fullname category id i using $catids = array(1,2,3) foreach($catids $catid) { $sql3 = mysql_query("select a.cat_fullname seo_settings a, jcategories_to_hcategories b a.cat_id = b.hcategory_id , b.jcategory_id = $catid "); $data3 = mysql_fetch_array($sql3); } but $data3 return booleanfalse important there rows , connected correctly assume there problem in sql probably. try this $catids = array(1,2,3); $query = " select a.cat_fullname seo_settings left join jcategories_to_hcategories b on jcategories_to_hcategories b b.jcategory_id in (".implode(",", $catids).") "; $sql3 = mysql_query($query) or die(mysql_error()); while($data3 = m...

binding - How to bind a form to an SQL statement in microsoft access -

**edit hello tryng include sql statement in vba can sort through data , filter. have found way include sql in vba error says "the runsql action requires sql statement" sql statement within strsql variable. private sub buttonnot_click() dim strsql string strsql = "select table1.[firstnam], table1.[lastnam]" & _ "from table1 " & _ "where ((([firstnam]) <> 'jamie') , (([lastnam]) <> 'cartman'));" docmd.runsql strsql me.filter = "" me.filter = "firstnam<>'jamie' , lastnam<>'cartman'" end sub me.recordsource = {sql string} make sure turn filter on after appending query string.

count - Select Last of each ID in Excel -

i have table in excel multiple map units, , value corresponding each map unit. map units listed multiple times, , want last value each map unit selected. for example: mapunit = 1 ; value = 2 mapunit = 1 ; value = 4 mapunit = 1 ; value = 1 map unit =2 ; value = 3 mapunit=2 ; value = 4 mapunit = 3; value = 2 mapunit = 4; value =1 mapunit = 4; value = 5 and want output like: mapunit =1 ; value = 1 mapunit = 2; value = 4 mapunit =3 ; value = 2 mapunit =4 ; value = 5 is there formula in excel or sql query this? thank you! ok, think should work. assumptions cells reference above in a1:b9 (with column headers in row 1) , i'm putting unique mapunit numbers in column e , formulas going column f . =index(offset($b$1,match(e2,$a$2:$a$9,0),0,countif($a$2:$a$9,e2),1),countif($a$2:$a$9,e2)) please let me know if need clarification. edit: in case list of unique mapunit values longer, can make list copying original column , doing remove dupl...

c# - Why can't I access methods specific to my child class? -

in c#, have parent class public member. want derive parent class, derive class of public member, create , access new methods, follows... public class animal { } public class sheep : animal { public void makealamb() { } } public class farm { public animal myanimal; } public class sheepfarm : farm { public void sheepfarm() { this.myanimal = new sheep(); this.myanimal.makealamb(); } } this code doesn't compile. "animal not contain definition makealamb()". want essence of polymorphism, no? missing? i'm looking forward finding out. thanks in advance! if i'm guessing correctly you're intending do, consider using generics: public class farm<tanimal> tanimal : animal { public tanimal myanimal; } public class sheepfarm : farm<sheep> { public void sheepfarm() { this.myanimal = new sheep(); this.myanimal.makealamb(); } ...

logging - Log to file and console python -

i'm using python's logging module log debug strings file give me log use script attached don't give me output screen how can show print in screen , print log formatt ? help? class streamtologger(object): """ fake file-like stream object redirects writes logger instance. """ def __init__(self, logger, log_level=logging.info): self.logger = logger self.log_level = log_level self.linebuf = '' def write(self, buf): line in buf.rstrip().splitlines(): self.logger.log(self.log_level, line.rstrip()) logging.basicconfig( level=logging.debug, format='%(asctime)s:%(levelname)s:%(name)s:%(message)s', filename="out.log", filemode='a' ) stdout_logger = logging.getlogger('stdout') sl = streamtologger(stdout_logger, logging.info) sys.stdout = sl #stderr_logger = logging.getlogger('stderr') #sl = streamtologger(stderr_logger, logging.error) ...

Cordova showing shows default splash screen in iOS? -

i working on small app ios, replace images inside platforms/ios/app/resources/splash own images, still showing default image, ideas why doing this? here option can use command-option-shift-k clean out build folder. quit xcode , using terminal clean ~/library/developer/xcode/deriveddata manually. remove contents because there's bug xcode run old version of project that's in there somewhere. go terminal open app, run, cordova build ios, cordova prepare ios

python - nosetests/unittest still shows error when test passes? -

i have unit test tests if api point unaccessible if not authenticated this: def test_endpoint_get_unauth(self): r = self.get('/api/endpoint/1') self.assertstatuscode(r, 401) the test passes, nosetests/unittest still shows me error exception raised saying "not authorized." there anyway stop this? full log: error in views [/myenv/lib/python2.7/site-packages/flask_restless/views.py:115]: not authorized -------------------------------------------------------------------------------- traceback (most recent call last): file "/myapp/myenv/lib/python2.7/site-packages/flask_restless/views.py", line 113, in decorator return func(*args, **kw) file "/myapp/myenv/lib/python2.7/site-packages/flask/views.py", line 84, in view return self.dispatch_request(*args, **kwargs) file "/myapp/myenv/lib/python2.7/site-packages/flask/views.py", line 149, in dispatch_request return meth(*args, **kwargs) file "/myapp/myen...

java - How to enumerate vertices in Geometry in JTS? -

java topology suite has geometry class, has getnumpoints() method. according documentation, counts vertices in constituent geometries. how enumerate these points? can obtained getcoordinates() method, looks not optimal, since (1) not iterative , (2) requires convert each coordinate tuple point geomertfactory . as have proper geometry type linestring or polygon, use (cast geometry it), can use getpointn(index) . coordinates not points way. coordinate not geometry in jts, class hold numeric values. points actual geometries.

ruby on rails - Issue converting currency from string in before_validation callback -

i'm having issue stripping dollar signs , commas out of currency before validations run. reason value being set 0 when saved. class property < activerecord::base before_validation :format_currency validates :street_name_1, presence: true validates :city, presence: true validates :state, presence: true validates :postal_code, presence: true validates :rate, presence: true, numericality: true private def format_currency self.rate = rate.to_s.gsub(/[^0-9\.]/, '').to_i # strip out non-numeric characters end end when '$3,500'.to_s.gsub(/[^0-9\.]/, '').to_i in rails console correctly returns "3500". rate being passed in model form well. for life of me can't figure out why it's not setting value on save. appreciated. edit: needed override default setter , gsub when rate set due database column being integer. def rate=(rate) write_attribute(:rate, rate.to_s.gsub(/[^0-9\.]/, '').to_i) end ...

mysql - #1064 Syntax Error, Simple Search and Replace Command? -

switching wordpress databases, , attempting run search , replace command change permalinks. use ruepi; update [table_name] set [field_name] = replace([field_name],'[http://131.193.220.64/ruepi]','[http://ruepi.uic.edu]'); i getting back: sql query: update [table_name] set [field_name] = replace( [field_name], '[http://131.193.220.64/ruepi]', '[http://ruepi.uic.edu]' ) ; mysql said: documentation #1064 - have error in sql syntax; check manual corresponds mysql server version right syntax use near '[table_name] set [field_name] = replace([field_name],'[http://131.193.220.64/rue' @ line 1 not sure syntax wrong? if on real quick. edit: still getting #1146 error, same error got when trying command: update table_name set field_name = replace(field_name, 'http://131.193.220.64/ruepi', 'http://ruepi.uic.edu/'); error: error sql query: update `table_name` set `field_name` = 'http://131....

Why is this PHP code accessing a MySQL database not working? -

<?php require('database.php'); $user = $_post["username"]; $password = $_post["password"]; $location = $_post["location"]; $stmt = $mysqli->prepare("insert userinfo (username, password, location) values (?, ?, ?)"); if(!$stmt) { //printf("query prep failed: %s\n", mysqli->error); echo "query prep failed".$mysqli->error; exit; } $stmt->bind_param('sss', $username, $password, $location); $stmt->execute(); $stmt->close(); error_log("username ".$user, 3, "/tmp/php_error.log"); } ?> database.php <?php $mysqli = new mysqli('localhost', 'php', 'passtheword', 'android'); if($mysqli->connect_errno) { printf("connection failed: %s\n", $mysqli->connect_error); exit; } ?> this query not modifying database reason. know 'database.php' valid, , do...

batch file - I can't get a variable of loop -

i trying write simple batch file the script gets namefile file "dump" , split string, can't display variable !! for /r %%a in (dump\*) ( set file=%%a /f %%i in ("%%a") ( /f "tokens=1 delims=-" %%d in ("%%~ni") set db=%%d ) echo %db% ) pause any ideas? thanks help. try setting setlocal enabledelayedexpansion , swapping var exclamation marks instead, see below: setlocal enabledelayedexpansion /r %%a in (dump\*) ( set file=%%a /f %%i in ("%%a") ( /f "tokens=1 delims=-" %%d in ("%%~ni") set db=%%d ) echo !db! ) pause

Using post method in PHP to save data to database -

this question has answer here: what enctype='multipart/form-data' mean? 7 answers reference - error mean in php? 29 answers i'm checking whether or not text box has value or not before saving database. i'm creating movie website, validation working fine. the problem saving, i'm uploading picture movie. picture being upload folder web site application directory, problem here i'm having error code while clicking on save notice: undefined index: photoimg in c:\xampp\htdocs\star_crud\home.php on line 233 notice: undefined index: photoimg in c:\xampp\htdocs\star_crud\home.php on line 234 my code below : if (isset($_post['create'])) { // keep track post values $cast = $_post['cast']; $title = $_post['title...

c++ - Seemingly pointless #define of function -

i've encountered code along lines of: bool cblahclass::somefunction(dword *pdw) { return_false_if_file_doesnt_exist //the rest of code makes sense... //... } everything see makes pretty sense except have little question line return_false_if_file_doesnt_exist i searched string , find #define: #define return_false_if_file_doesnt_exist \ if (false==doesfileexist()) return false; my question is... hell? there reason make #define this? why not write: bool cblahclass::somefunction(dword *pdw) { if ( false == doesfileexist() ) return false //the rest of code makes sense... //... } the reason can think of is little bit easier , little less annoying write out "return_false_if_file_doesnt_exist" write out "if (false==doesfileexist()) return false". anyone see other reason this? there name sort of thing? well, idea behind using macro simplify maintenance in situations when specific check might change....

How to pass javascript variables to rails variables -

how can pass javascript variable ruby. want don't know how express it. function save(){ var g = document.getelementbyid("self").value; <% @owner.info = g %> } another possible work around need able extract contents of text area through rails , not javascript. can me? what attempting doesn't make sense vanilla rails installation , javascript. here's workflow accomplishes you're trying along details: 1. page requested server the ruby code runs rails , application executed on server. server receives request, executes ruby code, , sends response html document. 2. user gets response server the user's browser receives html , turns pretty web page. it's @ point javascript related application executed in user's browser. connection server has been severed , no further ruby code executed until request made. 3. user fills out ajax form on page rendered in step 2, have form. following this guide can tell form submi...

javascript - Knockout: Make observable object from array -

i have thought simple question solve... apparently not. i have server returns list of objects (json) loads database. database, objects have id attribute unique: { "stores": [ { "id": "1f0", "name": "foo", "address": "foo here street" }, { "id": "2b4", "name": "bar", "address": "bar here street" }, { "id": "3b4", "name": "baz", "address": "baz here street" } ] } the idea pretty simple: want create observable (i'm guessing want observablearray ) instead of array want object attributes id attribute , value whole store object: { "1f0": { "id": "1f0", "name"...

ios - Value retrieval from KeychainItem -

i tried retrieving string keychainitem, stored below: @property (nonatomic, strong) keychainitemwrapper *account; if (account == nil) { account = [[keychainitemwrapper alloc] initwithidentifier:@"test" accessgroup:nil] } [account setobject:self.username forkey:(__bridge id)(ksecattraccount)]; [account setobject:@"c6a07d48aabf35b26e1623fb" forkey:(__bridge id)(ksecvaluedata)]; when retrieved below: keychainitemwrapper *wrapper = [[keychainitemwrapper alloc] initwithidentifier:@"test" accessgroup:nil]; self.account = wrapper; } nsstring *prevusername = [account objectforkey:(__bridge id)(ksecattraccount)]; nsstring *token = [account objectforkey:(__bridge id)(ksecvaluedata)]; i received following value nslog(@"%@",token); <63346264 32636462 64653234 34313862 38633537 31326235 66653464 63303731> how retreive string saved? doing wrong here? try this: nsdata *namedata= [account objectf...

ios - PFQueryTableViewController bringing duplicate results - Pagination -

i using pfquerytableviewcontroller retrieve objects parse database. using pagination improve performance of app. however, when ask load more objects queryfortable gets executed again , bring same results again. do guys know whether bug or there can do. here code: - (pfquery *)queryfortable { nslog(@"to aqui %@",self.location.name); pfquery *imagequery = [pfquery querywithclassname:@"wallimageobject"]; [imagequery wherekey:@"geopoint" neargeopoint:self.location.coordinatesingeopoint withinkilometers:0.5]; [imagequery wherekey:@"venuename" equalto:self.location.name]; [imagequery orderbydescending:@"createdat"]; // if pull refresh enabled, query against network default. if (self.pulltorefreshenabled) { imagequery.cachepolicy = kpfcachepolicynetworkonly; } // if no objects loaded in memory, cache first fill table // , subsequently query against network. if (self.objec...

mysql - Increment integer field by 1 starting from a certain row -

table1: id, field1(integer), field2, ... as shown above field1 integer serialized 1 100 i enter new record field1 value 45 php form. given value exists in table (from 1 100) **i want query store new record before existing 1 in table , increment field1 values starting second 45 ** thanks help! i recommend against this. normally, should insert rows in order. if want sort, sort name, or relevant value. if want reason have particular sort order, can in 2 update statements: 1: shift rows make room new row. update yourtable set field1 = field1 + 1 field1 >= 45 2: insert new row. insert yourtable (field1) values (45) as can tell, can become inefficient, since updating rows. if table becomes larger, take more time insert rows, @ beginning. if need can optimize little, instance, keeping gaps between rows. if have numbering in steps of 100, can insert row @ 4450, right between 4400 , 4500. need renumber when there no gap between records want insert new ro...

php - Drupal build custom query between taxonomy and content -

i received project coded else on drupal 7 apparently not follow of drupal's standards , coded website overwriting template system (and late modify or edit of current structure). i have following issue need build custom query: the data in cms created such: category (created in taxonomy) -> subcategory (created content type) -> item (created content type) when adding entries in cms, workflow such: first create main category taxonomy (named category) the create subcategory contents when adding/editing subcategory, select parent category radio list and items selected checkbox list i have taken screenshots cms make things clearer regarding structure, can found here: http://dropcanvas.com/qdokx/ the problem not being able build view @ all, need create custom query can following: read categories read subcategories belonging each category read items under each category with php, generate custom html using loops on above data the purpose of on web...

Android styles.xml windowNoTitle (ActionBarActivity) -

i want hide title bar (where activity tile shown) in application. i'm doing setting android:windownotitle item true . works fine devices api level 19. tested device running api level 10 , hides notification bar. tile bar still shown. here res/values/styles.xml <resources> <style name="appbasetheme" parent="theme.appcompat.light"> <item name="android:windownotitle">true</item> <item name="android:windowfullscreen">true</item> </style> </resources> edit: i'm using appbasetheme theme in manifest. there no other styles.xml files in other value-vxx folder. edit#2: i'm extending actionbaractivity activity. i use 1 theme devices , works on api level 8 16 (since have 5 physical devices). i'm sure it's working on 17-19 devices too. make sure in manifest file (in application section), there line android:theme="@style/apptheme" ...

What's the different between the Java and Clojure code? -

eventloopgroup bossgroup = new nioeventloopgroup(); // (1) eventloopgroup workergroup = new nioeventloopgroup(); try { serverbootstrap b = new serverbootstrap(); // (2) b.group(bossgroup, workergroup) .channel(nioserversocketchannel.class) // (3) .childhandler(new channelinitializer<socketchannel>() { // (4) @override public void initchannel(socketchannel ch) throws exception { ch.pipeline().addlast( new 6messagedecoder(), new loginhandler()); } }) .option(channeloption.so_backlog, 128 ) // (5) .childoption(channeloption.so_keepalive, true); // (6) // bind , start accept incoming connections. channelfuture f = b.bind(port).sync(); // (7) // wait until server socket closed. // in example, not happen, can gracefully // shut down server. f.chan...

SQL - operate on current condition row -

i'd illustrate question using free sql 'simulator': http://sqlzoo.net/wiki/select_from_nobel_tutorial assume please given list of subject/winner pairs (i put them in where..or clauses) , want them listed in result additional flag 'is in db?' y/n. i tried prepare sth like: select subject, winner, ( case when winner null 'n' else 'y' ) "is in db?" nobel (subject='literature' , winner='saint-john perse') or (subject='medicine' , winner='sir frank macfarlane burnet') or (subject='medicine' , winner='peter medawar') or (subject='medicine' , winner='christiano ronaldo') only last or condition won't give result. despite listed flag n, otherwise wouldn't put case sentence existing rows. not sure either if case sentence correct @ all. tried case winner when null 'n' possibly select in select or temporary table? kindly advise you didn...

jquery - Hide ClearButton from Primefaces-Mobile InputText -

Image
i'm using primefaces 5.0 , i'm trying build mobile page. primefaces-mobile built on jquery mobile. the following line <p:inputtext value="#{whatever}" /> is giving me output: this because using clear button option of jquery mobile. can see textfield pretty small , need space clear button taking, want remove it. any suggestions? primefaces-mobile known not supporting jquery mobile features. first try can can check if supported: <p:inputtext value="#{whatever}" pt:data-clear-btn="false"/> if doesn't work can cheat: html: <div class="remove-clear"> <p:inputtext value="#{whatever}"/> </div> css: .remove-clear .ui-input-text { display: none; } .remove-clear .ui-input-has-clear { padding-right: 0 !important; } working example (unfortunately can show how cheat directly in jquery mobile) : http://jsfiddle.net/gajotres/jwtgq/

css - Font-face not working with Sass -

i think know i'm doing when comes font-face , sass, not time seems. i'm trying use http://www.fontsquirrel.com/fonts/theano-didot on http://tjob.be/ . used fontsquirrel generator ttf usual , files seem fine. so why isn't showing correct font? the heading instance, says "tjobbe andrews freelance photographer , web designer" should in font, not georgia. i'm getting same cross-browser, mobile , desktop. totally stumped. relevant css: h1, h2, h3, h4, h5, h6 { font-family: "theano_didotregular"; src: url("theanodidot-regular-webfont.eot"); src: url("theanodidot-regular-webfont.eot?#iefix") format("embedded-opentype"), url("theanodidot-regular-webfont.woff") format("woff"), url("theanodidot-regular-webfont.ttf") format("truetype"), url("theanodidot-regular-webfont.svg#theano_didotregular") format("svg"); } relevant h...

objective c - ios - get initial data from server on app start -

i'm new ios development , trying solve following problem. in app (which speaks rest api) want make initial request server on app start user info. decided use separate service class singleton method. makes request server once , returns user instance. @implementation lsshareduser + (lsuser *)getuser { // make request api server on first call // on other calls return initialized user static lsuser *_shareduser = nil; static dispatch_once_t oncetoken; dispatch_once(&oncetoken, ^{ lshttpclient *api = [lshttpclient create]; [api getuser:^(afhttprequestoperation *operation, id user) { _shareduser = [[lsuser alloc] initwithdictionary:user]; } failure:nil]; }); return _shareduser; } @end my question proper way of initializing global data server? see request async (with afnetworking lib) return null until request finished. another problem here once failed (bad connection example) user null forever. update code this static l...

c# - Calculate power of a negative number -

i relatively new c# , since math.pow(x,y) returns nan negative number(read: not negative power), want know how calculate result more efficiently. doing write basic loop, want know if can implemented in shorter way (using linq maybe)? for(int i=0;i<power;i++) { result = result * num; } math.pow(x,y) returns nan negative number. that's because arbitrary exponentiation not defined negative base: http://en.wikipedia.org/wiki/exponentiation when base b positive real number, b n can defined real , complex exponents n via exponential function now, exponentiation of negative numbers real result defined if power integer, in case, pow not calculate you. should is: suppose want know pow(-2, 5) give pow problem pow(2, 5) instead. look @ exponent; if number you've got right answer. if odd number, make answer negative. so in case, pow(2, 5) returns 32. exponent 5 odd, make -32, , you're done.

Implementing android custom progress bar -

i'm new in android development , wanted know if can give me suggestion how implement somthing this. i want implement custom progress bar this , want able somthing after progress bar passing each 1 of vertical lines , number of vertical lines should customizable programmatically. somthing play specific sound or display specific toast or anything. sorry if question dumb , time. update: lets say, progress based on time in seconds , lines equal numbers of seconds. example whole progress in 40s , lines in 10th, 20th , 30th seconds. you can set max value of progress bar: progressbar.setmax(4); // or whatever number of notches want edit : sleep 1000 milliseconds (1 second), , update progress bar. keep updating until reaches max value. private void startprogressthread() { new thread(new runnable() { @override public void run() { while (progressbar.getprogress() < progressbar.getmax()) { // wait 1 second ...

html - How to parse form array in golang Beego -

how parse html form array beego. <input name="names[]" type="text" /> <input name="names[]" type="text" /> <input name="names[]" type="text" /> go beego type rsvp struct { id int `form:"-"` names []string `form:"names[]"` } rsvp := rsvp{} if err := this.parseform(&rsvp); err != nil { //handle error } input := this.input() fmt.printf("%+v\n", input) // map[names[]:[name1 name2 name3]] fmt.printf("%+v\n", rsvp) // {names:[]} why beego parseform method return empty names? how values rsvp.names? as can see implementation of formvalue method of request, returns first value in case of multiple ones: http://golang.org/src/pkg/net/http/request.go?s=23078:23124#l795 better attribute r.form[key] , iterate on results manually. not sure how beego works, using raw request.parseform , request.form or request.postform maps should job...

Ado.net C# login check Ms Sql using a windows form application -

hi tring develope login screen. in windows form aplication. got: private void button1_click(object sender, eventargs e) { if ((textbox1.text == "") || (textbox2.text == "")) { messagebox.show("bu alanları boş bırakamazsınız.", "chat giriş", messageboxbuttons.ok, messageboxicon.error); return; } sqlconnection conn = new sqlconnection(); conn.connectionstring = "server=cagdas-laptop;database=chat;trusted_connection=true;"; conn.open(); dataset ds = new dataset(); sqldataadapter sda = new sqldataadapter("select * kullanici kul_adi='" + textbox1.text + "' , sifre='" + textbox2.text + "'", conn); sda.fill(ds); if (ds.tables.count == 0) { messagebox.show("geçersiz kullanıcı.", "chat giriş", messageboxbuttons.ok, messageboxicon.error); } e...

javascript - Why wont this return the image from an object to display the image in html? -

Image
updated code & image it looks images each of returned objects in query "undefined" parse.com , javascript. i've managed code return object want, want take out "pic" url can show on html page. i've looked, struggle see examples of how pull out attributes of class. the below shows approach, thats returning bad url shown in screen shot. what have done wrong here? var currentuser = parse.user.current(); var friendrequest = parse.object.extend("friendrequest"); var query = new parse.query(friendrequest); query.include('touser'); query.equalto("fromuser", currentuser); query.equalto("status", "request sent"); //query.exists("pic"); query.find({ success: function(results) { // if query successful, store each image url in array of image url's imageurls = []; (var = 0; < results.length; i++) { var...

string - google python class strings2.py exercise E -

what happens @ line ? why -1 ? if n != -1 e. not_bad given string, find first appearance of substring 'not' , 'bad'. if 'bad' follows 'not', replace whole 'not'...'bad' substring 'good'. return resulting string. 'this dinner not bad!' yields: dinner good! def not_bad(s): n = s.find('not') b = s.find('bad') if n != -1 , b != -1 , b > n: s = s[:n] + 'good' + s[b+3:] return s -1 means substring not found. from official python documentation : return lowest index in s substring sub found such sub wholly contained in s[start:end]. return -1 on failure. defaults start , end , interpretation of negative values same slices.

c++ - Radix Sort using queues -

my program takes unsorted array , sorts in using radix sort. radix sort uses array of queues, 1 per possible digit , runs through each digit , places array until place values run through , array sorted. right sort doesn't run properly, spits out improper values, believe has how placing them array. appreciated, thanks. #include <iostream> #include <queue> #include <ctime> #include <cstdlib> using namespace std; int *radixsort(int q[]); int main() { const int max=1000; int radix[max], *sortedradix; int seed =time(0); srand(seed); //fill array random #s (int i=0;i<max;i++){ int num=0+rand()%max; radix[i]=num; } //print unsorted (int j=0;j<max;j++) cout << radix[j] << " "; cout << endl << endl; //radix sort sortedradix=radixsort(radix); //print sorted (int j=0;j<max;j++) cout << sortedradix[j] << " "; cout << endl <<endl; cout<<"flag"; return...

PHP convert html special chars like accents to show properly -

i have simple web page data $_post users input: comments, usernames, etc. , send them email , save them on database. problem when send email, doesn't matter client is, see gibberish. tried declaring meta tag in emails iso 88xx, utf8, windows, etc., no success. tried million examples of htmlentities(), leading same thing... plain gibberish. (althought source code shows different things sometimes, plain text never changes). example code: if (isset($_post['name'])) { $name = htmlentities($_post['name'], ent_quotes); } a result of mail() of $name (don quijóte) "don quijóte". sorry if repost can't working. have tried setting headers, like... // set content-type when sending html email $headers = "mime-version: 1.0" . "\r\n"; $headers .= "content-type:plain/text;charset=utf-8" . "\r\n"; mail($to,$subject,$message,$headers); this sets encoding utf-8. more here: http://www.w3schools.com/php/...

r - Rainfall data, can't get value of table? -

i tried analyse rainfall data. problem have data in format: head(dati) x x.1 x.2 x.3 1. stat 2. stat 3.stat 4. stat 5. stat 2 2013 1 val01 00:00 0 0.7 0.2 3 2013 1 val01 01:00 0 0.5 0.2 4 2013 1 val01 02:00 0 0 0.2 5 2013 1 val01 03:00 0 0 0 6 2013 1 val01 04:00 0 0 0.1 7 2013 1 val01 05:00 0 0 0 as see there spaces in columns, , when try dati[1,5] [1] 0.7 53 levels: 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 1.1 1.2 1.3 ... hprab i understand need 1 number: 0.7. how can , why there information levels? my code was: dati<-read.csv2("precipitation.csv", header = true,row.names=null, sep = ";", quote = "", dec = "," , fill = true, comment.char = "") attach(dati) dati[...

Square-Connect 500 error when trying to delete batch of items -

received 500 internal server error executing post of https://connect.squareup.com/v1/batch with json object {"requests":[ {"method":"delete", "relative_path":"/v1/me/items/13fd1363-2e1f-4b55-bfbf-f58b97814cfa", "access_token":"xxx-xxxxxxxxxxxxxxxxxx"}, {"method":"delete", "relative_path":"/v1/me/items/9d415859-8758-4147-aa16-7088c84bb201", "access_token":"xxx-xxxxxxxxxxxxxxxxxx"} ]} when same items deleted individually there no problem: delete https://connect.squareup.com/v1/me/items/13fd1363-2e1f-4b55-bfbf-f58b97814cfa also, have been able execute inventory adjustments in batch think technique ok. is bug or doing wrong? i'm amending original post include sample response suggested [ { "status_code": 200, "body": {}, "request_id": "0" }, { "status_code...

android - Refer an integer from Service to Service -

i building app needs pass integer 1 service other service. firstservice package com.jebinga.myapp; import android.app.service; import android.content.intent; import android.hardware.sensor; import android.hardware.sensorevent; import android.hardware.sensoreventlistener; import android.hardware.sensormanager; import android.os.bundle; import android.os.handler; import android.os.ibinder; import android.util.log; import android.view.menuitem; import android.widget.textview; public class firstservice extends service implements sensoreventlistener { int value1=10; @override public void oncreate() { super.oncreate(); bundle korb=new bundle(); korb.putint("ente", value1); intent in = new intent(firstservice.this, secondservice.class); in.putextra("korb", korb); this.startservice(in); system.err.println("firstservice value1: "+value1); } @override public ibind...

java - Threads execute not at the same time -

i have 3 threads, each thread have manipulation instance(q) of same class (q), periodically (that's why use thread.sleep() in method somecheck). main task make thread execute not @ same time, @ 1 time can execute 1 thread. tried put content of run method each thread synchronized (q){}, not understand put notify , wait methods. class q { boolean somecheck(int threadsleeptime){ //somecheck__section, if want stop thread - return false; try{ thread.sleep(threadsleeptime); } catch (interruptedexception e) { } return true; } } class threadfirst extends thread { private q q; threadfirst(q q){this.q=q;} public void run(){ do{ //working object of class q } while(q.somecheck(10)); } } class threadsecond extends thread { private q q; threadsecond(q q){this.q=q;} public void run(){ do{ //working ob...

node.js - What does err and doc mean in cursor.toArray(function(err, docs){})? -

this official mongodb documentation . toarray cursor.toarray(function(err, docs){}) converts cursor object array of matching records. convenient way retrieve results careful large datasets every record loaded memory. collection.find().toarray(function(err, docs){ console.log("retrieved records:"); console.log(docs); }); what err , doc mean in cursor.toarray(function(err, docs){})? docs array documents returned cursor. when there error, err object describes error.

Regex to search for a phrase -

hy, please me regex find phrases in text. my regex not ok. assumption phrases begin uppercase , end dot, , between can contain anything. \b([a-z]+[aa-zz]*\b(.)+) sincerly, you can use following if between phrase doesn't consist of dot. [a-z][^.]*\. or perhaps, try using following. [a-z].*?\.

python - Connect two sockets together without writing byte-manipulating plumbing code? -

in python, possible connect 2 sockets without writing byte-manipulating plumbing code? for example, write program interacts user (request/response format) , after that, performs tcp connection host , hands on stdin/stdout sockets. so data received on stdin sent on tcp socket, , data received tcp socket sent stdout - simultaneously, instantly, without either of them blocking. what recommended way of doing this? i'd avoid writing load of socket code if possible , have 'just work'. edit: first post didn't answer op wanted. revised significantly. """ open terminal , run nc -l 8080 type in both terminals> """ import sys socket import socket, af_inet, sock_stream select import select host = 'localhost' port = 8080 sock = socket(af_inet, sock_stream) sock.connect((host, port)) reader = sock.makefile('r', 0) writer = sock.makefile('w', 0) while true: ins, _, _ = select([reader, sys.stdin],[],[])...

javascript - Query returns items in console log, but html is showing Uncaught TypeError: Cannot call method 'get' of undefined when trying to display on the page -

parse.com , javascript sdk. the code queries , returns results should display in id "imgs". @ moment i'm getting uncaught typeerror: cannot call method 'get' of undefined error. i've tried, cannot understand whats causing or how fix it. a url page here http://kudosoo.com/friendslisttest.html driving me mad... var currentuser = parse.user.current(); var friendrequest = parse.object.extend("friendrequest"); var query = new parse.query(friendrequest); query.include('touser'); // query.include('fromuser'); //query.include('pic'); query.equalto("fromuser", currentuser); query.equalto("status", "request sent"); query.find({ success: function(results) { // if query successful, store each image url in array of image url's imageurls = []; (var = 0; < results.length; i++) { var object = resul...

python - How to return the most similar word from a list of words? -

how create function returns similar word list of words, if word not same? the function should have 2 inputs: 1 word , other list. function should return word similar word. lst = ['apple','app','banana store','pear','beer'] func('apple inc.',lst) >>'apple' func('banana',lst) >>'banana store' from doing research, seems have use concepts of fuzzy string matching, nltk, , levenshtein-distance, i'm having hard time trying implement in creating function this. i should point out similar, mean characters , i'm not concerned meaning of word @ all. slow solution debugging: def func(word, lst): items = sorted((dist(word, w), w) w in lst) # print items here debugging. if not items: raise valueerror('list of words empty.') return items[0][1] or, faster , uses less memory: def func(word, lst): return min((dist(word, w), w) w in lst)[1] see https://stackover...

ios - Storyboard initWithCoder ok, but when is encodeWithCoder called -

i experimenting storyboard , nscoder. initwithcoder called right, when viewcontroller being loaded storyboard. how , when call encodewithcoder? guess done storyboard loading other view or disposing viewcontroller. tried dismissviewcontrolleranimated on viewcontroller containing encodewithcoder method. any idea? thanks encodewithcode called when object serialized byte stream can written disk / send on network or ... storyboard never called never written disk read disk

function - scheme, search-last funcion whithout several expressions -

i must create function - (search-last x list), made this: (define (search-last o lst) (let loop ((lst lst)) (if (eqv? (caar lst) o) (cdar lst) (if (pair? (cdr lst)) (loop (cdr lst)) o)))) but ex. (define l '((1 . 2) (2 . 5) (3 . 5) (2 . 1))) should 1 output 5 know made mistake dont know how can improve it. cant use expression "!" , vector, for, while, set, sort, reverse, list-ref, list-tail, append, length. a tail recursive solution using named let (define (search-last o lst) (let loop ((lst lst) (match #f)) ; when not found match #f (cond ((null? lst) match) ; return last match @ end ((eqv? (caar lst) o) ; when found (loop (cdr lst) (cdar lst))) ; recurse new match (else (loop (cdr lst) match))))); or keep old match

flask - Python import error. Circular imports -

i'm creating simple flask app. i'm using blueprints provide views , openid login. have faced problem when try import created openid object file views interpreter throws import error. traceback (most recent call last): file "/.../proglist/proglist.py", line 11, in <module> views_admin import views views_a file "/.../proglist/views_admin.py", line 4, in <module> proglist import open_id file "/.../proglist/proglist.py", line 11, in <module> views_admin import views views_a importerror: cannot import name 'views' proglist.py # importing views views import views views_admin import views views_a ... open_id = openid(app, 'temp_dir_path') views_admin.py from proglist import open_id ... @views.route("/login", methods=["get", "post"]) @open_id.loginhandler def login(): i have been struggling problem hours , couldn't find answer. thank help. ...

ruby - Generate all way of arranging a given number of elements -

i generate possible way of arranging of number of elements number_of_elements . now, want print every possibility possibility upto . edit : number_of_elements 3, want possible ways of arranging 0 , 1 , 2 . a number can appear 0 or many times, , order important . 0 != 00 != 01 != 10 != 11 . for example, all_combinations(3, 14) should print: 0 1 2 00 01 02 10 11 12 20 21 22 000 # updated. put 100 here mistake. 001 ... i tried this: def all_combinations(number_of_elements, upto) 0.upto upto |n| puts n.to_s(number_of_elements) end end all_combinations(3, 10) my idea integers, convert them base number_of_elements , interpret number possibilities. works, except missing elements. (this output code above) : 0 1 2 # 00 missing # 01 missing # 02 missing 10 11 12 20 21 22 # 0.. elements missing 100 101 ... any idea or other simple method those? confer this question . following slight modification of answer there. class numeric def seq...

How can I break a long ruby hash into multi-lines? -

i have hash: arr={ [0,1]=>[0,0,1,1], [0,2]=>[0,1,0,1], [0,3]=>[0,1,1,0], [1,2]=>[1,0,0,1], [1,3] =>[1,0,1,0], [2,3] => [1,1,0,0] } and want split on 2 lines quite long, @ 121 characters. i'm not sticker line length guide line 80 , longer prefer so tried arr={ [0,1] => [0,0,1,1], [0,2] => [0,1,0,1], [0,3] => [0,1,1,0] } arr.merge({[1,2] => [1,0,0,1], [1,3] => [1,0,1,0], [2,3] => [1,1,0,0]}) but tests fail with errors like undefined method `[]' nil:nilclass how can better break up? 1 option line continuation \ didn't particularly neat. arr={ [0,1]=>[0,0,1,1], [0,2]=>[0,1,0,1], [0,3]=>[0,1,1,0], \ [1,2]=>[1,0,0,1], [1,3] =>[1,0,1,0], [2,3] => [1,1,0,0] } although guess do arr={ [0,1]=>[0,0,1,1], [0,2]=>[0,1,0,1], [0,3]=>[0,1,1,0], \ [1,2]=>[1,0,0,1], [1,3] =>[1,0,1,0], [2,3] => [1,1,0,0] } but looks w whitespace maintenance smell indentation. are there neater opti...

Python lists, modules, and loops (syntax error) -

currently learning python i'm little stumped particular question. i need print length of list using loop without use of built-in functions. i understand following works when input it: listlength = 0 list1 = ['a', 'b', 'c', 'd'] y in list1: listlength += 1 print(listlength) however question gives file cannot edit: import function_lists list1 = ['a', 'b', 'c', 'd'] print("length of list:", function_lists.listlength(list1)) in editable file named function_lists i've done this: def length(a_list) length = 0 y in list1: listlength += 1 syntax error: list1 not defined - can tell i'm misunderstanding how modules work, shouldn't list1 pulled out of un-editable file via import function_lists work? i'd ask prac tutor don't have until late week. you should using parameter name, a_list , instead of parameter passed, list1 . @andy g pointed out,...

vb.net - VB: Object variable or With block variable not set - why? -

i trying vb app write database if check box selected simple 1 indicate yes, rows in db set 0. seems line of code pointing , suggesting 'object variable or block variable not set' complete newbie thing... sqlcomm.parameters.addwithvalue("@cbselect", cbselect.checked) 'passing @chkbox parameter command here code behind. protected sub button3_click(byval sender object, byval e system.eventargs) handles button3.click each gvrow gridviewrow in gridview1.rows 'itterate tru rows dim chkbox checkbox = ctype(gvrow.findcontrol("cbselect"), checkbox) 'find checkbox inside gridview dim sqlcon new sqlconnection("data source=syd-pb0fw9m\blah;initial catalog=support_metrics;persist security info=true;user id=reportserver;password=xxxxxxxx") dim sqlcomm new sqlcommand("insert contacted values (@cbselect)", sqlcon) 'this insert example, can update can current gridview row id using gvrow.cells(0).te...

Perl XML::LibXML getting the Nth element -

here simplified sample xml <book_reviewers> <results> <reviewer> <name>anne</name> <profession>catfish wrangler</profession> </reviewer> <reviewer> <name>bob</name> <profession>beer taster</profession> </reviewer> <reviewer> <name>charlie</name> <profession>gardener</profession> </reviewer> <reviewer> <name>don</name> <profession>dogooder</profession> </reviewer> <reviewer> <name>ellie</name> <profession>elephant trainer</profession> </reviewer> <reviewer> <name>freddy</name> <profession>fencer</profession> </reviewer...

laravel 4 - dompdf Blank Page On Large Content -

i using dompdf print email summaries, these emails printed sequentially once have large email doesn't fit in remaining of page, new page created , content printed there. resulting first page partially or blank can't find solution that.

android - Getting my old version of Eclipse SDK Version: 3.6.2 up and running again? -

i have written number of simple apps android, have not posted on android market / google play year or two. wrote simple app when tried post google play error: you uploaded apk not zip aligned. need run zip align tool on apk , upload again. google must have changed while napping. after little research found needed load latest version of eclipse export/signing tool included in newer versions zip aligning. mistake think. first tried update function on eclipse sdk version: 3.6.2 had been using did not work. in frustration loaded latest version of sdk off android site. worked fine emulator comes far slow on computer (macbook pro os 10.6.8, 2.4 ghz intel core 2 duo, 2 gb 667 mhz ddr2 sdram). tried number of suggestions on getting faster emulator, none of worked. since emulator on 3.6.2 version of eclipse worked fine simple apps write said use version of eclipse , zip align app manually. unfortunately, apps on older version of eclipse have errors in them preventing them wo...

ios - UITableView Not Scrolling after contentInset -

i'm working on project have tableview , uitextfield. i'm applying following method when uitextfield gain/loose focus : -(void)enableinset { cgfloat offset = -30.0f; uiedgeinsets inset = uiedgeinsetsmake(placesmapview.frame.size.height - offset, 0.0f, 0.0f, 00.f); // updating tableview position. placestableview.contentinset = inset; placestableview.contentoffset = cgpointmake(0.0f, -(placesmapview.frame.size.height - offset)); placestableview.scrollindicatorinsets = inset; } and - (void)disableinset { cgfloat offset = self.navigationcontroller.navigationbar.frame.size.height + [uiapplication sharedapplication].statusbarframe.size.height; uiedgeinsets inset = uiedgeinsetsmake(offset, 0.0f, 0.0f, 00.f); placestableview.contentinset = inset; placestableview.contentoffset = cgpointmake(0.0f, -offset); placestableview.scrollindicatorinsets = inset; } the enableinset method called in viewdidlayoutsubviews. when call disableinset , enableinset, uitableview can not scro...