Posts

Showing posts from June, 2014

objective c - CLLocationManager Overheating iPhone -

i'm making app augmented reality. have screen image camera, radar view , markers on screen. i'm using cllocationmanager updates on heading , location. need heading updates turned on, because radar rotation depends on it. i'm using location updates position , based on i'm looking markers show. problem when i've got both turned on iphone overheating little on time (10 +- minutes). i've got accuracy set every 100 metres , distance filter 100. should set timer stop , start updating of location prevent overheating (and save battery life too)? there other approach this? advices. this time user "time profiler" instrument. i'm sure using gps responsible of heat have other part of code using cpu or gpu heavily. there's opengl performance tool, @ see if can find parts taxing gpu much. another possibility using avfoundation camera image, , see if can specify less expensive preview parameters video image overlaying.

jquery - How would you achieve this 3d hover effect? -

i'm trying 3d mouseover effect when you're on div. here's it's now http://jsfiddle.net/6tnbu/ i know how make in sort lower-left , top-right corner have cleaner shadow, oblique style. thought maybe load triangle on corners know if there's other way achieve that. thanks if don't mind using pseudo-elements, there's ::before , ::after (although note that, recall, ie doesn't recognise double-colon declaration, you'd have use :before , :after ): #box::before { content: ' '; position: absolute; top: -10px; left: -10px; bottom: 0; height: 100%; background-color: #f90; border-bottom: 10px solid white; border-right: 10px solid black; } #box::after { content: ' '; position: absolute; top: -10px; left: -10px; right: 0; width: 100%; border-bottom: 10px solid black; border-right: 10px solid white; } js fiddle demo .

Proxy Basic Authentication in C#: HTTP 407 error -

i working proxy requires authentication, i.e., in browser if try open page ask credentials. supplied same credentials in program fails http 407 error. here code: httpwebrequest request = (httpwebrequest)webrequest.create(url); iwebproxy proxy = webrequest.getsystemwebproxy(); credentialcache cc = new credentialcache(); networkcredential nc = new networkcredential(); nc.username = "username"; nc.password = "password"; nc.domain = "mydomain"; cc.add("http://20.154.23.100", 8888, "basic", nc); proxy.credentials = cc; //proxy.credentials = system.net.credentialcache.defaultcredentials; request.proxy = proxy; request.proxy.credentials = cc; request.credentials = cc; request.preauthenticate = true; i have tried every possible thing seem missing something. like, have make 2 requests? first out credentials , once hear server need credentials, make same request credentials? this method may avoid need hard code or configure p

OpenCV, ffmpeg and eclipse on linux -

i'm writing program using ffmpeg , opencv. installing ffmpeg have ran sudo apt-get install ffmpeg, , opencv make & sudo make install. have made project , need tell eclipse headers , lib files are. they? thanks, nahum i don't run debian, these paths may not right you, packages using binary packages (via apt-get, rather apt-src) install libraries in /usr/lib , include headers in /usr/include . on system include directory ffmpeg /usr/include/libavformat , include directory opencv /usr/include/opencv , /usr/include/opencv2 . both libraries in default location of /usr/lib . if know name of library, can use find , locate commands location. e.g find / -iname name* .

operators - || in javascript -

can please tell me || doing here (function() { window.myapp = window.myapp || {}; window.myapp.lang = window.myapp.lang || {}; myapp.lang.extend = function(subclass, superclass) { subclass.prototype = new superclass(); }; })(); window.myapp = window.myapp || {}; it means: create window.myapp empty object if not exist.

objective c - dynamically resizing view height -

i've seen many questions regarding topic, yet cannot find 1 satisfactory answer. i've created sample view using interface builder, attached below: layout sample now text content dynamic, , when have list of such views 1 underneath other, strange state in views overlap each other. looking simple way view resize itself, or @ least expend size of subviews. all explanations find have single label, in manual calculations of size. there no simple mechanism provided coca toch this? thank you you have subclass superview containing other items. override -layoutsubviews method , in method calculate sizes , reposition subviews.

lightopenid - OpenID, Google, and pass-through variables? -

i new openid, , using lightopenid provide authentication against google accounts. possible perform authentication doesn't involve header redirection or can pass through , post variables exist within original http request? any variables in original http request lost when header redirection takes place. thanks! you can set parameters in $openid->return_to . for example, if do: $openid->return_to .= '?a=5&b=23' you $_get['a'] == 5 , , $_get['b'] == 23 in request after authentication. there no way set post parameters way, or avoid redirections.

android - Elegant way to store numerical data such as game moves -

i storing game data such sequence of moves in multi-dimensional array, defined as: private final int[][] gamemoves = {{1},{2},{0},{3},{1,4},{1,4,5},{2,4}} the array of course bigger. i feel there should more elegant way this, possibly storing data separately code using either xml file or sqlite database , retrieving in while-loop. if using xml file, format , method of retrieval? if using sqlite database, way data inside database before executing source code? any examples appreciated. if data never gets changed, there isn't reason persist it, if gets read frequently, since you'll taking performance hit in reading thereof. if anything, perhaps separate package containing game data objects each providing 'gamemoves', might winner. or, if you're tied separation conceptual and/or requirement standpoint, json might way go, it's more directly tied multidimensional arrays xml file might be, , easier work db. for example, json file might be

