Posts

Showing posts from May, 2011

ios - UIBarButtonItem not appearing -

my app layout follows - the rootviewcontroller tabviewcontroller 3 tabs each having uinavigationcontroller rootviewcontroller. within 1 of these tabs pushing upon cell selection tabcontroller has 2 tabs. trying set rightbarbuttonitem on each of these 2 tab's viewcontrollers... in viewdidload method of both of these doing: self.navigationitem.rightbarbuttonitem = [[uibarbuttonitem alloc] initwithbarbuttonsystemitem:uibarbuttonsystemitemedit target:self action:@selector(selectionchanged:)]; however doing absolutely nothing! thought apple documentations set navigationitem's rightbarbuttonitem anywhere within navigation controllers view hierarchy doesn't seem case here. idea - if - doing wrong? the solution instead of setting rightbarbuttonitem on self.navigationitem need set on parent tabbarcontroller : self.tabbarcontroller.navigationitem.rightbarbuttonitem = [[uibarbuttonitem alloc] initwithbarbuttonsystemitem:uibarbuttonsystemitemedit target:self actio

sql server - How to implement trigger after insertion? -

i have column named htmlcontent stores html content in table eemaildata , column named eemaildataid unique id of table or can primary key of table. now want want create trigger primary key table , insert eemaildataid in column htmlcontent on specific location. i think take place substring function. can suggest me other solution? for need add id where want replace primary key value eg: <a href="localhost:19763/bitbucket/guest/... ?guestinvitefwd=uaraiad and use following trigger create trigger eemaildata_trigg on eemaildata after insert if exists (select top(1)* eemaildata p join inserted on p.eemaildataid = i.eemaildataid ) begin declare @html varchar(max),@id int select @html=htmlcontent ,@id=eemaildata eemaildata eemaildataid =(select top(1) eemaildataid inserted) update eemaildata set htmlcontent=replace(@html,'uaraiad',@id) eemaildataid=@id end now after trigger uaraiad replaced ee

ASP.net MVC 4 Drop Down List -

i bit lost on concept of drop down list in mvc 4. i have models gender - int id - string title user -string firstname - gender -... i bit unsure how tackle it, keep clean , simple. for type in class users, should gender because name of table or should ienumerable? if if missing other things? also should provide specific controllers? or how display dropdownlist in c# mvc 4 razor code. have @ selectlist class http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlist%28v=vs.108%29.aspx this goes in model, can create dropdownlist this: @html.dropdownlist("genderid", model.genders)

mysql - SQL JOIN many-to-many -

sorry minimalistic title don't know how describe in short. have 3 tables: the table of groups id | genre ----------------- 1 | action 2 | adventure 3 | drama many many table groupid | elementid ----------------- 3 | 1 1 | 2 2 | 2 2 | 3 3 | 3 and table of elements id | element ----------------- 1 | pride , prejudice 2 | alice in wonderland 3 | curious incident of dog in night time all fine , simple. select trying achieve following id | element | genre ------------------------------------------------------------- 1 | pride , prejudice | drama 2 | alice in wonderland | null 3 | curious incident of dog in night time | drama i want select all elements table elements , set genre field drama or null . i'm trying in mysql . thank in advance it's possible little trick (outer join on many-to-man

pygtk - How can I display a Gtk Widget over (inside) a Cairo surface? -

i have gtk widget named cloud (which subclasses gtk.eventbox) cairo surface painted svg. i'm trying display other gtk widgets (label/buttons) on it. i tried adding gtk.label elements cloud not shown on surface. using gtk.fixed , position cloud under label doesn't work either. how draw gtk widget on cairo surface? i don't know cloud gtk widget is; more generally, can use gtk.overlay . add() cloud widget main child, add_overlay() other widgets.

ruby - Temporarily switch MongoMapper to read from slave replicas -

i'm using mongomapper our primary datastore, , want run reporting jobs against slave nodes in our replica set, rather primary. unfortunately, of our background jobs read/write , need go against primary. is there way can following: mongomapper.options({:slave_ok => true}) report.fetch_data # sorts of stuff, uses normal models, developer doesn't have go out of his/her way specify read preference mongomapper.options({:slave_ok => force}) right looks mongomapper wants set read preference bring connection , not change after that. mm doesn't natively support this, wouldn't hard on per-model basis via plugin. module mongomapper module plugins module readpreference extend activesupport::concern included class << self attr_accessor :read_preference end end module classmethods def query(options={}) options.merge!(:read => read_preference) if read_preference

Link into picture - jQuery -

what easiest way change element: <a href="pic.png"> into: <img src="pic.png"> use replacewith $('a').replacewith(function() { return $('<img/>').attr('src', this.href); }); replace 'a' selector links need replaced.

html - Unable to style the color of bullets in a list -

