Posts

Showing posts from June, 2010

r - Efficient Way to Convert to Numeric -

i have converted bunch of columns factor numeric, code cumbersome. had individually convert each column, ended taking more time should. code used (only short sample - have many more columns): city1$ny <-as.numeric(levels(city1$ny))[city1$ny] city1$chi<-as.numeric(levels(city1$chi))[city1$chi] city1$la <-as.numeric(levels(city1$la))[city1$la] city1$atl<-as.numeric(levels(city1$atl))[city1$atl] city1$mia<-as.numeric(levels(city1$mia))[city1$mia] i positive instead of doing of that, could've done: city1[,citynames]<-as.numeric(levels(city1[,citynames]))[city1[,citynames]] where citynames of columns data convert.. doesn't work, get: error in as.numeric(levels(city1[, citynames]))[city1[, citynames]] : invalid subscript type 'list' can tell doing wrong? or there no easier way task other long, annoying first method? i positive instead of doing of that, could've done: city1[,citynames]<-as.numeric(levels(city1[,...

swift - Load UIView from xib without storyboard -

i'm trying load nib programmatically without using iboutlets in storyboard. i've set file owner's custom class , created outlets images , labels. i've created instance of uinib , called instantiatewithowner in custom class manually load nib. i'm trying load nib on uitableviewcontroller. my question how load xib on view controller without adding uiview view controller using storyboard , without connecting outlets uiview. there several questions , tutorials how load nib using storyboard , iboutlets, straightforward. can tell me how go programmatically, in swift? note: have 2 viewcontrollers in project. vc1 has collectionview image , label. i'm using xib , custom class display selected collectionview in vc2. you don't have have owner setup. can instantiate nib , reference top level objects created it. having said that, if pass self owner , have outlets connected, works well. it's worth noting if instantiate nib multiple times, ...

python - How to access var within function but outside subfunction -

i have following function, includes function inside it: def function(): previously_parsed_tv_urls = set() def _get_all_related(tv_urls): api_urls = [self._build_api_url_from_store_url(url) url in tv_urls not in previously_parsed_tv_urls] previously_parsed_tv_urls = tv_urls.union(api_urls) function() however, don't have access previously_parsed_tv_urls . how access within _get_all_related function? here error get: unboundlocalerror: local variable 'previously_parsed_tv_urls' referenced before assignment if want reference earlier defined name, in "higher" scope, python fine it. grants sorts of power, when you're messing around in interpreter. however , python pretty generous @ trying stop doing things can bite or cause nasty, difficult debug problems. unboundlocalerror comes in. as redefine name in particular scope, python marks local scope (only), , not higher provide value. keeps ac...

openrefine - Extra blank space between words -

please me 2 questions on how grel expression for: if there double spaces between 2 words in column, how can eliminate 1 space example: robert--smith robert-smith minus character equals blank illustration how can exact word in text filter. thanks! 1°) try transform---> value.replace(" "," ") or, common transforms ----> collapse consecutive white spaces 2°) column ---> text filters , enter word or, column---> facet---> customs facet , type : value.contains(" you_word ") or value.contains(/(yourexactword)/) return true or false facet h.

wpf - How could I reuse my code behind? -

i have 2 controls quite different layout, xaml structure quite similar (same kind of containers , same element names), their code behind identical . unfortunately, far, had repeat code event handlers on each of 2 classes. i in process of extracting common functionality satellite classes, using composition, still redundancy of constructors, field declarations, , initialization bothers me lot. so question boils down to: is there way avoid redundant code behind code when 2 usercontrols have layout differences, identical code-behind? wpf seperates concerns using controltemplate can changed. "code-behind" behavior. not need viewmodel that.

loops - simple q on 'while' method in Ruby -

i writing "while" loop method below: objective: find position of first letter that's vowel in give word "stackoverflow" vowels = ["a","e","i","o","u",] word = "stackoverflow" n = 0 while vowels.include? word[n] == false n += 1 end print n question: why n return 0? opposed 2 first "o" letter in "stackoverflow operator precedence in while loop evaluation. try (vowels.include? word[n]) == false evaluate check vowel , compare false. you face different issue if there no vowel in "word"

gethostbyaddr function is too slow (Perl socket programming) -

i'm trying run example in website tutorialspoint but it's slow. thought had buffering response changing print syswrite did nothing added debugging messages , found out function gethostbyaddr takes around 10 seconds resolve. i know there other modules socket programming wondering if problem common. i running on localhost , using mac of course can slow. contacts other machines lookup dns entry. (specifically, looking host address w.x.y.z looks ptr entry z.y.x.w.in-addr.arpa .) if authoritative dns server unresponsive, you're machine waiting response never come until machine has decided it's waited long enough. if find gethostbyaddr slow, don't use it. work ip address. it's not gethostbyaddr useful. 216.58.219.46 has names lax17s04-in-f14.1e100.net , lax17s04-in-f46.1e100.net , know better google.com . , there's 209.85.250.97 gethostbyaddr returns no names, no matter how many domain names resolve 209.85.250.97 .