c++ - determining if templated type is dynamic -

i writing template of working class, , might dumb question, if have template structure (linked list) hold possibly pointers objects how know being deleted, or pointers in first place? for example: linkedlist used in 2 ways in program a pointer object of class thing placed inside node inside linkedlist an enum placed inside node inside linkedlist i know nodes being deleted, how know thing in node pointer can deleted well, , not null referenced object? you can specialize node based on type of object, , pointer specialization, create destructor node-type allocates , deletes pointer managed node. for instance: //general node type non-pointer types template<typename t> struct linked_list_node { t data; linked_list_node<t>* next; linked_list_node(const t& d): data(d), next(null) {} ~linked_list_node() {} }; //specialized version pointer types template<typename t> struct linked_list_node<t*> { typedef void (*deleter)(

osx - Does Mac OS X come with a Lisp environment built in with Emacs? -

i have been trying find environment not involve installing else on mac lisp, not using after homework done (who know if continue using it). have tried can't find anything. know if have it, , how use within emacs? you have few options one-click lisp environments. if prefer emacs-based environment, check out lispbox . installs separate instance of emacs, afaik, won't have existing emacs settings it. if want use existing emacs, slime available both through quicklisp (which should using) or through elpa . if you're ok not having emacs environment, , you're not going using language long, lispworks personal , has one-click environment installer in os x. if asking scheme (or go either scheme or common lisp), take @ racket (not technically scheme, has lot of additional features, support r5rs , have short list of unsupported r6rs features ).

objective c - ios change notifications for app from inside app -

i have "settings" tab inside app asks user if want "receive notifications when app closed?" normally user has in ios5 notifications center in general tab. can modify settings own app? no, can't directly modify settings in app. the best can use url scheme take user directly notification settings app: [[uiapplication sharedapplication] openurl:[nsurl urlwithstring:@"prefs:root=notifications_id&path=mail"]]; (replace "mail" bundle display name of app.)

wordpress - Resolving a duplicate primary key on mysql import -

i'm looking append comments table 1 wordpress site another. users different. when import comments site b a, run duplicate key issue; comment_id taken. so how can resolve , append table simple .sql file? have take user information, generate new user, check comments made on site b, pull content , postid, go site , recreate comment newly created user!? what headache! thanks. if problem duplicate key issue, go end of sql file after engine=myisam , make engine=myisam autoincrement=a nubmer above last id in new database or query database last id add 1 , use on new insert query. example 1: create table if not exists `movies` ( `id` int(255) not null auto_increment, `title` varchar(255) not null, `year` int(4) not null, `size` varchar(255) not null, `added` date not null, primary key (`id`), unique key `title` (`title`,`year`) ) engine=innodb default charset=latin1 auto_increment=4 ; the inserts dump: insert `movies` (`title`, `year`, `size`,

jquery - Adding AJAX function to anchor behavior but Keeping href for SEO -