i'm trying change colour of list points it's not working? <div class="mobile-menu" id="mobile-menu"> <div id="mobile-menu-links"> <h4>general:</h4> <ul class="mobile-menu-links"> <li><a href="">news</a></li> <li><a href="">the boring rules!</a></li> <li><a href="">the rankings</a></li> </ul> .mobile-menu #mobile-menu-links ul{ list-style-type: none; margin:0; padding-left:3%; } .mobile-menu #mobile-menu-links ul li{ padding-bottom:2px; border-bottom:1px solid #bababa; } if add color:red in either of 2 css declarations, doesn't change colour. please note html closed in document, copi

caching - angular view not updating from shared service -

i need little bit of structuring angular app. i have 2 controllers, 'offerlistcntrl' (displays list of offers) , 'offerdetailscntrl' (displays single offer via id) service/model called 'offers'. connect 2 web services respectively via offers service, getoffers (returns array of offers) , getoffer (returns single offer) , trying avoid calling getoffer(id) if getoffers has been called (saves service call) myapp.factory('offers', function($http,config) { var data=[]; var offers = { get: function () { var promise = $http.get(config.api_end_point + "getoffers?appid=12",{cache:"true"}) .then(function (response){ data = response.data; return response.data; }); return promise; }, getoffer: function(id) { var local = _.find(data.offers, function(offer) { return offer.offerid == id }); if(local){ console.log("local cop

c++ - Return the count of negative numbers in the optimal way -

a variation of "searching in matrix sorted rowwise , columnwise" given 2d matrix sorted rowwise , columnwise. have return count of negative numbers in optimal way. i think of solution initialise rowindex=0 if rowindex>0 rowindex++ else apply binary search and implemented in code 5x5 matrix #include<iostream> #include<cstdio> using namespace std; int arr[5][5]; int func(int row) { int hi=4; int lo=0; int mid=(lo+hi)/2; while(hi>=lo) { mid=(lo+hi)/2; . if(mid==4) { return 5; } if(arr[row][mid]<0 && arr[row][mid+1]<0) { lo=mid+1; } else if(arr[row][mid]>0 && arr[row][mid+1]>0) { hi=mid-1; } else if(arr[row][mid]<0 && arr[row][mid+1]>0) { return mid+1; } } } int main() { int ri,ci,sum; ri=0; //rowindex ci=0

c# - issue Initializing SimpleMembership in filter class -

i trying initialize attribute class reason struggling results. i have created mvc4 "basic" project template in visual studio 2012. have created folder name filters in project , create class initializesimplemembership.cs. have home controller , associated view , calling [initializesimplemembership] in home controller class no result. application not generating required tables. (note: have created database before) i trying initialize simplemembership least code can understand , make complex along grows. in filter folder using system; using system.data.entity; using system.data.entity.infrastructure; using system.threading; using system.web.mvc; using webmatrix.webdata; using simplelogin_system_04.models; namespace simplelogin_system_04.filters { public class initializesimplemembership : actionfilterattribute { private class simplemembershipinitializer { public simplemembershipinitializer() { try {

javascript - Google Chrome: how to fetch "minimized" event? -

i try fetch events when state of window changes. far, use content script adds "resize" listener window: window.onresize = function() {...} . allows me fetch when window's state changes "normal", "maximized" , "fullscreen". however, have no idea "minimized". minimizing window not fire "resize" events. tried use onfocuschanged api add listener, i.e., chrome.windows.onfocuschanged.addlistener(function(windowid) {...})); , has issues. firstly, if window minimize has focus, windowid = -1 (chrome.windows.window_id_none) , cannot fetch window readout state. , secondly, if window doesn't have focus, onfocuschanged event not fired. in short, how can detect when chrome window has been minimized. lot hints i think might help: chrome.windows.onfocuschanged.addlistener(function() { console.log("focus changed."); chrome.windows.getcurrent(function(window){ console.log(window.state);

ruby on rails - Pow domains not loading in Chrome -

so, struggled last hour. reason, pow domains hit www.website-unavailable.com error in chrome. rails servers work great traditional rails s , pull @ localhost:3000 . i'm using anvil.app manage domains. no matter what, hit www.website-unavailable.com page in chrome each time try visit .dev domain. the strangest thing is, site loads great in other browsers. not chrome. tried installing chrome canary , hits exact same error (fresh install!). i tried, in order, no avail, server running again: rebooting. pow restart in terminal various sites. reinstalling pow. clearing dns cache @ chrome://net-internals#dns nothing seems work. idea working again? not huge deal use localhost:3000 love pow. strange thing is, working wonderfully weeks. i ran same issue, changing opendns google's dns servers didn't help. apparently, issue asynchronous dns built chrome. there couple workarounds: use .xip.io domain instead of .dev disable asynchronous dns in ch

what's the fast and new way(based on high performance) of reading event logs from remote machine using c# -

i know question has 100's of similar questions. have gone through of them , outdated , doesn't seem perform well. i trying read event logs remote computers using c#, way during slow (reading 60,000 logs) takes 30 mins. i using eventlogreader class i have tried event log query , wmi way. speaking slow. there other way of doing this. how can read them faster? i don't know if faster, worth shot my suggestion skip eventlogreader class , go straight wmi ( may able query want. also, can remote machine backup event log try copying backup... see http://msdn.microsoft.com/en-us/library/windows/desktop/aa394593(v=vs.85).aspx you may want @ how construct wmi query on how wmi c#

c++ - CUDA Copying multiple arrays of structs with cudaMemcpy -

suppose struct x primitives , array of y structs: typedef struct { int a; y** y; } x; an instance x1 of x initialized @ host, , copied instance x2 of x, on device memory, through cudamemcpy. this works fine primitives in x (such int a), cudamemcpy seems flatten double pointer single pointer, causing out of bounds exceptions wherever there's access struct arrays in x (such y). in case supposed use memcpy function, such cudamemcpy2d or cudamemcpyarraytoarray? suggestions appreciated. thanks! edit the natural approach (as in "that's i'd if c) towards copying array of structures cudamalloc array , cudamalloc , initialize each element separately, e.g.: x** h_x; x** d_x; int num_x; cudamalloc((void**)&d_x, sizeof(x)*num_x); int i=0; for(;i<num_x;i++) { cudamalloc((void**)d_x[i], sizeof(x)); cudamemcpy(&d_x[i], &h_x[i], sizeof(x), cudamemcpyhosttodevice); } however, for's cudamalloc generates crash. confess i'

Is there an on end event where I can free up drawable resources in android? -

in android app, use imageview's show images. want free when activity ends. read somewhere can use imgview.setimagedrawable(null); free up. when activity ends. there function on destroy or on end can override can free there? thanks actually there ondestroy in activity , don't need null drawable s unless introduced memory leak somewhere else in code.

c++ - Why does vector::pop_back invalidate the iterator (end() - 1)? -

note: question applies erase , too. see bottom. what's reason behind fact end() - 1 iterator invalidated after pop_back called on vector ? to clarify, i'm referring situation: std::vector<int> v; v.push_back(1); v.push_back(2); std::vector<int>::iterator i1 = v.begin(), i2 = v.end() - 1, i3 = v.begin() + 1; v.pop_back(); // i1 still valid // i2 invalid // i3 invalid std::vector<int>::iterator i4 = v.end(); assert(i2 == i4); // undefined behavior (but why should be?!) assert(i3 == i4); // undefined behavior (but why should be?!) why happen? (i.e. when invalidation ever prove beneficial implementation?) (note isn't theoretical problem. visual c++ 2013 -- , 2012 -- display error if try in debug mode, if have _iterator_debug_level set 2 .) regarding erase : note same question applies erase : why erase(end() - 1, end()) invalidate end() - 1 ? (so please don't say, " pop_back invalidates end() - 1 because equivalent

knockout.js - Using Knockout with Ember instead of handelbars -

knockout fantastic templating engine it's not framework angular , ember, durandal making progress i'd explore options. have 3 main questions: is there current support alternative templating engines in ember (real support, not it's possible)? has used knockout ember? how 1 go adding support knockout? is there current support alternative templating engines in ember (real support, not it's possible)? has used knockout ember? no. ember.handlebars tightly integrated ember binding system. may possible not advisable. how 1 go adding support knockout? the correct way approach have desired templating language in case knockout compile handlebars templates inside build process. this has been done quite in emblem project. emblem haml inspired indentation based templating language compiles handlebars. has required tooling support node based command line compiler, grunt tasks, runtime support coffeescript, etc. you have custom build if need thi

javascript - Less redundant way of putting this -

i have code stores checked value of checkbox in localstorage. how shrink it? $('#ospone').click(function(e){ savesettings(e["currenttarget"]["id"], e["currenttarget"]["checked"]); getsettings(e["currenttarget"]["id"]); }); $("#osptwo").click(function(e){ savesettings(e["currenttarget"]["id"], e["currenttarget"]["checked"]); getsettings(e["currenttarget"]["id"]); }); $("#ospthree").click(function(e){ savesettings(e["currenttarget"]["id"], e["currenttarget"]["checked"]); getsettings(e["currenttarget"]["id"]); }); $("#ospfour").click(function(e){ savesettings(e["currenttarget"]["id"], e["currenttarget"]["checked"]); getsettings(e["currenttarget"]["id"]); }); settings func

javascript - Why variable shows up as undefined? -

i querying user in friend request array works, check using useradd keeps showing undefined. know why showing undefined? this code: exports.searchpost = function(req, res, err) { user.find({$or:[ {firstname: req.body.firstname}, {lastname: req.body.lastname}, {email: req.body.email}, {phone: req.body.phone}] }, function(err, users) { if(err) { return res.render('searcherror', {title: 'weblio'}); } else { if(req.body.firstname=== '' && req.body.lastname==='' && req.body.email==='' && req.body.phone=== '') { //maybe diff page saying not valid search page return res.render('searcherror', {title: 'weblio'}); } else { var useradd; console.log('addman'); users.foreach(function(u

php - Inserting a custom binary format blob into SQL -

i have log file made in custom binary format. log file uploaded server , php inserts mysql database, so $tmpname = $_files['file']['tmp_name']; $fp = fopen($tmpname, 'r'); $content = fread($fp, filesize($tmpname)); $query = "insert device_log (did, devicelog) values ( '$res1', '$content')"; but doesn't work, because sql has trouble contents, giving you have error in sql syntax; check manual corresponds mysql server version right syntax use near '««»»qì™Ãºx' @ line 1 error. i've read need escape data mysql_real_escape_string , ruin initial data, i.e. wouldn't able read back. correct way insert such blob? you might want base64 encode data before insertion database, might alleviate issue (you need base64 decode data when reading back).

Objective C Calling Method Syntax -

this question has answer here: explain object variable declaration , assignment 4 answers i'm bit confused on how methods called , syntax behind it. can dissect 2 lines of code me? i've got bunch of random questions. nsstring *teststring; teststring = [[nsstring alloc] init]; so what's going on here? there's new pointer called teststring being created... point to? then in last line, it's being set, quite confused what. is: [[nsstring alloc] init] returning address? method "alloc" being called on nsstring, , init being called on output? alloc , init do? thanks. alloc / init standard way create new objects in objective-c. method alloc class method of nsobject class, nsstring (and other objective-c objects) subclass of. allocates memory string teststring , , returns that. init method returns empty , immutable st

html5 - :hover won't trigger because bounding box is in the way -

edit: seems problem on safari edit 2: newest safari beta fixes problem here problem: i trying create circular tab behind circular image , change opacity when hover on tab. the problem is, because bounding box on circular image square , image in front of tab, :hover element won't trigger. i created jsfiddle demonstrates problem: http://jsfiddle.net/hgarrerereyn/a6l5j/ here code in jsfiddle: html: <div id="div1"></div> <div id="div2"></div> css: #div1 { height:50px; width:50px; border-radius:50px; background:red; position:absolute; top:0px; left:0px; z-index:-1; } #div2 { height:200px; width:200px; border-radius:200px; background:blue; position:absolute; top:0px; left:0px; } /* next part doesnt work :( */ #div1:hover { opacity:0.5; } i okay using jquery if pure css won't cut it. appreciated if want change when hovering on circle in div2, try setting pointer-events: none; on overlapping div. b

android - NullPointerException when trying to load a button -

i trying open new activity. when null pointer exception. works untill following code gets executed. button rmtests =(button)findviewbyid(r.id.btnrmtests); rmtests.setonclicklistener(ansrmtest); here better @ code. public class displaytests extends listactivity { private dbmanagement mdbmanager; public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); //mdbmanager = new dbmanagement(this); //mdbmanager.open(); button rmtests =(button)findviewbyid(r.id.btnrmtests); rmtests.setonclicklistener(ansrmtest); //filldata(); } private onclicklistener ansrmtest = new onclicklistener(){ @override public void onclick(view v) { try{ system.out.println("fart"); } catch(exception ex){ system.out.println(ex.tostring()); } } }; i not sure why activity b

angularjs - Passing a dummy version of service to a controller in unit test -

i trying test controller passing dummy version of service. however, when karma runs makes call real service, specified in controller definition (line 3) instead of object try inject beforeeach(inject(function(....) please me identify doing wrong. //i have code following. angular.module('myapp') .controller('membersearch2ctrl', ['$scope', 'personnelservice', 'savedsearchservice', '$routeparams', '$log', function membersearch2ctrl($scope, personnelapi, savedsearches, $routeparams, $log) { // utilises personnelservice make ajax calls data server.... } ]); // real version of service makes ajax calls , returns real data angular.module('myapp') .service('personnelservice', function($http, $q) { //this.search(....) }); // dummy version of above, has same functions above returns hardcoded json angular.module('myapp') .service('personnelservicem

android - AndEngine move two objects simultaneously -

i creating game using andengine , in want object flying in sky drop bombs below. using timehandler create both flying object , bombs. but not working properly. problems facing are: 1) instead of single bomb 2 or 3 bombs dropped. 2) , bomb objects not getting recycled. code recycling object getting called, doesn't seem work. have noticed 1 thing i.e. suppose, have 1 flying object drops bomb. when bomb leaves screen, recycling code bomb object gets called once. , after sometime flying object leaves screen gets recycled. when flying object created , drops bomb, code recycling bomb getting called twice. third flying object, code recycling single bomb getting called thrice , on. the code add flying object follows private void createdragonhandler() { timerhandler spritetimerhandler; float meffectspawndelay = 10f; spritetimerhandler = new timerhandler(meffectspawndelay, true, new itimercallback() { @override public void

command line - how to copy only selected folders using robocopy? -

i have directory in there 36 subfolders. want copy last 18 folders using robocopy. how do that? there option can use? this batch file should skip 18 folders , use robocopy each individual folder after that. @echo off /f "skip=18 delims=" %%a in (' dir /a-d /b ') ( robocopy "%%a" "target folder" switches )

Select from three table on condition basise in mysql -

i have 3 tables 1- sale id unit ref 1 200 rm-s-2002 2 300 rm-s-2003 2- rent id unit ref 1 400 rm-r-2009 2 100 rm-r-2010 fields structure of both table same,in ref middle s represent sale table , r represent rent table 3- details id list_ref 1 rm-r-2010 2 rm-s-2002 3 rm-s-2003 the detail table contains ref of both tables(rent , sale).now want select unit if if details.list_ref=rent.ref select rent.unit else select sale.unit. here condition comes before select...how can used in query? try select d.id, d.list_ref, coalesce(s.unit, r.unit) unit details d left join sale s on d.list_ref = s.ref left join rent r on d.list_ref = r.ref sample output: | id | list_ref | unit | ------------------------- | 1 | rm-r-2010 | 100 | | 2 | rm-s-2002 | 200 | | 3 | rm-s-2003 | 300 | here sqlfiddle demo

backbone.js - backbone-relational: usage with standalone model without relations -

i using backbone-relational. usage onetomany model works fine. but having troubles using backbone-relational single/standalone model: window.beeronlineshopposition = backbone.relationalmodel.extend({ urlroot:"../api/beeronlineshoppositions", idattribute: 'id', relations: [ ], defaults:{ "id":null, "position_amount":"" } }); window.beeronlineshoppositioncollection = backbone.collection.extend({ model:beeronlineshopposition, url:"../api/beeronlineshoppositions" }); in main have: beeronlineshopproductdetails:function (id) { var beeronlineshopproduct = beeronlineshopproduct.findorcreate(id); beeronlineshopproduct.fetch(); var beeronlineshopproduct_view = new beeronlineshopproductview({el: $('#content'), model: beeronlineshopproduct}); }, so, when jump existing records (...beeronlineshop/beeronlineshopproducts/#4) , nothing happens. debugging shows, fetch executed , vie

C# why XmlDsigC14NTransform remove all whitespaces from xml -

i have problem xmldsigc14ntransform. trying repeat example http://www.di-mgt.com.au/xmldsig2.html (part compose canonicalized signedinfo element , compute signaturevalue) code loses whitespaces xml , cant correct hexdump. my c# code: xmldocument signedinfoxml = new xmldocument(); signedinfoxml.load(@"c:\temp\new_sign.txt"); xmldsigc14ntransform xmltransform = new xmldsigc14ntransform(); xmltransform.loadinput(signedinfoxml); memorystream memorystream = (memorystream)xmltransform.getoutput(); return bitconverter.tostring(memorystream.toarray()).replace("-"," "); source xml(from file c:\temp\new_sign.txt): <signedinfo xmlns="http://www.w3.org/2000/09/xmldsig#"> <canonicalizationmethod algorithm="http://www.w3.org/tr/2001/rec-xml-c14n-20010315" /> <signaturemethod algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" /> <reference uri=""> <tran

youtube - Need help to build http request for yoututbe video upload -

let me mention first learner @ building http requests. trying examine http traffic , how works. had luck loging in getting values of various tokens page , passing them parameters : galx, dsh, , bgresponse to : https://accounts.google.com/serviceloginauth with parameters: continue=$continue&service=youtube&dsh=$dsh&hl=en_us&galx=$galx&pstmsg=1&dnconn=&checkconnection=youtube:1000:1&checkeddomains=youtube&timestmp=&sectok=&_utf8=$_utf8&bgresponse=$bgresponse&email=$email&passwd=$password&signin=sign in&persistentcookie=yes&rmshown=1 now stuck @ trying build http request upload video youtube. apart video file parameters need pass upload video youtube? can please me build http request? any highly appreciated. in advance. praney i recommend use google's resumable upload guide. shows http requests need, simple example. enough me working, since friday evening encountering "503 : servic

wso2esb - WSO2 an Open Source Enterprise Service Bus (ESB) -

i new can u please guide me site start wso2 esb open source enterprise service bus (esb) proxy services wso2 docs best place started. you can refer wso2 esb 4.7.0 , latest wso2 esb release. please go through samples . you have few things to do before trying samples , can go through proxy service samples . i hope helps!

javascript - PhantomJS skip header on first page -

i want remove header first page , have header defined as: header = { height: header_height, contents: phantom.callback(function(pagenum, numpages) { if(pagenum == 1) { return ""; } return header_contents; }) }; but lefts empty margin header_height . there way set header.height=0 first page? you can't set margin first page. can include css style on first page phantomjs respects css margin

c - Explain typedef for function used in qsort library -

i using qsort library function sort array of structure elements, while searching on internet found resource: info: sorting structures c qsort() function @ support.microsoft. i understand qsort function requires typecast generic pointers. however not able line: typedef int (*compfn) (const void*, const void*); which has been declared, , subsequent call: qsort((void *) &array, // beginning address of array 10, // number of elements in array sizeof(struct animal), // size of each element (compfn)compare // pointer compare function ); how typedef behaving, mean have typedeffed int (*compfn) or int (compfn) ? if former, shouldn't call (*compfn) ? syntax: typedef int (*compfn) (const void*, const void*); ^ ^ ^ ^ ^ | return type | arguments type | new type name defining new type compfn new user def

Storing expensive database calculations in Microsoft SQL server -

i'm using microsoft sql server. want store/cache expensive calculations can reused. in example have items rated users, database schema looks this: user id : int item id : int useritemrating userid (user) itemid (item) rating : int to highest rated items need calculate average rating of each item (lets assume operation expensive , useritemrating changed/updated frequently). way of caching calculation? should add column "averagerating" item , create trigger updates it? create view? temporary table holds calculations? in sql server, create indexed view, this: create view dbo.itemratings schemabinding select itemid, count_big(*) cnt, sum(rating) totalrating dbo.useritemrating group itemid go create unique clustered index ix_itemratings on dbo.itemratings (itemid) there various restrictions on creation , usage of indexed views, above valid (assuming useritemrating in dbo schema). things note:

.net - HttpWebRequest - Redirect -

i html code page: http://trendstop.knack.be/nl/detail/446121707/6x-international.aspx each time make html request using: imports system imports system.io imports system.web imports system.net imports system.io.isolatedstorage imports system.threading imports microsoft.visualbasic imports system.text public class getsource function gethtml(byval strpage string) string dim strreply string = "null" try dim objhttprequest system.net.httpwebrequest dim objhttpresponse system.net.httpwebresponse objhttprequest = system.net.httpwebrequest.create(strpage) objhttpresponse = objhttprequest.getresponse dim objstrmreader new streamreader(objhttpresponse.getresponsestream) strreply = objstrmreader.readtoend() catch ex exception strreply = "error! " + ex.message.tostring end try return strreply end function end class i html of redirected ur

php - Save into database less and html -

i have site developed in cakephp (php) , in page user can insert textarea less code (css) , in textarea html code. i want store database problem is: - validate textarea usre doesn't insert bad code (iframe banner...) preserve security database , site, exist parsing, pattern , regular expression less code (css) , html code save database without possibility insert insane code php, cakephp(with model validation) or javascript? thanks validating , filtering html complex problem , might make sense restore tools written. here nice comparision (it might bit biased towards html purifier covers functionalities , problems of different solutions pretty wall) http://htmlpurifier.org/comparison if not sure tags should banned simplest approach filter against list of tags explicitly allow (whitelist)

c++ - Automatic downcast of a pointer to a derived object -

good morning, i have templatized class , want manipulate objects vector of pointers. use vector of pointers templatized class need class derived non-templatized class, , did it. here's problem: call method of derived class pointer base class, cannot use virtual functions because template functions can't made virtual. need make explicit cast, tedious: once create number object new, in fact, downcast need made number*, although object known number in advance. i solved problem in awkward way: function myset tests supported values of typeid correct dynamic cast. long series of nested ifs perform typeid checking. besides tediousness, function works calling 'set' method, , similar functions should defined calling other methods. if make automatic casting kind of object i'm pointing to, simpler. the cons of approach are: the code repetitive: if defined function (such t get() {return val;}, need myget function full set of nested ifs! the list of supported t

eclipse - Referenced classpath entry for JAR in local maven repository missing when importing nutch -

i trying import nutch 1.4 eclipse. cloned git repository , build using maven. then, imported in eclipse maven project, i'm getting following error: the archive: /home/devang/.m2/repository/javax/jms/jms/1.1/jms-1.1.jar referenced classpath, not exist. i've seen behaviour when had project imported in eclipse, deleted local maven repository. to solve this, make m2eclipse re-download project's dependencies: right-click on project , select maven > update project... select force update of snapshots/releases , hit ok

for loop - Explain the output of a c program -

#include<stdio.h> main() { static int i=1; printf("\nsoftware"); for(;i<5;i++) main(); return 0; } the output comes out infinite loop. please explain. you calling main function main function. after call new main function print string , again call main function. your i variable not incremented @ all, because not incremented in first iteration of loop. after call main , never return previous main next iteration of loop happen. loop infinite , i equal 1 . if changed loop other loop, loop still infinite. i'm including repaired code, fun of it: #include<stdio.h> int main() { static int i=0; if(i>=5) return 0; i++; printf("\nsoftware %i", i); main(); return 0; }

php - Calculate the index number of a value - bitwise sort of -

i want provide user visibility subscription pages using bitwise operators . if user's permission page 60 able see subscription pages visibility set on 2,3,4,5 (eg. 2^2 =4,2^3=8,2^4=16,2^5=32 32+16+4+2 =60 allowed view pages permission id =2,3,4,5) public function permission($perm) { $this->permission = ~$perm & $this->permission; } i used code useless need , suggesations.......thank :) adding permission: $this->permission |= $perm; checking if permission set: $is_permitted = (bool)($this->permission & $perm); checking permissions set: for ($permissions = array(), $i = ceil(log($this->permission, 2) + 0.1) /* floating point imprecision */; $i >= 0; $i--) if ($this->permission & (1 << $i)) $permissions[] = $i;

Is it possible to create a javascript api that only allows certain domains to call it -

i want provide data different websites through javascript api, , don't want others have modify backend code. i believe best way providing jsonp other websites (please correct me if wrong). however don't want able use api - options controlling usage of api. if api called js running on remote website use cors (check ie support). but if need more granular control on api usage must use key , check referer against key. btw using key can make script faking referer , using api. but if it's js api there's no alternative.

symfony - Persist association symfony2 -

i started using doctrine2 , associations don't understand aspects. i've 2 php class : class user extends baseuser { protected $id; protected $team; /** * id * * @return integer $id */ public function getid() { return $this->id; } public function setid($id) { $this->id = $id; } public function getteam() { return $this->team; } public function setteam($team) { $this->team = $team; } } and /** * team * * @orm\table(name="basket__team") * @orm\entity(repositoryclass="tperroin\basketbundle\entity\teamrepository") */ class team { /** * @var integer * * @orm\column(name="id", type="integer") * @orm\id * @orm\generatedvalue(strategy="auto") */ private $id; /** * @var string * * @orm\column(name="categorie", type="string", length=255) */ private $categorie; /** * @var string * * @orm\manytomany(targetentity="application\sonata\use

Using Perl regex to find and extract matches over multiple lines -

i have text file of several hundreds of terms in following format: [term] id: id1 name: name1 xref: type1:aab xref: type2:cdc [term] id: id2 name: name2 xref: type1:aba xref: type3:fee i need extract terms xref of type1 , write them new file in same format. planning use regular expression this: /\[term\](.*)type1(.*)[^\[term\]]/g to find corresponding terms don't know how search regex on multiple lines. should read original text file string or rather line line? appreciated. a different approach use $/ variable split blocks in blank line, each block split newline character , run regular expression each line.so when 1 of them matches print , read next block. example one-liner: perl -ne ' begin { $/ = q|| } @lines = split /\n/; $line ( @lines ) { if ( $line =~ m/xref:\s*type1/ ) { printf qq|%s|, $_; last; } } ' infile assuming input file like: [term] id: id1 name: nam

javascript - Add overlay pointer to an popup window in Extjs 4? -

Image
i want add arrow mark extjs window marked below. have created window required form fields , can point out place user clicked. requirement add arrow window. thanks in advance. <div id="overlay"> hello world </div> #overlay { width: 200px; height: 50px; position:relative; background-color: green; } #overlay:after { content: ""; position: absolute; top: 50px; left: 50px; width: 0px; height: 0px; border-top: 10px solid green; border-left: 10px solid transparent; border-right: 10px solid transparent; } the div after overlay looking this. in same way can add overlay sencha extjs window.

Format text string in matlab -

i'm trying extract parameter name string have: vi('$excitation', '0a', '0a', '0a') i want "$excitation" out of it. currently i'm using: for = 1:length(parameters); par{a,1} = sscanf ((parameters{a,1}),'vi(''%s, %*s, %*s, %*s,%*s')'; titles{1,a} = par{a,1}; end which gets me: "$excitation'," i've tried changing : 'vi(''%s'',, %*s, %*s, %*s,%*s' and no change in result. any suggestions? helpful explain why have doesn't work, don't make same mistake again! edit: i have similar problem "gi('magflux(current1): matrix1', 19, 131, 'wb')" i'd "magflux_wb" output what work this: op=textscan((parameters{a,1}),'%s','whitespace','','delimiter',' ''(),','multipledelimsasone',true); par{a,1} = op{2}; titles{1,a} = par{a,1}; as why original

Linkedin Groups not getting in android -

am trying groups in linkedin, using call http://api.linkedin.com/v1/people/~/group-memberships?count=10&start=10&format=json when try call url getting error message "access group-memberships denied". here code: string message=""; token requesttoken; service = new servicebuilder() .provider(linkedinapi.class) .apikey("xxxxxxxxxx") .apisecret("xxxxxxxxxx") .build(); requesttoken = service.getrequesttoken(); string url = "http://api.linkedin.com/v1/people/~/group-memberships?count=10& start=10&format=json"; oauthrequest request = new oauthrequest(verb.get, url); request.addheader("content-type", "application/json"); service.signrequest(linkrdintoken, request); response response = request.send();

Can't retrieve custom title of OSX terminal tabs -

i'm trying select terminal tab in osx , send keystrokes it. terminal in osx 10.8.4 doesn't seem store "terminal" tab's custom title, if set custom title inspector. ideas? here code i'd use select right tab: tell application "terminal" set allwindows number of windows repeat 1 allwindows set alltabs number of tabs of window repeat j 1 alltabs if custom title of tab j of window contains "blah" set frontmost of window true set selected of tab j of window true end if end repeat end repeat end tell i'm working on older version of osx, couldn't duplicate problem (your code works fine me), perhaps try: if ((custom title of (current settings of (tab j of (window i)))) string) contains "blah"

osx - Applescript (10.6.8). how to start app from user input -

i developing automated test several mac osx apps applescript. app should following. 1.) display dialog shows up, user can type in 1 or more app names want tested example (1.test.app, 2.autotest.app,....) 2.)depending on how many apps names has typed in, apps should start , close consecutively check if working. so example if user type in apptest1.app, apptest2.app, apptest3.app -> first app starting should apptest1.app , close it, next app should apptest2.app start , close , on. thank much. lg, san this should trick tell application "finder" set thepath path applications folder set theapps name of every file of thepath set apps_to_test choose list (theapps) multiple selections allowed end tell repeat the_app in apps_to_test tell application the_app activate quit saving no end tell end repeat

multithreading - NSURLConnection in background Thread -

i want load (big) asynchronously in background thread (use nsoperation). after many searches came across 2 options: first use with: cfrunlooprun() which explain wonderful in link : http://www.russellj.co.uk/blog/2011/07/09/nsurlconnection-in-a-background-thread/ the second use with: nsport* port = [nsport port]; nsrunloop* rl = [nsrunloop currentrunloop]; // runloop rl addport:port formode:nsdefaultrunloopmode]; which explain in link : http://www.cocoaintheshell.com/2011/04/nsurlconnection-synchronous-asynchronous/ i realy want use first option because elegant , readability. i'm afraid not understand differences between 2 approaches. thanks help. i'd recommend following built-in method if suits needs. it's easy use , reliable. (void)sendasynchronousrequest:(nsurlrequest *)request queue:(nsoperationqueue )queue completionhandler:(void (^)(nsurlresponse , nsdata*, nserror*))handler

Time spent on HierarchicalRequirement in Rally Rest API -

i have report hooks rally api web service. lists user stories , defects presentation external client. developers filling in time spend on tasks in time sheet, when try actual time spent using 'taskactualtotal' value, come 0. the values definately recorded internal reports on timesheet produce these values. do have call time spent using different method? thanks do developers enter time in time tracker module? there no connection between actuals , time tracker module. actuals predates time tracker. the actuals field designed used during retrospectives provide insight on root causes missed commitments, while time tracker module designed report on development costs. we recommend using actuals values teams new scrum or agile still working on providing estimates. comparing estimates actuals can valuable during retrospectives identify larger gaps in estimating might occurring. for more established teams, recommend actuals field remain hidden these values can s

javascript - The new Operator -

is possible write javascript function follows (valid) typescript interface: interface foo{ // constructor: new (): string; } i.e. when called new operator returns string. e.g. following not work. function foo(){ return "something"; } var x = new foo(); // x foo (and not string) whether or not :) you should able do: function foo(){ return new string("something"); } var x = new foo(); console.log(x); you can return object, literals don't work. see here: what values can constructor return avoid returning this?

javascript - Is incluing many .js files via one php file a good practice? -

i'm working on big project, organization purpuses links many .js files, jquery plugins base javascript code. every link .js file in index.php generates new request server. practice have 1 link php file fopens .js files , echoes content? will explain better example, this: <script src="/js/scripts.php"></script> instead of this: <script src="/js/1.js"></script> <script src="/js/2.js"></script> ... <script src="/js/n.js"></script> in development should separate file cause sake of debugging , organizing. in production, files should minified 1 , pushed cdn :)

performance - Javascript variables and memory leaking? -

is possible create memory leaks when coding in javascript? , if dependent on javascript rendering engine e.g. v8 or ie's chakra i seem getting slow performance when iterating through large loop constructs. should "delete" variables im not using? var myvar = 'very long string'; delete myvar; in example you've shown, unless myvar in global scope garbage collected @ end of function. in general, don't need worry memory in javascript. need worry memory when unintentionally create references objects , forget them. example: function buttonclick() { var clicked = false; document.body.addeventlistener('click', function(event) { if (clicked) return; if (event.target.nodename !== 'button') return; clicked = foo(); }, true); } the above code bad code begin (not cleaning event listeners), illustrates example of "memory leak" in javascript. when buttonclick() called, binds function

core data - Relationship between logged in Users stackmob -

i use stackmob backend , coredata. i have "user" , "sport" objects (user <<-> sport). users must have sport object require. if user logged in, others can't use sport object until users logged out. example, want change sport. when change have crash. because, sport have reverse relation users. seems can't use same object between users. how possible? , how resolve situation? crashed here(smincrementalstore.m): - (id)newvalueforrelationship:(nsrelationshipdescription *)relationship forobjectwithid:(nsmanagedobjectid *)objectid withcontext:(nsmanagedobjectcontext *)context error:(nserror *__autoreleasing *)error with crashlog: * ** terminating app due uncaught exception 'smexceptionincompatibleobject', reason: 'no attribute found entity user maps primary key on stackmob. attribute name should match 1 of following formats: lowercasedentitynameid or lowercasedentityname_id.