android - Error: Cannot resolve method shutdownInput(),shutdownOutput(),close() -

here code: public void exit() { (iterator<socket> iterator = sockets.values().iterator();iterator.hasnext();) { socket socket = iterator.next(); try{ socket.shutdowninput(); socket.shutdownoutput(); socket.close(); }catch (exception e) { } } } i'm getting error: cannot resolve method shutdowninput(),shutdownoutput(),close() . what doing wrong? when call iterator.next() , it's going return object, not socket. have cast returned object socket. do: socket socket = (socket) iterator.next();

php - failed to open stream: Invalid argument with exclamation marks in URL -

https://www.google.co.uk/s?tbm=map&fp=1&gs_ri=maps&suggest=p&authuser=0&hl=en&pb=!2i14!4m12!1m3!1d36371.595804441626!2d-2.4949300500000002!3d53.74963355!2m3!1f0!2f0!3f0!3m2!1i1600!2i740!4f13.1!7i10!10b1!12m6!2m3!5m1!2b0!20e3!10b1!16b1!19m10!1e1!1e13!1e2!1e5!1e3!1e10!1e12!1e15!1e27!4smaps_sv.tactile!20m49!1e1!1e13!1e2!1e5!1e11!1e4!1e3!1e10!1e12!1e15!1e27!2m2!1i203!2i100!3m1!2i4!5smaps_sv.tactile!6m3!1m2!1i86!2i86!7m26!1m3!1e1!2b0!3e3!1m3!1e2!2b1!3e2!1m3!1e2!2b0!3e3!1m3!1e3!2b0!3e3!1m3!1e4!2b0!3e3!1m3!1e3!2b1!3e2!2b1!4b1!9b0!22m3!1sjf4ovtpahmj-ul_-hugd!3b1!7e81!23m1!4b1!26m9!1e12!1e15!1e13!1e3!1e27!2m2!1i80!2i80!4smaps_sv.tactile!37m1!1e81&q=downing%20street&pf=p&tch=1&ech=14&psi=jf4ovtpahmj-ul_-hugd.1443823133674.1 when trying read .txt file shows on url above fopen returns failed open stream: invalid argument. i have tried urlencode gives same error <?php $url = "https://www.google.co.uk/s?tbm=map&fp=1&gs_ri=maps...

c - Strings overlap when fwrite is called from function -