is possible have link/button execute ajax/jquery function load new content @ same time contains link page same specific content? this seo, , concerned crawler unable index sitemap. something not sure: <a href="mypage.html" onclick="javascript: loadajaxcontent()" > page </a> the overall goal create dynamic site nice effects between transition of 1 page , another. @ same time, want search engines find pages. you need use first prevent default action tag. easiest way use jquery seen below. dont know specific html element lets assume have 1 anchor tag on page. first, once document loaded, bind click event anchor. once ancore clicked prevent default action occuring. can perform whatever action desire. $(document).ready(function() { $('a').click(function(e) { e.preventdefault(); //perform ajax loading }); });

frontpage - Yootheme joomla template 2.5 remove content block in front page -

i'm manage remove content part in front page (inner page still remain) in yootheme joomla 2.5, after go through several post , tutorial, added following code: <?php $menu = & jsite::getmenu(); if($menu->getactive() !== $menu->getdefault()) : ?> <jdoc:include type="component" /> <?php endif; ?> after hacked of code, content block removed frontpage article, block still appear blank box, i've try system output setting selected no in backend, content block unable display front , inner page, how can totally kick frontpage blank box away? please advise & thanks! turn off blocks in theme using modules section of joomla console, if want remove default front page logo text bubbles, in modules, can turned off in yootheme template config, accessible joomla console.

How to find wather SharePoint Foundation 2010 Sp1 and CU June 2011 are installed in the windows 2008 server R2 -

how find out weather sharepoint 2010 sp1 , cujune 2011 installed in windows 2008 server r2? you can go ca or powershell , build version. get-spfarm | select buildversion

How to create an instance of enum using reflection in java? -

when i'm reading "effective java", author told me single-element enum type best way implement singleton, because don't have consider sophisticated serialization or reflection attacks. means cannot create instance of enum using reflection, right? have done test, enum class here: public enum weekday {} then tried create instance of weekday: class<weekday> weekdayclass = weekday.class; constructor<weekday> cw = weekdayclass.getconstructor(null); cw.setaccessible(true); cw.newinstance(null); as know, doesn't work. when change key word "enum" "class", works. want know why. thank pre. this built language. java language specification (§8.9) : it compile-time error attempt explicitly instantiate enum type (§15.9.1). final clone method in enum ensures enum constants can never cloned, , special treatment serialization mechanism ensures duplicate instances never created result of deserialization.

java - Why should we declare interface methods as public? -

this question has answer here: protected in interfaces 13 answers when implement interface method, forced make public method. we may have cases want use either default (like in case of access within same package) or protected . can please explain reason behind limitation? interfaces meant define public api of type - , that, not implementation. method (or static member) define in interface definition public . since interface can't contain concrete implementation, there no way call member methods within. , declaring such methods leaving calls them subclasses or totally unrelated clients mean type definition incomplete , brittle. why if need define protected or package access members, can in abstract class (which may contain implementation).

database - custom mysql function - cant pass parameters down -

as title states. here's function delimiter // create function getcreatevalue( table_name char(64), id_field char(64), name_field char(64), name_value char(64) ) returns integer begin declare ret integer; select count(*) ret table_name name_field = name_value; if ret < 1 insert table_name set name_field = name_value; select id_field ret table_name name_field = name_value; else select id_field ret table_name name_field = name_value; end if; return ret; end// delimiter ; when run like select getcreatevalue('table1', 'id', 'name', '123456'); i error table "table_name" does't exist. parameter wasnt passed. why? set @qry = concat( 'select count(*) ret ', table_name, ' ', name_field, ' = ?'); prepare stmt1 @qry; set @v = name_value; execute stmt1 using @v; deallocate prepare stmt1;

ios - Storing complete class object into database in iPhone -

i new development. i want store complete object of class database. creating application user can add multiple views parent view , want save it, next time when user fetches it, ever has saved i.e. views parent view previously. any logic or suggestion on same helpful, thanks in advance any object want save need conform nscoder protocol. keep in mind if have custom objects within parent object need conform nscoder. add following methods custom class(es). - (id)initwithcoder:(nscoder *)coder { _inventory = [[coder decodeobjectforkey:@"inventory"] retain]; return self; } - (void)encodewithcoder:(nscoder *) encoder{ [encoder encodeobject:_inventory forkey:@"inventory"]; } in example above want encode player's inventory. if inventory contains custom objects (as opposed bunch of nsstrings example) they'll need own nscoder methods. below turn can save out nsuserdefaults. adjust appropriately store in db. keep in mind if want send nsd

c# - Login Form trouble -

i wrote following code log in application using c# , linq. connected sql service oriented database have created in visual studio. problem having 1 not understand , hoping can me here. have created 2 message boxed try see output of code buy not getting it. if great! public bool userlogin(string user, string pass) { var database = new exampledataset(); var query = employee in database.employee (employee.employeeid.tostring() == employee.tolower() && employee.password == pass) select employee; if (query.count() != 0) { return true; messagebox.show("you logged in"); } return false; messagebox.show("you not logged in"); } private void cmdlogin_click(object sender, eventargs e) { string user = (txtuser.text); string pass = (txtpass.text); userlogin(user, pass); } from code wrote, seems problem compare string representation of employee employeeid property employee.employe

How to create Cash Register Effect using Pure Javascript? -

i wanted create cash register effect using pure javascript(with out using libraries), here link cash register effect implemented using mootools, http://jsbin.com/ehuzes/edit#preview i want effect using raw javascript. huge help, if gives solution. $('#number').on('change', function (e) { $(this).cashregister($(this).val()); }); (function ($) { $.fn.cashregister = function (num) { var output = $('#output').html(); function intervalfunc(interval, num) { var end = parseint($('#number').html()); var cont = parseint($('#output').html()) $('#output').html( cont + interval ); if ( $('#output').html() == num ) { clearinterval(int); return false; } } if (num > output) { var int = setinterval(function() { intervalfunc(1, num) }, 0.1); }else if (num < output) {

c++ - Fast bucket implementation -

in graph class need handle nodes integer values (1-1000 mostly). in every step want remove node , neighbors graph. want begin node of minimal value. thought long how in fastest possible manner , decided following: the graph stored using adjancency lists there huge array std::vector<node*> bucket[1000] store nodes value the index of lowest nonempty bucket stored , kept track off i can find node of minimal value fast picking random element of index or if bucket empty increase index removing selected node bucket can done in o(1), problem removing neighbors need search bucket bucket[value of neighbor] first neighbor nodes, not fast. is there more efficient approach this? i thought of using std::list<node*> bucket[1000] , , assign every node pointer "list element", such can remove node list in o(1). possible stl lists, can done normal double linked list implement hand? i did similar priority queue implementation using buckets. what did use h

mysql - Whats an efficent way to put multiple types of users in a db -

i'm building website have users logging site multiple sources, including facebook , google+ , want able keep basic info on each user in data base, can track creation of things comments , posts. how efficiently in sql database. create new table each type of user? the usual approach is: a user table common data a facebook_user table (which has it's own pk , user fk) facebook specific data a google_user table... when loading user, can join tables or can create view contains join or, if have many special types, can load user , read others individually (maybe keep is_x_user in user table speed up).

java - Ext Gwt setVisible results in disappearing fields -

i'm having issue have 4 form fields in fieldset. if conditions met, use setvisible(true/false) hide or show fieldset. i'm running problem hide fieldset, when make appear, doesn't display labels , textfield boxes. if in reverse, show fieldset, hide later, have no problem switching between views , having show properly. i use hboxlayout fieldset. i'm wondering if it's layout potentially causing problem or maybe it's rendering order? does have workaround or solution? thanks. the workaround found removing , adding fields again. it's still not identical, fields seem pushed on bit left side, @ least shows again.

Access RGB of each pixels in bitmap using C Win32 -

i have demo program written in plain c win32. program using framegrabber grab images camera , store them in main memory buffer (images 8bit/pixel grayscale). demo can show grabbed images on computer screen. , save them on hard disk. now want add function program, read raw data buffer each frame , lets show each pixel color (rgb) on console, can use them analysing. i have following information far in code : lpstr createbmp( hwnd happwnd, int nimagetype ) { void * pwingbits = null; int i; z_bitmapinfo zwingheader; // bitmapinfo cerating dib // create dc bitmap. hdcbits = createcompatibledc( ghdcmain ); switch ( nimagetype ) { case bayer_filter: break; case color32: break; case color24: break; case color3x16: break; case bw1x10: break; default: case bw8: // create bitmap-infoheader. zwingheader.bmiheader.bisize = sizeof( bitmapinfoheader ); zwingheader.bmiheader.bi

jquery - JSONP request successful, but returns no data -

i'm having trouble retrieving jsonp data 1 of sites. on site data being provided following mvc2 controller action: public jsonresult jsonlist(string key) { var consultants = rep.findall().where(c => c.isactive).select(c => new consultantjsonitem { firstname = c.firstname, surname = c.surname }); return json(consultants, "application/json"); } on site b, i'm using jquery retrieve json, this: $.ajax({ url: 'http://www.sitea.com/controller/jsonaction/', datatype: 'jsonp', crossdomain: true, success: function (json) { alert("success"); // displays alert(json); // empty }, error: function (xhr, status, error) { alert(status); // not called } }); i can see in firebug console response completed correctly 200 code, , can see content length of response 11516 bytes, yet response tab empty , jquery not give me data work with. can tell me why is? note: site using jquery 1.

java - Primefaces Panels inside OrderList -

i'd implement reordering of list elements using p:orderlist , p:panel components. there pojos in list, problem occurs list of strings. there bean: public class backingbean { private list<string> list; public void adddate() { list.add(new date().tostring()); } // getters , setters... } my page source: <p:orderlist id="videos" value="#{bean.list}" var="date" itemvalue="#{date}" controlslocation="none"> <p:column > <p:panel header="#{date}" toggleable="true" togglespeed="500"> fc barcelona 1 of 3 clubs... </p:panel> </p:column> </p:orderlist> the problem every time toggle 1 of panels, panels minimized , maximized few times, i.e. if there 3 elements in list, panels maximized/minimized 3 times. wrong? well, depends if need reordering functionality. if can afford go without i

sql - Creating a table and populating with a merge -

i have sql 2008 r2 table consists of (col1(char), col2(int, prim key), col3(char)). i populating table with... merge [dbo].[data] target using ( select 01, 1, 'data1' union select 03, 2, 'data2' union select d2, 3, 'data3' )as source ([col1], [col2], [col3]) on (target.[col2] = source.[col2]) when matched update set [col1] = source.[col1], [col3] = source.[col3] when not matched insert ([col1], [col2], [col3]) values (source.[col1],source.[col2], source.[col3]); it populates fine, aside "select d2, 3, 'data3'" statement, , throws invalid column name. ideas why or how fix it? thanks you need add little char col1: ' merge [dbo].[data] target using ( select '01' col1, 1 col2, 'data1' col3 union select '03', 2, 'data2' union select 'd2', 3, 'data3' )as source ([col1], [col2], [col3]) on (target.[col2] = source.[col2]) when matched up

Dropdown in html -

i have dropdown states in html. when go through list, goes expanding on page. there way can limit this? don't want display using size=" " property. you might try styling css . here's example: .fakelist { height: 30px; }

asp.net mvc 3 - Can One Link Invoke Two Ajax Updates? -

i have mvc 3 page has 2 partial views, 1 items in bucket a , , 1 items in bucket b (simplified discussion... there's significant logic rendering each bucket, , logic different between buckets). i have link on page lets me move item bucket a bucket b . once link clicked, have refresh partial views items in bucket a , , partial view items in bucket b . i can refresh 1 or other using ajax, this: @ajax.actionlink("move b", "_bucketb", "home", new { item = model.item }, new ajaxoptions() { updatetargetid = "divforbucketb", httpmethod = "post", insertionmode = insertionmode.replace }) how can approach problem of refreshing divforbucketa when actionlink clicked? update the html goes divforbucketa needs generated using appropriate view , controller. changes div contents significant processed on client in javascript (other perhaps invoking ajax call... can done?) this how jquery. need fix url.ac

java - Disable JFrame when a new JFrame is opened -

i trying disable "main" jframe when new frame pops up. want can not click or drag on frame. tried making new frame jdialog , did not disable other frame. looked @ other post this, suggested make jdialog still not work. need doing please. thanks. codeii using make jdialog , problems it? editdialog=new jdialog(introscreen.frame); introscreen.frame represents "main" frame. you have set jdialog#setmodal or jdialog#modalitytypes , maybe dialog.modalitytype application_modal

iphone - How to open preferences/settings with iOS 5.1? -

looks ios 5.1 has broken standard url encoding navigating user preference. for example: [[uiapplication sharedapplication] openurl:[nsurl urlwithstring:@"prefs:root=twitter"]]; works in ios 5.0 not in ios 5.1 (both device , simulator). has found way replicate functionality in ios 5.1? no don’t know way replicate functionality. but can file radar requesting restoration. here radar requesting schemes documented in first place. david barnard has confirmed ios 5.1 breaks settings apps url schemes. update : ios 8 has similar functionality opening app’s settings. apple, mike , soto_ighost . the constant uiapplicationopensettingsurlstring (uiapplication documentation) open settings app , not, twitter’s settings. not same functionality cleaner before , officially recognized. this should useful each app has place in settings using privacy, cellular data, background app refresh , notifications.

unscheduling a scheduled task in Android with ScheduledExecutorService -

i use scheduler ensure loop not take long, exit loop if scheduler fires , ends loop. this quite straight forward: public void startschedulerfortimeout() { log.i("x", "scheduling timeout " ); timeoutforloopreached = false; scheduler.schedule(new runnable() { public void run() { timeoutforloopreached = true; log.i("x", "set timeout flag "); } }, 10, timeunit.seconds); } so in code write: startschedulerforusbmessagetimeout(); while (!done && !timeoutforloopreached) { ...do loop stuff } to make sure scheduled task not fire when run loop again need unschedule obsolete task (in case ended loop before timeout) new timer start again @ beginning of new loop (instead of old 1 firing after first loop has been finished right in between second time loop executes) how can unschedule scheduled task has not been fired avoid scheduled task mixup? many thanks! use scheduledfuture :

how does emacs implement grep? -

when emacs grep, can split window , show nice buffer , , emacs has function (grep args),i want know, how can source code? emacs executes external grep process, , formats output. assuming mean source code wraps , displays it, not grep itself, pretty simple: m-x find-function <ret> grep <ret> (find-function function) find definition of function near point. finds source file containing definition of function near point (selected `function-called-at-point') in buffer , places point before definition. set mark before moving, if buffer existed. you may find find-library useful poke around with.

java - Writing a .class file? -

currently, i'm working on project user can enter in custom values in gui values translated .class file runtime read when program starts up. realize writing .txt file easier, not want do. new .class file making extend abstract class called "problem" also. can point me in right direction writing aforementioned file? in advance helpers! way, if have construct .java file compile somehow, solution also. still, don't know how :/ more code: package resources; import java.awt.image; import java.io.file; import java.io.serializable; public abstract class problem implements comparable<problem>, serializable{ private static final long serialversionuid = 42l; private file locatedat; public static final int easy = 0; public static final int medium = 1; public static final int hard = 2; public abstract string gettitle(); public abstract string getquestion(); public abstract image getquestionimage(); public abstract int getdiffic

php - Best practices for SOA and articles -

i building soa, , 1 of things provide clients (all under our control), articles. on client side figured on caching articles , article listings there no need store them in db. problem comes comments have stored on per client basis. thought seemed odd store article comments without article in db, , seems pretty obvious me should not handled soa. i guess question is, faced problem, teh best way proceed? store comments in db, without articles. store articles , comments in db. or maybe make soa handle them?

php - google oauth authentication -

i trying pass authorization data google plus data variable keeps showing value of "moved temporarily" doing wrong? <?php session_start(); $client_id = ''; $client_secret = ''; $api_key = ''; $redirect_uri = 'http://localhost:8888/oauth'; $scope = "https://www.googleapis.com/auth/plus.me"; if (!isset($_request['code'])) { $login_path = "https://accounts.google.com/o/oauth2/auth?"; $login_path .= "redirect_uri=" . $redirect_uri; $login_path .= "&response_type=code"; $login_path .= "&client_id=" . $client_id; $login_path .= "&approval_prompt=force"; $login_path .= "&scope=" . $scope; $login_path .= "&access_type=offline"; echo "<a href='" . $login_path . "'>login</a>"; } else {

CSS Overflow issue with IE7 -

Image
so in ie8 , above along other browsers such firefox have div grow when there data in div automatically this: .example { min-height:1px; overflow:hidden; } but in ie7 content inside div not fill out. below example: so thought fix ie7 issue this: .example { min-height:1px; overflow:hidden; } * html .example { height:1px; overflow:visible; } but in ie7 show 1 pixel height, still looks see in example above min-height in ie7. how can get, cross browsers, have content inside div auto fill out content inside div min-height in ie8 above? min-height buggy in ie7. quick fix: .example { min-height: 1px; height: auto !important; height: 1px; } anyway, don't know why need min-height ... problem overflow: hidden won't work in ie7 unless parent container has position: relative .

python - Type error when trying to access the dict value -

i have dict d1={'a':['in-gaap','inr',0,1],'b':['in-gaap','inr',0,2],'c':['in-ca','share',0,4],'n1':['','','','aaa']} d2={'d':['in-gaap','inr',0,'a+b'],'e':['in-gaap','inr',0,'y+t']} k in d2.iterkeys(): a=re.findall('\w+',d2[k][3]) x2=dict([(x,d1.get(x,0)[3])for x in a]) # here showing type:error int obj not subscriptable d1[k]=[d2[k][0],d2[k][1],d2[k][2],eval(d2[k][3],x2)] 'a' list dynamically created splits d[k][3] , stores in "a" d[k][3] contains in first iteration a=['a','b'] , in second iteration a=['y','t'] comparing list "a" keys dict "d1" keys if key takes value or assigns default value,upto working fine. when try create dict comparing list "a" dict "d1" ,by using cod

java - Multiton - real world example? -

i'm reviewing design patterns. came across 1 multiton , find difficult think of real-worlds usage example. so what's main field of application strengths of multiton pattern? telephonymanager telephonymanager = (telephonymanager) getsystemservice(context.telephony_service); inputmethodmanager imm = (inputmethodmanager) getsystemservice(context.input_method_service); clipboardmanager clipboard = (clipboardmanager) getsystemservice(clipboard_service); this multitone, real life example

php - Creating a multi dimensional array - is there a better way than this -

i have code foreach ($objworksheet->getrowiterator() $row) { $output[] = array(); //adding blank array end doesn't seem //advance array pointer manually. $test = end($output); $celliterator = $row->getcelliterator(); foreach ($celliterator $cell) { //specifically bit $output[key($output)][] = $cell->getvalue(); } } but don't how i've found current key using $output[key($output)][] = $cell->getvalue(); is there better approach? why don't use variable? foreach ($objworksheet->getrowiterator() $row) { $cells = array(); foreach ($row->getcelliterator() $cell) { $cells[] = $cell->getvalue(); } $output[] = $cells; }

c# - How to make a Excel CommandBarButton Invisible on create? -

Image
i have excel add-in has 2 buttons, second of hidden when add-in loaded. here code: public void onstartupcomplete(ref system.array custom) { object omissing = system.reflection.missing.value; commandbarbutton button1 = (commandbarbutton)g_plctoolbarinstance.controls.add(1, omissing, omissing, omissing, omissing); button1 .visible = true; button1 .enabled = true; button1 .caption = "button1"; button1 .style = msobuttonstyle.msobuttonicon; button1 .picture = picturedispconverter.toipicturedisp(oneico); commandbarbutton button2 = (commandbarbutton)g_plctoolbarinstance.controls.add(1, omissing, omissing, omissing, omissing); button2 .visible = false; button2 .enabled = false; button2 .caption = "button2"; button2 .style = msobuttonstyle.msobuttonicon; button2 .picture = picturedispconverter.toipicturedisp(twoico); .... } problem second button gets drawn, removed (instead o

xml - Android hdpi/mdpi/ldpi for Values folder? -

android allows define hdpi/mdpi/ldpi drawable folder in order account different sized screens/devices. wondering if same support can applied values folder (or layout folder)? reason being, typically define "sizes.xml" file holds standard dp sizes apply margins , paddings. same sp sizes text. i'd adjust values based on phones dpi. yes, believe in res/ folder can use "configuration qualifiers". example, can have values-sw600dp-mdpi-land/ folder. see "using configuration qualifiers": http://developer.android.com/guide/practices/screens_support.html#qualifiers i first noticed looking @ google's iosched app sample code, @ res folder: https://github.com/google/iosched/tree/master/android/src/main/res you'll see have "values-sw600dp-land", "values-w400dp" , "values-v17" folders, name few.

ios - Clearing after-image from Airplay device, using UIWebView -

i send secondary ui airplay - on ios 5.1. on ipad, user may use uiwebview play video, , if have airplay setup, video sent airplay device. when video finishes playing or if user pauses, uiwebview not clear out image airplay screen. if load different url uiwebview, airplay image clear out, after few seconds. i've tried work-around loading blank page, , reloading original video page, not seem work. thoughts? in effort clear other types of content uiwebview, happened discover following statement disconnect airplay video connection immediately, , thereby revealing underlying secondary ui sent via uiscreen. [mywebview stringbyevaluatingjavascriptfromstring:@"document.body.innerhtml = \"\";"];

iphone - Setting "device-width" property on iPad -

i'm trying implement uiwebview display twitter webapp (the iphone version) . it's little widget inside ipad app . but, realize webapp uses "device-width" property determine size of webapp . so, can't make twitter's webapp fit 320px width uiwebview . my question: there someway "fake" property , set own value it? btw: i've tried this: displaying wiki mobile page in uiwebview within uipopovercontroller it kinda works, resizes fit webview's frame. but, reason, makes twitter show old (very old, , ugly) webapp, instead of current one. here's webview implementation: lateralweb = [[lateralwebview alloc] initwithnibname:@"lateralwebview" bundle:nil]; lateralweb.view.frame = cgrectmake(0, 0, 320, self.view.bounds.size.height); lateralweb.webview.autoresizingmask = uiviewautoresizingflexibleheight; lateralweb.webview.scalespagetofit = yes; lateralweb.webview.scrollview.contentsize = cgsizemake(320, self.view.bounds.siz

Ignoring whitespaces while reading input files in C -

i'm trying write code registers first word of every line command, want able read word regardless of there being spaces or not in front of it. i'm using fgets() , strncmp first x characters of each line this, doesn't work arbitrary amount of whitespace. have tried using sscanf() inside fgets() loop store first word of each line variable seems skipping through lines , reading them incorrectly. rather not post code quite lengthy this: while( fgets(line, buffer, input) != null ) { if(strncmp(line, "word", 4) != null) //do } there many strncmps , each of them ignore arbitrary amount of preceding spaces. you can use isspace skip on whitespace: #include <ctype.h> while( fgets(line, buffer, input) != null ) { char *p = line; while (isspace(*p)) // skip whitespace p++; if(strncmp(p, "word", 4) != null) //do }

jquery - About loading images using masonry.js -

recently, write project needs load items "pinterest". use masonry -- jquery plugin. but problem is, plugin runs after images loaded, because needs calculate size of items , reposition them. leads problem is: if images fail load, plugin not run or calculate in wrong way. has experience can give me help? var $container = $('#tweetbox'); $container.imagesloaded( function(){ $container.masonry({ itemselector : '.each_tweet' }); $('.fancy img').each(function(){ var $this = $(this), url = $this.attr('alt'); $this.attr('src',url); }); }); thank ! i found solution: use lazy load images load blank image first. after images loaded re-trigger masonary

Java multidimensional array considered a primitive or an object -

is int[][] matrix = new int[10][10]; primitive or considered object? when send parameter function, send reference (like object) or value (like primitive)? every java array object. when pass argument, pass copy of reference array.

Amazon AWS Itemsearch - Using Keywords to Search in Product Title Only -

does know how target amazon aws itemseach searches in product title only? i'm using keywords results returned vaguely related. this example searches 'wireless headset xbox' in 'accessories' node(676172011) of 'videogames': &operation=itemsearch &searchindex=videogames &itempage=1 &browsenode=676172011 &sort=salesrank &keywords=wireless%20headset%20xbox &responsegroup=large i expect return products 'wireless headset xbox' in tile. aprroximately 50% 'correct'. looking @ results returned similar 'astore' searches, results have keyword in title. any appreciated. according itemsearch documentation need replace keywords parameter title parameter: title - the title associated item. can enter or part of title. title searches subset of keyword searches. if title search yields insufficient results, consider using keywords search. [emphasis mine]

c# - Session in generic handler? -

i have following simple handler (removed code vissibilty sakes, below still fails) <%@ webhandler language="c#" class="downloadhandler" %> using system; using system.web; public class downloadhandler : ihttphandler { public void processrequest(httpcontext context) { if (context.session["t1"] != "true") { } } public bool isreusable { { return false; } } } the line if (context.session["t1"] != "true") failing "object reference not set instance of object." , dont quite why is? that's because http handler in order access session need explicitly implement irequiressessionstate interface. keep in mind if there implicit locking on session object , won't able have multiple handlers in same session state processed simultaneously. there ireadonlysessionstate interface read-only session state access.

java - Checking of a line is in a file with bufferedread and hashset -

my problem have write code check if customers name in txt file (customers.txt). the problem check hashset if customer in file , says isn't in file while is.(checked manually) please me solve this. the code have below. public class customer { //declaration public static string s; private string line ; public string namecustomer; /** * constructor */ public klant(){} /**checking of customer in file */ public void getcustomer() { // make simpleinoutdialog simpleinoutdialog input = new simpleinoutdialog("customers"); namecustomer = input.readstring("give in name"); try{ bufferedreader br = new bufferedreader(new filereader("l:\\documents/informatica/6de jaar/gip/customers.txt")); hashset<string> hs = new hashset<string>(); int = 0; while ((line = br.readline()) != null) { i++; if (i == 1){hs.add(br.readline());} if (i % 4 == 0){hs.add

Is it possible to retrieve id of Jenkins build I triggered via its API? -

let's trigger build sending request /job/awesomesauce/build . possible retrieve id of triggered build? i'm aware can try access /job/awesomesauce/lastbuild/api/json , give me erroneous information in case there multiple builds running @ once. additionally, there seem slight delay (few seconds) before gives me information running build. i had sort of thing, , here workaround used: had dummy parameter passed build (in case build_id of build; in case may timestamp), queried , parsed both build queue api ( [server]/queue/api/... ) , regular api (in case build has finished) build containing appropriate parameter value.

php - How do I get this function in a controller to load in view -

this in controller class landingpage extends ci_controller { public function startencryptedsession(){ $this->load->library('session'); $this->load->library('encrypt'); $this->load->view('index', array('session', $this->session)); } } how load in view index view code <?php echo $head; ?> <body> <?php echo $guts; ?> </body> <?php echo $foot; ?> <?php echo $session->userdata('session_key'); ?> i'm using code igniter mvc when load view, gives me: <h4>a php error encountered</h4> <p>severity: notice</p> <p>message: undefined variable: session</p> <p>filename: views/index.php</p> <p>line number: 8</p> </div><br /> <b>fatal error</b>: call member function userdata() on non-object you need pass variables want use view. this: one way: in con

Teaching git while keeping it 'as easy as svn' -

i @ university , group starting programming project together. in previous subject taught basics of svn , how commit, how use toitosesvn. told not worry branching (and not taught it) since small program. during project svn server went down, leaving unable work, people don't think of it. for project, pushing have dvcs. after explaining how git differs svn, said ok, want easy using svn. since using eclipse^ want instructions on how use git eclipse. (i plan on using egit ) since not taught it, branching foreign concept rest of group members. however, due new concepts in git (for example, branching) how use gui not thing needs taught. how introduce concepts of git in way easy svn developers used gui? note: git being used because pushing , know (and don't know mercurial or bazaar) ^: building android program. a few notes: git ready good, gentle introduction git. i visual nature of git computer scientists . git not analogous subversion. trying draw analo

ruby - Single method_missing for Array, Hash and Range -

i new ruby. there way write single 'def array/range/hash' method_missing work ranges, arrays , hash i.e. enumerables ? e.g. following should work: [1..5].sum() [1,2,3,5].sum() {'x' => 1, 'y' = 4}.sum() sum() our custom method defined inside method_missing. of now, have written 3 different functions handle method_missing array, range , hash separately. you can define method_missing enumerables opening enumerable module , adding instance method it: module enumerable def method_missing *args puts 'hi' end end [].hithere # => hi but recommend define concrete sum method (starts lower case letter, according ruby methods naming guidelines) instead of adding logic method_missing : module enumerable def sum # implementation end end [].sum

SocketError (getaddrinfo: Name or service not known) - Sunspot/Solr Rails development -

i have had lots of trouble deploying rails 3.0.10 application ubuntu 10.04 server passenger, capistrano, nginx , mysql (and more trouble apache2). after downgrading rake 0.8.7 it's working, sunspot/solr doesn't work in development environment. sunspot_solr server running, , able server's url, , connect via browser. url same in sunspot.yml. have no idea have done can have caused problem. had same problem sunspot earlier (before downgraded rake). started working again. don't know why... have tried 2 versions of sunspot (1.2.1 , 1.3.0). both have been working earlier, not anymore. this error message i'm getting: socketerror (getaddrinfo: name or service not known): app/models/resource.rb:128:in `text_search' app/controllers/search_controller.rb:21:in `index' rendered /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.10/lib/action_dispatch/middleware/templates/rescues/_trace.erb (2.0ms) rendered /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.10/lib/action_dispatch

php - Converting json to jsonp -

i created account on 500px.com, , use api: http://developer.500px.com/ but looks cant return jsonp, json. is there way make php file can post url -> make convert response api json jsonp, can handle on client side? i havent been writing php in long time, appreciated. hope idea, otherwise ill elaborate. thanks sure can. difference between json , jsonp jsonp wrapped function name; { "x": "hello" } // json foo({ "x": "hello" }); // jsonp. in it's simplest form can end this; <?php echo $_get['callback']; ?>(<?php echo file_get_contents($_get['endpoint']); ?>); and you'd expect clients use this; http://yourserver.com/proxy.php?endpoint=https%3a%2f%2fapi.500px.com%2fv1%2foauth%2fauthorize&callback=foo note encoded url , addition of callback parameter know function invoke. of course , you'll need valid input; check existance of parameters, check endpoint passed isn't mal

Android ListView: Do I need to create another class to use it? -

i have app using scrollview , loads lot of images. i decided change listview. saw use listview, class must extend listactivity. my current class lot of things, inserting in database, updating, etc. so, should create new classe listview? can current class extends listactivity? in case need create separate class listview, how use in current class? any appreciated! best regards your class doesn't necessary have extend listactivity use simple activity listview element in it's layout. use existing activity replace current scrollview element listview element. retrieve element in oncreate() , set adapter map images listview rows. have make own custom adapter show images.

regex - Range in reverse order? -

the following regex failing on me; [aa][æ-åÆ-Å].* but regex not failing [aa][v-zv-z].* it when æ-å used (danish carachters). im puzzled why? the error getting it parsing "[aa][æ-åÆ-Å].*" - [x-y] range in reverse order. æ character code 145, while å character code 134, you're saying give me characters between character codes 145 , 134 doesn't work since lower bound greater upper bound. same true Æ Å . here's 1 chart of character codes can determine regex need create instead: http://www.asciitable.com/

python - Configure Django to use a certain database only for write queries -

we have open source app built django http://map.ninux.org/ used our wireless community network , hosted outside of our network hetzner in nurimberg. we'd have mirror inside our network internal use only. i set mirror write queries on database hosted outside network. best set mirror write queries both on local db , on 1 outside network. any suggestion? i'm wondering if there articles developing distributed / redundant / decentralized applications django. thanks! the multiple database documentation shows how set 2 databases , how select database saving write operations do.

string - How do I insert the results of several commands on a file as part of my sed stream? -

i use djing software on linux (xwax) uses 'scanning' script ( visible here ) compiles music files available software , outputs string contains path filename , title of mp3. example, if scans path-to-mp3/artist - test.mp3, spit out string so: path-to-mp3/artist - test.mp3[tab]artist - test i have tagged mp3s bpm information via id3v2 tool , have commandline method extracting information follows: id3v2 -l name-of-mp3.mp3 | grep tbpm | cut -d: -f2 that spits out numerical bpm me. i'd prepend bpm number above command part of xwax scanning script, i'm not sure how insert command in midst of script . i'd want generate is: path-to-mp3/artist - test.mp3[tab][bpm]artist - test any ideas? it's not clear me where in script want insert bpm number, idea this: to embed output of 1 command arguments of another, can use "command substitution" notation `...` or $(...) . example, this: rm $(echo abcd) runs command echo abcd , substitut