my assignment display kernel information , have output log file. program long because contains alot of parts display necessary ones. main method calling part1()-part10() functions. output is: 1. cpu tintel(r) when expected: 1. cpu type & model: intel(r) core(tm) i5-4210u cpu @ 1.70ghz part1(): int part1() { char filename[] = "/proc/cpuinfo"; file *fp = fopen(filename, "r"); int n = 5; // line on information contained. int i; char line[256]; if(fp != null) { for(i=0; i<=n-1; i++) { fgets(line, sizeof(line), fp); } fclose(fp); printf("1. cpu type & model:\t %s", line+13); output("1. cpu type & model:\t", line+13); return 0; } else return 1; } output(): int output(char *x, char *y) { file *fp; fp = fopen("local_kernel.log ", "a"); fwrite(x , 1 , sizeof(x) , fp ); fwrite...

regex - how to replace everything except string of interest -

file.txt fruits:banana,apple,grape,limon,orange,tomate, fruits:apple,limon, fruits:banana,grape,limon, fruits:orange,tomate,grape, fruits:banana, fruits:apple, fruits:banana,apple, i need replace different "banana" fruit, , output this: fruits:banana,fruit,fruit,fruit,fruit,fruit, fruits:fruit,fruit, fruits:banana,fruit,fruit, fruits:fruit,fruit,fruit, fruits:banana, fruits:fruit, fruits:fruit,apple, i tried using awk, can replace fields of specific strings. example replace strings "apple" fruit2, or strings "apple" fruit2 , strings "tomate"or "orange" fruit3 awk -f":" '{ gsub(/apple/,"fruit2",$2); print }' ofs="," file.tx or awk -f":" '{ gsub(/apple/,"fruit2",$2);;gsub(/tomate|orange/,"fruit3",$2); print }' ofs="," file.txt |sed "s/./:/7" fruits:banana,fruit2,grape,limon,fruit3,fruit3, fruits:fruit2,limon, fruits:banana,...

Does Haskell's `Data.Vector.Mutable.unsafeNew` zero the memory? -

the docs says new "creates mutable vector of given length" , unsafenew "creates mutable vector of given length. length not checked." however this resolved github issue indicates unsafenew not 0 memory while new does. which 1 it? no, not in general. if click through source pretty clear: https://hackage.haskell.org/package/vector-0.11.0.0/docs/src/data-vector-generic-mutable.html#new new unsafenew addition of basicinitialize .

jquery - Is there an equivalent to jTable component for Bootstrap? -

i looking similar jtable component written jquery , bootstrap. link jtable website: http://www.jtable.org http://datatables.net/ has it's own implementation of bootstrap http://datatables.net/manual/styling/bootstrap jtable & bootstrap read more @ https://github.com/hikalkan/jtable/pull/956

c# - Using where all on linq -

i trying implement search function application, want happen send list if there no keyword specified , have where clause. here action: public actionresult classes(string keyword ="") { employeecontext emp = new employeecontext(); list<classlist> asd = (from subj in emp.subjects join prof in emp.professors on subj.id equals prof.id join dep in emp.departments on prof.id equals dep.id subj.subj == keyword select new classlist() { id = subj.id, subj = subj.subj, days = subj.days, cstart = subj.cstart, cend = subj.cend, units = subj.units, fname = prof.fnam...

javascript - Call function again only after it finish executing -

i have function gets called every time enter key pressed. need make function not called if press enter key again, if , when function has not finish executing yet. when function has finished executing, called again if press enter key again. how in jquery, or javascript? onkeydown = 'if(event.keycode==13) somefunction()' function somefunction() { //some codes //some settimeouts } simply set boolean when done , check before executing function. onkeydown = 'if(event.keycode==13) { if (!finished){somefunction();}' var finished = false; function somefunction() { finished = false //some codes //some settimeouts finished = true; } though, luis points out, javascript single threaded , shouldn't running problems describe unless not understanding problem fully.

In R XML Xpath, @href is returning the text "href" -

i trying contents of href using xpath code described in these two posts . unfortunately code returning actual text "href" , several spaces in addition url. how can avoid that? library(xml) html <- readlines("http://www.msu.edu") html.parse <- htmlparse(html) node <- getnodeset(html.parse, "//div[@id='msu-top-utilities']//a/@href") node[[1]] # > node[[1]] # href # "students/index.html" # attr(,"class") # [1] "xmlattributevalue" it's named character vector. can do: as.character(node[[1]]) which give ## [1] "students/index.html" alternately, here's better idiom in xml2 package: library(xml2) doc <- read_html("http://www.msu.edu") nodes <- xml_find_all(doc, "//div[@id='msu-top-utilities']//a") xml_attr(nodes, "href") ## [1] "students/index.html" "faculty-staff/index.html" ...

javascript - Why am I not getting image width and height after loading? -

i image element. let user upload image. after upload, process image. want load processed image , show it. getting , show image fine. i need know width , height of image loaded. i doing correctly below , should work not sure why width , height zero: html: <img id="photo" src=""> js: var id = 1000; var img = $("#photo").attr('src', '/photo/get/' + id) .on('load', function () { var w = 0; var h = 0; if (!this.complete || typeof this.naturalwidth === "undefined" || this.naturalwidth === 0) { alert("could not load image"); } else { alert('image loaded'); w = $(this).width(); h = $(this).height(); alert("width=" + w + " height=" + h);//prints 0, 0, why??? } }); jqueryobject.width() return computedstyle of targeted el...

python - Best prime numbers to choose for a double hashed hash table size? -

what best prime numbers choose double hashed hash table size ? side info the hash table part of word analysis project, markov models, training bots model , generate text if else write (which takes lot of words, sentences, transcripts, books... bigger corpus , better) i'm not familiar of math around prime numbers read on guys propose , try go there what have in mind: the prime numbers shouldn't far/close each other ----> don't have increase size frequently, hash table doesn't end half empty (less collisions, looking ideal ratio between load factor , hash table size) optimal big corpus - i'm not sure how big prime numbers have choose should be, never did before... i thought of implementing function (not hash function) that'd double size of hash table , closest prime number ------> has running time of o(n) because prime divisible ____( have check whether numbers number that's double size of current hash table size have remainder other z...

c# - Cascading Dropdown in Javascript and can't get them in CodeBehind -

i have code in javascript cascading dropdown problem can't access data in codebehind in c# web. this code in javascript : function collegedepartment() { var s1 = document.getelementbyid("college"); var s2 = document.getelementbyid("department"); s2.innerhtml = ""; if (s1.value == "college of engineering") { var optionarray = ["civil engineering", "computer engineering", "electrical engineering", "electronics , communication engineering", "industrial engineering", "mechanical engineering"]; } else if (s1.value == "cas") { var optionarray = ["political science", "mascomm", "liacomm"]; } else if (s1.value == "commerce") { var optionarray = ["business ad", "hotel management", "tourism"]; } else if (s1.value == "education") { var opt...

javascript - How to refresh a table inside a div tag using ajax php -

i have ajax table click event gets database data according clicked name first table , display second table employee information. problem employee information data pile in second table, want refresh second table every name user clicked. way second table inside div tag. here ajax code: function putthis(control){ var getid = control.innertext; var first = $("#from[name=from]").val(); var second = $("#to[name=to]").val(); $.ajax({ type:'post', url: 'testtable.php', data: {id: getid,from: first,to: second}, cache: false, global: false, success:function(data) { $("#result").append(data); alert("success: " + getid + " " + first + " " + second); } }); } if reading question (and correct me if not), want replace contents of element rather append data element. this can accomplished code changing line : $("#result").append(data); to : $("#result...

python - How to set path for PyGithub method? -

i'm working pygithub basic access own github repo. methods require "path" , i'm not sure is. parameters use in .get_contents() function? simple example: github import github g = github("***","***") repo = g.get_user().get_repo("my_projects") contents = repo.get_contents() you need pass following arguments: path - string - content path. ref - string - name of commit/branch/tag. default: repository’s default branch (usually master) e.g - repo.get_contents('config/version.rb','development') see more here

javascript - Example of Navigation between views in React Native Android? -

after check react native documentation, still don't understand best way create views , navigate between different components. i don't want use external components like: https://github.com/kureev/react-native-navbar/ https://github.com/23c/react-native-transparent-bar https://github.com/superdami/react-native-custom-navigation i don't need navigation bar, want set views , slide left, right o pop view, nothing more. i know basic, can't find helpful example. please, can me? functional example in https://rnplay.org/ ? thank you. watch example: https://github.com/h87kg/navigatordemo it's useful , written navigator example, better 1 above wrote, think. mainly watch relationship between loginpage.js , mainpage.js

ios - Debug navigator memory in Xcode grows -

i have developed application iphone, , check memory leak. i switch 2 viewcontrollers (two screens), vc1 , vc2 follow: click button in vc1 start vc2, using [ self presentviewcontroller:vc2 animated:yes completion:nil] ; click button in vc2 close vc2 , go vc1, using [ self dismissviewcontrolleranimated:yes completion:nil ]; i repeats step 1 , 2 ten times. in xcode , debug navigate memory, memory grows each time screen @ vc1, memory: 6mb screen @ vc2, memory: 6.6mb screen @ vc1, memory: 6.3mb screen @ vc2, memory: 6.8mb screen @ vc1, memory: 6.5mb screen @ vc2, memory: 7mb screen @ vc1, memory: 6.6mb screen @ vc2, memory: 7mb screen @ vc1, memory: 6.6mb screen @ vc2, memory: 7.2mb ... screen @ vc1, memory: 7mb vc1 starts memory 6mb, @ end, uses 7mb, after 10 time switching of vc1 , vc2. i verify code , run xcode instrument find memory leak, instrument shows no leak. what cause memory grow 6mb 7mb? my application has memory leak? or normal ...

android - Start RecognitionListener following vocal command -

i'm trying build app sparks action following pre-defined voice command me, "ok google". want device launch voice recognition intent give "ok google" type of message. know how launch such intent: if (isconnected()) { intent intent = new intent(recognizerintent.action_recognize_speech); intent.putextra(recognizerintent.extra_language_model, recognizerintent.language_model_free_form); intent.putextra(recognizerintent.extra_max_results, 4); intent.putextra(recognizerintent.extra_language, "en-us"); startactivityforresult(intent, request_code); } else { toast.maketext(getapplicationcontext(), "plese connect internet", toast.length_long).show(); } however, right now, i'm able start intent following tap on button. want able launch without interacting ui. may possible launch intent after intent in expectation of vocal command, it's not desired app...

javascript - Need to know a function that loads on the DIV only and Not Body Onload -

could please me here. need code load on div , not on body onload. how can this? <div id="typingtext"><h1>new ways move people</h1></div> <script type="text/javascript"> var text = "new ways move people !"; var chararray = text.split(""); var timer; function loop() { if (chararray.length > 0) { document.getelementbyid("typingtext").innerhtml += chararray.shift(); } else { cleartimeout(timer); return false; } timer = settimeout('loop()', 70); } </script>

java - Getting a null value on my arraylist.set(). using jsp -

my objective add words html form, store them in array, display them in page, , have 2 links 1 delete item , 1 edit item(the word edit entered in html form). i using arraylist store input coming input type. able add , delete item, when tried change value of item in arraylist (i using arraylist.set()), value returns null. if hard code set() see item change reason can't value input type. wondering missing. i have 2 jsp pages. main.jsp , edit.jsp. 1 java class wordoperations validations here code sorry if messy , if doesn't display right in here. first time posting on stackoverflow any appreciated. thanks this code form display items main.jsp <h3>word list</h3> <form action="wordoperations" method="post"> word: <input type="text" name="newword"> <input type="submit" value="add"> </form> <br/> <% ...

android - Fragment is not removed from BackStack -

i use backstack store fragments , works fine. when want remove fragment backstack, nothing happens. checked questions this , saw remove item backstack using popbackstack, me, not work me. this code: fragmentmanager fragmentmanager = getsupportfragmentmanager(); fragmenttransaction fragmenttransaction = fragmentmanager.begintransaction(); int count = getsupportfragmentmanager().getbackstackentrycount(); string currenttag = getsupportfragmentmanager().getbackstackentryat(getsupportfragmentmanager().getbackstackentrycount() - 1).getname(); fragment currentinstance = getsupportfragmentmanager().findfragmentbytag(currenttag); fragmenttransaction.remove(currentinstance); fragmenttransaction.commit(); fragmentmanager.popbackstack(getsupportfragmentmanager().getbackstackentrycount() - 1, fragmentmanager.pop_back_stack_inclusive); int count1 = getsupportfragmentmanager().getbackstackentrycount(); currentinstance shows topmost fragment correctly. ...

arrays - bash- find average of numbers in line -

i trying read file line line , find average of numbers in each line. getting error: expr: non-numeric argument i have narrowed problem down sum= expr $sum + $i , i'm not sure why code doesn't work. while read -a rows in "${rows[@]}" sum=`expr $sum + $i` total=`expr $total + 1` done average=`expr $sum / $total` done < $filename the file looks (the numbers separated tabs): 1 1 1 1 1 9 3 4 5 5 6 7 8 9 7 3 6 8 9 1 3 4 2 1 4 6 4 4 7 7 with minor corrections, code runs well: while read -a rows total=0 sum=0 in "${rows[@]}" sum=`expr $sum + $i` total=`expr $total + 1` done average=`expr $sum / $total` echo $average done <filename with sample input file, output produced is: 1 5 7 5 2 5 note answers because expr in...

java - Android how to add back button in activity to return back in fragment activity -

hello have simple activity , fragment want add add button on activity action bar , return fragment.here code public class fragment2jazz extends fragment { button msgbutton; button callbutton; button internetbutton; public fragment2jazz(){} @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { view rootview = inflater.inflate(r.layout.jazz_fragment, container, false); msgbutton = (button) rootview.findviewbyid(r.id.btnjazz1); callbutton= (button) rootview.findviewbyid(r.id.btnjazz2); internetbutton= (button) rootview.findviewbyid(r.id.btnjazz3); msgbutton.setonclicklistener(new view.onclicklistener() { @override public void onclick(view view) { intent intent = new intent(getactivity() , jazzmessage.class ); getactivity().startactivity(intent); } }); callbutton...

javascript - Access radtreeview on client side with dataset -

this event on radtreeview node click can write event on client side javascript because take time load when post . using dataset here filled when page load first time . there anyway access dataset in client side or anyway make method more faster or can make method in client side can execute faster . protected void radtreeview1_nodeclick(object sender, radtreenodeeventargs e) { ds = (dataset)session["dsgrr"]; foreach (griddataitem item in radgridview2.items) { item["sn#"].text = null; item["type"].text = null; item["accounttitle"].text = null; item["description"].text = null; item["costcenter"].text = null; item["debit"].text = null; item["credit"].text = null; } if (e.node != null && e.node.value != null) { datarow[] dr = ds.tables["jv"]....

android - My bitmap image is cropped -

Image
i'm using method: public bitmap decodeuri(uri selectedimage) throws filenotfoundexception { bitmapfactory.options o = new bitmapfactory.options(); o.injustdecodebounds = true; bitmapfactory.decodestream(getcontentresolver().openinputstream(selectedimage), null, o); final int required_size = 800; int width_tmp = o.outwidth, height_tmp = o.outheight; int scale = 1; while (true) { if (width_tmp / 2 < required_size || height_tmp / 2 < required_size) { break; } width_tmp /= 2; height_tmp /= 2; scale *= 2; } bitmapfactory.options o2 = new bitmapfactory.options(); o2.insamplesize = scale; return bitmapfactory.decodestream(getcontentresolver().openinputstream(selectedimage), null, o2); } to decode uri mi camera , send webserver via httpurlconnection object in post headers. instead original image: i cropped imagen: i don't know why. perhaps decodeuri method wrong? kn...

javax.mail - The code is giving Multiple Marker at this line -

this line giving errors not able find clue kindly me..?? have added related jar files giving error please check code , help properties properties = system.getproperties(); properties.setproperty("mail.smtp.host", host);

sql - Foreign key on two columns -

Image
for school project needed create database. erd. in sql create category table: create table "category" ( "id" number(5) not null, "subcategoryid" number(5) null, "name" varchar2(32) not null, constraint "category_pk" primary key ("id") ); alter table "category" add constraint "category_fk" foreign key ("subcategoryid") references "category" ("id"); product table create table "product" ( "id" number(5) not null, "categoryid" number(5) not null, /* category.id or category.subcategoryid */ "name" varchar2(32) not null, "brand" varchar2(32), "type" varchar2(32), "year" number(4), constraint "product_pk" primary key ("id") ); the product table has categoryid (foreign key) on category.id, product.categoryid needs foreign key on category.subcategoryid. is p...

spring - How to change parameter name in datatable.net such as : "draw", "recordsTotal" , "recordsFiltered" -

i use pagingandsortingrepository of spring framework app. when page interface in server response client parameter: totalpages , totalelements , numberofelements , size . client datatable jquery (datatable.net) needs draw , recordstotal , recordsfiltered parameters. please me resolve problem. use ajax.datasrc callback preprocessing response : $('#example').datatable( { serverside: true, ajax: { url: "path/to/server", datasrc: function(json) { json['recordstotal'] = json['totalelements']; json['recordsfiltered'] = json['numberofelements']; return json; } } });

algorithm - How many triangles can be made? -

i have sorted sequence of positive integers. how many triangles can made using these numbers lengths of sides (triangles can not degenerate)? have no idea other checking possibilities. i have no idea other checking possibilities. of course check possibilities - after all, required count how many possibilities have. it's matter of how check them. going through sets of thee o(n 3 ), slow. you can in o(n 2 *log 2 n) observing once you've picked 2 sides a , b , can find max length of third 1 binary-searching sorted list position of a+b .

Should I move my PHP site into a CMS like Wordpress? -

i have coded site proud of in php. working fine. told site needs built around cakephp. i new building dynamic websites not sure if he's correct or not. right now, if want see data, go phpmyadmin. if want operate on code, open php files. is there better way don't know about? not sure why should re-code site in cakephp. should i? please explain. also, cakephp come design templates wordpress? there's more 1 way skin cat. there nothing wrong in sticking plain php if comfortable maintaining contents in phpmyadmin. can make site dynamic using parameters (example.com/article?id=123) or using routing framework allow nice url's such (example.com/article/hello-world.html). personally, prefer sticking plain php personal website projects, instead of becoming dependent on framework or cms. no matter if choose stick plain php, framework or cms, still need figure ways to: route user request ever resources page should show user. security ("never trust ...

apache - URL rewrite (routing), mod_rewrite, or PHP -

was trying sort out myself no luck. i have website (php, apache), following structure, sample: 1. http://hostname/ 2. http://hostname/category?list=listname 3. http://hostname/product?id=...&name=productname 4. http://hostname/recipes 5. http://hostname/recipe?id=...&name=recipename + many others. current .htaccess is: rewriteengine on rewritecond %{request_filename} !-d rewritecond %{request_filename}\.php -f rewriterule ^(.*)$ $1.php so examples http://hostname/category?list= ... becomes /category.php?list... , catches php script , works. i want make friendly urls these: 1. http://hostname/ 2. http://hostname/category/listname/ 3. http://hostname/product/productname/ 4. http://hostname/recipes/ 5. http://hostname/recipe/recipename/ and on other hand previous urls must still work webiste hugely indexed search enginges. oldstyle urls must 301 redirect new urls. ideas? efforts had errors. tried make php routing via index.php entry point, cant how d...

ruby on rails 4 - ActiveRecord Query to identify orphan child records -

i have post , user models. every post belongs user. however, during database import, erroneous user_ids have been entered on posts. query posts user_ids don't refer user? thanks. i following, result in 1 select , 1 delete statement post.where('`posts`.`user_id` not in (?)', user.pluck(:id)).delete_all

android - Facebook setInitialize is deprecated but removing it causes inflating error -

as suggested here: the facebook sdk auto initialized on application start. if using facebook sdk in main process , don't need callback on sdk initialization completion can remove calls facebooksdk.sdkinitialize. if need callback, should manually invoke callback in code. facebook.setinitalizer(context) deprecated. problem when remove line: facebook.setinitalizer(context) suggested inflating error on: com.facebook.login.widget.loginbutton : <com.facebook.login.widget.loginbutton android:id="@+id/signin_activity_login_button_fb" android:layout_width="240dp" android:layout_height="wrap_content" ... /> error: android.view.inflateexception: binary xml file line #22: binary xml file line #22: error inflating class com.facebook.login.widget.loginbutton when return initalizer error gone. should do. also gradle: compile 'com.facebook.android:facebook-android-sdk:[4,5)'

pointers - C Programming - Sum of 2D arrays -

Image
i trying values of diagonal values 2d array. example.. 10 20 30 10 20 30 10 20 30 from codes, adding/summing numbers index[0][0] index 1 , index[2][2] using pointers compute 60. however, when build , run, returns computation of memory address instead. can explain problem here? (i'm new c programming , pointers) void diagonals2d(int array[][size], int rowsize, int colsize, int *sum) { int count; *sum=0; for(count=0;count<size;count++) { (*sum)+=*(array+count+count); } } the first parameter adjusted to int ( *array )[size] that is pointer. so expression array + count has type int ( * )[size] . corresponding "row" of array have dereference pointer *( array + count ) in case have object of type int[size] in turn in expression *( array + count ) + count is implicitly convered type int *. now dereferencing whole expression target element *( *( array + count ) + count ) it better declare function havin...

How to pass a variable from one function to an Sqlite3 query in another function in Python/Kivy -

i building app using python 2.7, kivy , sqlite3. having trouble passing variable value text_input widget(date picker kivy garden) value in function choose_date_water , passing function view_water_figures can used in querying sqlite table. have been trying days figure out without luck , hoping little help. how pass variable first function second? am querying sqlite table correctly using variable dp1 ? the relevant code: class logsheet(tabbedpanel): def choose_date_water(self): box = floatlayout() box.add_widget(label(text = "select date view", font_size = (30), pos_hint = {'center_x':0.5, 'center_y': 0.9 })) #box.add_widget(textinput(hint_text = "dd/mm/yyyy", font_size = (33), size_hint = (none, none), size = (300, 50), pos_hint = {'center_x':0.5, 'center_y': 0.6 })) dp1 = box.add_widget(datepicker(phint_x = (0.35), phint_y = (0.55), size_hint = (none, none), size = (190, 50), fon...

Apache Airflow Multi Tenant -

i'm attempting work out how airflow might work in multi-tenant environment. requirements should this: two teams, teama , teamb, using single airflow instance. team's , b each have own service user account: serviceusera , serviceuserb should run jobs under. for security reasons, team should not able create jobs run under serviceuserb , vice versa. at point it's not clear me whether requirement 3) can met airflow, short of giving each team separate airflow instance. there way in can achieved? thanks, chris

sql server - Which is faster in SQL, While loop, Recursive Stored proc, or Cursor? -

which faster in sql, while loop, recursive stored proc, or cursor? want optimize performance in couple of spots in stored procedure. code i'm optimizing formats strings output file. i'll assume using sql server. first of all, said in statements, recursive stored procs, while possible, not idea in sql server because of stack size. so, recursive logic break. however, if have 2-3 levels of nesting @ best, might try using recursion or using cte , bit recursive (sql server 2005 , up). once manage wrap head around cte, it's immensely useful technique. haven't measured, i've never had performance issues in few places used cte. cursors on other hand big performance hogs, ( and half internet ) recommend not use them in code called often. cursors more classical programming structure, akin foreach in c#, people find easier at, understand , maintain sql code uses cursors data manipulation, on convoluted multiple-inner-select sql monstrosity, it's not wors...

php - Display value of specific element from multi dimensional array -

please help, how can display posts site_id 1 below multidimensional array , display comma separated 4295, 4289, 4298, 4292 print_r($favorites); array ( [0] => array ( [site_id] => 1 [posts] => array ( [0] => 4295 [1] => 4289 [2] => 4298 [3] => 4292 ) [groups] => array ( [0] => array ( [group_id] => 1 [site_id] => 1 [group_name] => default list [posts] => array ( [0] => 4295 [1] => 4289 [2] => 4298 [3] => 4292 ...

Measuring string width in Python -

i have font (times new roman, 14) , need measure string width. found matplotlib , example api: from matplotlib import rcparams import os.path afm_filename = os.path.join(rcparams['datapath'], 'fonts', 'afm', 'ptmr8a.afm') matplotlib.afm import afm afm = afm(open(afm_filename)) afm.string_width_height('what heck?') but can't understand should paste instead of "datapaths", "fonts", "afm". way sting width in python? maybe way? import tkinter tkinter tkinter import font tkfont tkinter.frame().destroy() txt = tkfont.font(family="times new roman", size=14) width = txt.measure("what heck?") print(width)

excel - nested ifs with multiple sumifs based on changing criteria -

i having trouble formula , know if building in correct order or how can change desired result. getting formula missing opening or closing parenthesis error: =if(bh2="ppd fsc",sumifs('all bids'!r:r,'all bids'!d:d,bv2,'all bids'!e:e,i2,'all bids'!w:w,'dc tool'!u2,'all bids'!g:g,'dc tool'!v2,'all bids'!h:h,'dc tool'!m2),sumifs(freight!z:z,freight!q:q,'dc tool'!f2,freight!m:m,h2,freight!o:o,"ppd",freight!aa:aa,grids!$u$3),if(bh2="ppd gdc",sumifs('all bids'!r:r,'all bids'!d:d,f2,'all bids'!e:e,i2,'all bids'!w:w,'dc tool'!u2,'all bids'!g:g,'dc tool'!v2,'all bids'!h:h,'dc tool'!m2),sumifs(freight!z:z,freight!q:q,'dc tool'!f2,freight!m:m,h2,freight!o:o,"ppd",freight!aa:aa,grids!$u$3)) looks want 3 different possible sumifs, logic being follows: if bh2 = "x" sumifs1 , if...

c - Why is unprivileged recursive unshare(CLONE_NEWUSER) not permitted? -

i'm on ubuntu 17.04. single unprivilleged unshare of mount namespace works. can try using unshare(1) command: $ unshare -m -u /bin/sh # however unshare within unshare not permitted: $ unshare -m -u /bin/sh # unshare -m -u /bin/sh unshare: operation not permitted # here c program same: #define _gnu_source #include <stdio.h> #include <sched.h> #include <sys/mount.h> #include <unistd.h> int main(int argc, char *argv[]) { if(unshare(clone_newuser|clone_newns) == -1) { perror("unshare"); return -1; } if(unshare(clone_newuser|clone_newns) == -1) { perror("unshare2"); return -1; } return 0; } why it's not permitted? can find documentation this? failed find information in unshare or clone man page , in kernel unshare documentation. is there system setting allow this? what want achieve: first unshare: want mask few binaries on system own versions. second unshare: un...

android - Mediaplayer.prepare() crash with IllegalStateException, only for Xiaomi Note 3 & Xiaomi Mi4 -

for alarm app, error coming xiaomi note 3 & xiaomi mi4 devices & working fine other devices including personsal xiaomi redmi 3s. exception java.lang.runtimeexception: unable start activity java.lang.illegalstateexception : caused java.lang.illegalstateexception: android.media.mediaplayer._prepare (mediaplayer.java) android.media.mediaplayer.prepare (mediaplayer.java:1408) android.app.activity.performcreate (activity.java:6912) android.app.instrumentation.callactivityoncreate (instrumentation.java:1126) android.app.activitythread.performlaunchactivity (activitythread.java:2877) android.app.activitythread.handlelaunchactivity (activitythread.java:2985) android.app.activitythread.-wrap14 (activitythread.java) android.app.activitythread$h.handlemessage (activitythread.java:1635) android.os.handler.dispatchmessage (handler.java:102) android.os.looper.loop (looper.java:154) android.app.activitythread.main (activitythread.java:6692) java.lang.reflect.method.invoke (method.j...

java - How to add parameters in rest api for specific response in code? -

i have created first basic rest api. working find , give me output in xml using url http://localhost:8080/webservice/test/restclient now, i'm thinking if want api ask server specific data how can use parameters same in api url. here little updated code package restclient; //import javax.servlet.annotation.webservlet; import javax.ws.rs.get; import javax.ws.rs.path; import javax.ws.rs.pathparam; import javax.ws.rs.produces; import javax.ws.rs.core.mediatype; import javax.xml.bind.annotation.xmlrootelement; @path("/restclient") @xmlrootelement public class restwebclient { @get @produces(mediatype.text_xml) public string sayxmlhello(@pathparam("x") int x, @pathparam("y") int y) { string output = ""; if (x == 1 && y == 1) { output = "<?xml version=\"1.0\"?>" + "<hello> hello jersey" + "</hello>"; } else if (x...

android studio preview layout is different from prototype in xd -

Image
i make prototype apps adobe xd. problem when import assets android studio, screen ldpi, mdpi, hdpi, xhdpi xxhdpi , xxxhdpi has different. xd : android studio :

php - Use Doctrine ArrayCollection in symfony custom command -

i use arraycollection in custom symfony command. but way throwing error the class 'doctrine\common\collections\arraycollection' not found in chain configured namespaces appbundle\entity my command <?php namespace appbundle\command; use symfony\bundle\frameworkbundle\command\containerawarecommand; use symfony\component\console\input\inputargument; use symfony\component\console\input\inputinterface; use symfony\component\console\input\inputoption; use symfony\component\console\output\outputinterface; use doctrine\common\collections\arraycollection; use appbundle\entity\gameworld; class mycommand extends containerawarecommand { protected function configure() { $this ->setname('get:gw') ->setdescription('populate gameworld') ; } protected function execute(inputinterface $input, outputinterface $output) { $em = $this->getcontainer()->get('doctrine')->get...

bash - How can I iterate over .log files, process them through awk, and replace with output files with different extensions? -

let's have multiple .log files on prod unix machine(sunos) in directory: example: ls -tlr total 0 -rw-r--r-- 1 21922 21922 0 sep 10 13:15 file2017-01.log -rw-r--r-- 1 21922 21922 0 sep 10 13:15 file2016-02.log ...

java - How to properly use standalone TransactionManager in web application? -

i'd write next tiny java webapp using 1 of micro-frameworks. e.g. spark or jooby . problem both of them doesn't support jta, need use 1 of third-party libraries. i've googled open-source jta implementations , found two: atomikos , bitronix . seems latter project abandoned i've decided go atomikos. unfortunately documentation scarce can't find answers questions. here use case. suppose have 2 dao classes methods should executed under single transaction: class someservice { // both injected guice private foodao foodao; private bardao bardao; public void somemethod() { // both methods should executed in single transaction foodao.insert(new foo()); bardao.insert(new bar()); } } i've never used javax.transaction api directly/manually before (you know declarative transactions simple spring) i'm bit confused. jta provides 2 general abstractions( usertransaction , transactionmanager ) , both have methods han...