Posts

Showing posts from February, 2011

VF2 (or other) graph isomorphism implementation in Java -

possible duplicate: vf2 subgraph isomorphism i want implement graph isomorphism algorithm in java face lot of problems due small programming experience (maybe logic well). after research found 3 heuristic algorithms available: ullman, nauty , vf2. vf2 considered fastest , simplest implement told phd student. read paper devoting vf2 unfortunately don't understand how works (in code) , feasibility rules. lot of guys here refer c++ code implementation, unfortunately, link doesn't open. furthermore, 1 user (rich apodaca) suggested @ implementation (mx) of vf2 chemists didn't point out files, big project... please me implement isomorphism algorithm in java (better vf2 because of speed) , point out working code (not whole project, hard me understand structure) in java or c++ (which don't know @ least can try). thank you. try implementation used s-space project. it contains implementation of vf2. https://github.com/fozziethebeat/s-space the vf

javascript - JQuery Detect class changes -

i using plugin added class open .slide-out-div when opened. so trying change css if open detected. what need if $('.slide-out-div **open**') detected $('.otherdiv').css('top','0px'); not sure how put together... there no event of class-added , need track yourself... it can done infinite loop settimeout check if class has changed. function checkforchanges() { if ($('.slide-out-div').hasclass('open')) $('.otherdiv').css('top','0px'); else settimeout(checkforchanges, 500); } you can call function when want, or ondom ready: $(checkforchanges);

javascript - Deselect/Unfocus input field using JQuery -

possible duplicate: jquery unfocus is there way deselect/unfocus input field using jquery? $("input#name").select().focus(); in reverse? .blur(); reference: http://api.jquery.com/blur/ bind event handler "blur" javascript event, or trigger event on element. ...this method shortcut for... .trigger( "blur" ) ... the blur event sent element when loses focus. originally, event applicable form elements, such <input> . in recent browsers, domain of event has been extended include element types. element can lose focus via keyboard commands, such tab key, or mouse clicks elsewhere on page...

svn - Stick with TortoiseSVN 1.6? -

in team still works client tortoisesvn 1.6. tried out 1.7 , find big improvement on windows 7 machine. team members tell me can't upgrade. can't tell me exact reason?! told while ago left company :) is there valid reason stick 1.6? edit beside changed working copy format, benefit of 1.7 higher cost of upgrading of 1.6. the working copy format has changed in 1.7. you'd have upgrade clients use same working copy 1.7 @ once: older clients no longer able access wc once has been upgraded. there may reasons speaking against doing under circumstances (like if [non-tortoise] clients don't have upgraded svn client libraries built in yet). you'd have @ clients being used. i have upgraded several tortoisesvn-only work enviroments on past couple months , have had no problems. (of course, wise check in changes prior upgrading, in case.)

c++ - Why does Debug build fails whereas Release build succeed? -

i went through many topics asking "why release build fail , not debug?", i'm across situation it's reverse. here release build works fine debug mode build breaks. possible reasons or situations can happen? reply appreciated. in advance. one of our friend gave direction towards memory freeing issue.. this same thing i'm facing... when build in release mode build successfully, when try build in debug mode fails/breaks @ point there statement freeing allocated memory.. code like: check if buffer null, , free if it's not null... if(buffer){ free(buffer) } when keep breakpoint on line (inside if loop) , check value in debug mode, appears "bad pointer".(0x000000) but question remains why went inside of if-loop though buffer has value 0x000000 ? i don't know details environment, debug environments take steps trigger bugs (e.g. filling free d memory invalid data), whereas release build not, giving more chances lucky. the prob

function - Implement DFS for a tree in java -

please find tree class definition below. public class tree<t>{ private t head; private list<tree<t>> leafs = new arraylist<>(); private tree<t> parent = null; private map<t, tree<t>> locate = new hashmap<>(); public tree(t head) { this.head = head; locate.put(head, this); } public void addleaf(t root, t leaf) { if (locate.containskey(root)) { locate.get(root).addleaf(leaf); } else { addleaf(root).addleaf(leaf); } } public tree<t> addleaf(t leaf) { tree<t> t = new tree<>(leaf); leafs.add(t); t.parent = this; t.locate = this.locate; locate.put(leaf, t); return t; } } the tree class object created in class , nodes added in straightforward way (using addleaf(node) function). process builds tree alright. able suggest dfs function implementation on constructed tree adhering above class definition? thank you. this i've tried. ye

objective c - A classic design and a trivial issue with UIScrollView -

i feel idiot, because fight something, should straighforward, there hidden sabouteur in xcode somewhere. the ui built in storyboard. i have modal view, contains upper uinavigationbar , uiscrollview...inside scrollview textfields. understand when start edit text in textfield, keyboard pops out. thats ok. tracking moment via notificationcenter. [notificationcenter addobserver:self selector:@selector(keyboarddidshow:) name:uikeyboarddidshownotification object:nil]; i calling selector when happens -(void)keyboarddidshow:(nsnotification *)notification { ... code changing frame } of course, need resize scrollview make room keyboard, attach newly created cgrect "frame" value of scrollview's frame, scrollview not resize according wishes, instead takes size of vieconntroller's view minus statusbar's 44 pixels.. i lost few hours on , drives me nuts. can help? first: why need change frame of scrollview? keyboard appears above anyway. per

php - Loading Server Content on Another Window -

i have onclick event designed launch javascript function getdeadlineinfo function getdeadlineinfo(string) //string holds name of deadline { document.location.href='deadlineinfo.htm'; } it meant open new page "deadlineinfo.htm". need new page display content server have own function for: function contactserver(str) { ...additional code here xmlhttp.open("get","serverscript.php?q="+str,true); xmlhttp.send(); } the problem have no idea how send string variable passed getdeadlineinfo str used sql database. have been googling around , methods i've seen include using along lines of http://www.tek-tips.com/faqs.cfm?fid=5442 , doesn't work me if append format document.location.href="deadlineinfo.htm?name="+string; thanks help! a couple suggestions. encode url parameter using encodeuricomponent -> document.location.href="deadlineinfo.htm?name="+encodeuri

css - Content of one div to overlap content of another -

say have following structure: <div id="top" style="width:960px; height:400px; margin 0 auto; background-color:#f00;"> </div> <div id="bottom" style="width:960px; height:400px; margin 0 auto; background-color:#00f;"> <div id="overlapingdiv"> large content here ... </div> </div> how can make div id "overlapingdiv" come out "bottom" div 20px , overlap "top" 1 share background colors of both "top" , "bottom" divs (20px "top" div , rest "bottom" one)? you can float overlapingdiv , give negative margin, e.g. <div id="top" style="width:960px; height:400px; margin 0 auto; background-color:#f00;"> </div> <div id="bottom" style="width:960px; height:400px; margin 0 auto; background-color:#00f;"> <div id="overlapingdiv" style="float:left; ma

java - Javadoc for JavaFX 2.x works partially in Netbeans -

i've created javafx project in netbeans. compiles fine, code completion works...sort off.. instead of proper argument names, autocompleted functions like: somefunction(arg1,arg2,arg3)... ideas how fix this? during auto-completion netbeans displays proper text descriptions of functions or classes. looks it's bug in netbeans: netbeans bugzilla link

c# - Why would a developer include a parameter in a function that references the class it is used in? -

so have following situation: class child : base, ibase { response onoperationresponse(base base, parameters params) { // code code code } } public class base { protected void onoperationresponse(parameters params); } public interface ibase { response onoperationresponse(base base, parameters params); } i leaving lot out, i've put in parts confusing me. so, base class , ibase interface both contain same function name, want use interface's onoperationresponse call. getting confused, why developer of library added base parameter interface? shouldn't interface realize function suppose refer this ? am missing here? or there further under hood library hiding? shouldn't interface realize function suppose refer this? the parameter of type base being passed in onoperationresponse any instance of type base - why make assumption should same ibase instance being called on? a use case (totally made admittedly) aug

c# - stop unauthorized file download in asp.net -

i have login.aspx page custom textbox username , password i.e. no loginview after supplying correct username , pwd assign sessionid used visit other pages on website. now download file (1234) redierct user ~/download.aspx?fileid=1234 , on page check session id , send user file url i.e. ~/file/1234.pdf . if 1 dirctly enters file url, unable stop him. plase guide me on how this... p.s. : have read authentication rule in web.config file dont know how mark user authenticated ones supplies correct username , password @ login. (i checking username , pwd database , redirecting home page) your authentication strategy weak. should bounding areas of site (namely files directory in instance) roles , assigning users them. however, around more immediate problem, disable outside world getting files directory , when hit ~/download.aspx?fileid=1234 serve them file. can find instructions here: how serve pdf file

vcl - How should I do a date and time range selection in my Delphi application? -

i want user able specify "tuesday , 10am till 11am". can 1 complex control, or better off 3 separate simpler controls, such combo boxes, 1 day , 1 each start/stop times? would better off 3 combo boxes, 1 day , 1 each start/stop times? go whatever solution doesn't require natural language processing. it's less "cool" , might bit obsolete, bet it's easier users because can selection mice , know want. natural language hard, people might miss-spell things, enter impossible data or confusing data. do if enter this: "marţi, de la 22 la 21" (intentionally written in non-english, reversed hours in 24 hour format!). , don't think asking non-native-english speakers write dates in english, it's torture. in other words, unless have google's ability process natural languages in multiple languages, go plain multi-combo-box setup, proper editors each segment: 1 date, 2 times.

iphone - NSUserDefault to NSArray -

icstored value of 2 label in nsuserdefault, trought nsmutablearray. nsuserdefaults *userdefaults = [nsuserdefaults standarduserdefaults]; // add bookmark nsmutabledictionary *bookmark = [nsmutabledictionary new]; [bookmark setvalue:author.text forkey:@"author"]; [bookmark setvalue:book.text forkey:@"book"]; [bookmarks addobject:bookmark]; // save (updated) bookmarks [userdefaults setobject:bookmarks forkey:@"bookmarks"]; [userdefaults synchronize]; now problem how retrieve values of nsuserdefault trought nsarray? nsuserdefaults *prefs = [nsuserdefaults standarduserdefaults]; self.dataarray = [prefs arrayforkey:@"bookmarks"]; nsstring *author = ?? nsstring *book = ?? nsstring * author = [self.dataarray objectforkey: @"author"]; nsstring * book = [self.dataarray objectforkey: @"book"]; this assumes saved array , re-loaded array nsuserdefaults . should error checking in code.

How to handle Server side HTTP file upload from Java client -

i want upload file client server. client: java using http post server: java servlet i have added client side coding here. but, don't have idea server side processing. please me code snippet. private string tag = "uploader"; private string urlstring = "http://192.168.42.140:8080/sampweb"; httpurlconnection conn; string exsistingfilename = "/sdcard/log.txt"; string lineend = "\r\n"; string twohyphens = "--"; string boundary = "*****"; try { // ------------------ client request log.e(tag, "inside second method"); fileinputstream fileinputstream = new fileinputstream(new file( exsistingfilename)); // open url connection servlet url url = new url(urlstring); // open http connection url conn = (httpurlconnection) url.openconnection(); // allow inputs conn.setdoinput(true); // al

gwt - RequestFactory and offline clients -

i'm trying create application able work when network down. idea store data returned requestfactory on localstorage, , use localstorage when network isn't available. problem - i'm not sure how differentiate between server errors(5xx, 4xx, ...) , network errors. (i assume on both cases receiver.onfailure() called, still don't know how identify situation) any appreciated, thanks, gilad. the response code when there no internet connection 0. with requestfactory identify request unsuccessful because of network response code has accessed. requesttransport seems best place. here rough implementation of offlineawarerequesttransport. public class offlineawarerequesttransport extends defaultrequesttransport { private final eventbus eventbus; private boolean online = true; public offlineawarerequesttransport(eventbus eventbus) { this.eventbus = eventbus; } @override public void send(final string payload, final transportreceiver receiv

java - How to count the number of 1's a number will have in binary? -

possible duplicate: best algorithm count number of set bits in 32-bit integer? how count number of 1 's number have in binary? so let's have number 45 , equal 101101 in binary , has 4 1 's in it. what's efficient way write algorithm this? instead of writing algorithm best use built in function. integer.bitcount() what makes efficient jvm can treat intrinsic. i.e. recognise , replace whole thing single machine code instruction on platform supports e.g. intel/amd to demonstrate how effective optimisation is public static void main(string... args) { perftestintrinsic(); perftestacopy(); } private static void perftestintrinsic() { long start = system.nanotime(); long countbits = 0; (int = 0; < integer.max_value; i++) countbits += integer.bitcount(i); long time = system.nanotime() - start; system.out.printf("intrinsic: each bit count took %.1f ns, countbits=%d%n", (double) time / intege

javascript - Different line of text each hour -

i'm trying make site displays different line of text depending on hour (gmt). have tried using javascript, i'm beginner! i've managed piece following bit of code can't seem work. appreciated! function gettime(zone, success) { var url = 'http://json-time.appspot.com/time.json?tz=' + zone, ud = 'json' + (+new date()); window[ud]= function(o){ success && success(new date(o.datetime)); }; document.getelementsbytagname('head')[0].appendchild((function(){ var s = document.createelement('script'); s.type = 'text/javascript'; s.src = url + '&callback=' + ud; return s; })()); } gettime('gmt', function(time){ if (time>10 && time<11) { document.write("<b>paris</b>"); } ; }); javascript has date class. var hour = new date().gethours(); if(...) { // } this code extract i

c# - Call an operation that was dynamically added to the service contract -

i have wcf service contract (say iservice1) dynamically add operation described here . how call dynamically added operation client-side when have iservice1 transparent proxy , iclientchannel created via clientchannelfactory? update i can realproxy transparent proxy returned channelfactory using this method . var realproxy = system.runtime.remoting.remotingservices.getrealproxy( transparentproxy ); would possible call realyproxy.invoke(imessage) fake message trick proxy calling dynamically added method? replace generatepingmethod one: private static void generatenewpingmethod(servicehost sh) { foreach (var endpoint in sh.description.endpoints) { contractdescription contract = endpoint.contract; operationdescription operdescr = new operationdescription("ping", contract); messagedescription inputmsg = new messagedescription(contract.namespace + contract.name + "/ping", messagedirection.input); messaged

Firefox content script memory consumption -

i developing 1 extension firefox using addon-sdk. extension opens 1 tab , load 1 web page updated each n minutes. web page processed using 1 content script. problem memory grows each time content script gets executed. know why? there way call garbage collector in order maintain memory consuption stable? edit: web page contains bank account details , content scripts new movements on in. framed page , 1 of frames (which contains movements list) reloaded see if change occured. use jquery proccess list. when new movements appear, sent extension using port , extension saves them in remote web server using response. trying check instructions mozilla: https://developer.mozilla.org/en/xul_school/javascript_object_management https://developer.mozilla.org/en/zombie_compartments#proactive_checking_of_add-ons depends on using on add-on... if you're using oberserver example, need unregister observer won't leak... can give more descriptions addon? code or does... maybe yo

objective c - How to get an array from NSMutableData -

i have text file 5 strings. need use nsurlconnection contnent of file. nslog shows me, 'dump' empty. how can transform data nsmutabledata nsarray. arrays because need show 5 items in tableview. nsurlrequest *therequest=[nsurlrequest requestwithurl:[nsurl urlwithstring:@"http://dl.dropbox.com/u/25105800/names.txt"] cachepolicy:nsurlrequestuseprotocolcachepolicy timeoutinterval:60.0]; nsurlconnection *theconnection=[[nsurlconnection alloc] initwithrequest:therequest delegate:self]; if (theconnection) { receiveddata = [nsmutabledata data]; nsstring *dump = [[nsstring alloc] initwithdata:receiveddata encoding:nsutf8stringencoding]; nslog(@"data: %@", dump); nsarray *outputarray=[dump componentsseparatedbystring:@"\n"]; self.namesarray = outputarray; thanks in advance. btw url works, can see file. if don't want u

Output parameter issue in sql server and c# -

why if have stored procedure created output parameter, i'm getting following error: sp_dts_insertlsrbatch expects parameter @errormsg not supplied stored procedure code: set ansi_nulls on set quoted_identifier on go alter procedure [dbo].[sp_dts_insertlsrbatch] @lsrnbr varchar(10), @batchnbr varchar(10), @errormsg varchar(20) output begin set nocount on; if not exists(select * tbldts_lsrbatch (nolock) lsrnbr=@lsrnbr , batchnbr=@batchnbr) begin -- check if batchnbr exists under lsr -- if not add (lsr, batchnbr) else error if not exists(select * tbldts_lsrbatch (nolock) batchnbr=@batchnbr) insert tbldts_lsrbatch (lsrnbr,batchnbr) values (@lsrnbr, @batchnbr) else set @errormsg = 'batch dif lsr' end end c# code: sqlconnection conn = new sqlconnection(connstr); try { conn.

java - "Unable to load class" when starting Tomcat 7 web application -

i recieving below error message, whenever deploy application developed in spring mvc: unable load class [com.google.common.collect.computingconcurrenthashmap] check against @handlestypes annotation of 1 or more servletcontentinitializers java.lang.verifyerror: cannot inherit final class @ java.lang.classloader.defineclass1(native method) @ java.lang.classloader.defineclasscond(classloader.java:631) @ java.lang.classloader.defineclass(classloader.java:615) @ java.security.secureclassloader.defineclass(secureclassloader.java:141) @ org.apache.catalina.loader.webappclassloader.findclassinternal(webappclassloader.java:2820) @ org.apache.catalina.loader.webappclassloader.findclass(webappclassloader.java:1150) @ org.apache.catalina.loader.webappclassloader.loadclass(webappclassloader.java:1645) @ org.apache.catalina.loader.webappclassloader.loadclass(webappclassloader.java:1523) @ org.apache.catalina.startup.contextconfig.checkhandlestypes(contextconfig.java:2006) @ org.apache.catalin

php - What part of Zend Framework is cleaning session object when lifetime is over? -

i have application in zend need implement system log users work time database. there id_worktime, id_user, login_time , logout_time. logging in , logging out easy, there problem when user doesn't longer gc_maxlifetime. wrote class extending zend_session_savehandler_dbtable override gc() method: class vao_session extends zend_session_savehandler_dbtable { public function gc($maxlifetime) { $garbage = $this->fetchall($this->select()->from('session')->where('`modified` + `lifetime` < ?', time())); foreach ($garbage $session) { $variables = array(); $a = preg_split("/(\w+)\|/", $session['data'], -1, preg_split_no_empty | preg_split_delim_capture); for($i = 0; $i < count($a); $i = $i + 2){ $variables[$a[$i]] = unserialize($a[$i + 1]); } if (isset($variables['worktime'])) { $worktime = $variables['worktime']; $idwor

c# - AddObject and Save Not Working -

i have dbml have table within mvc environment. db.trucktable.addobject(trucktbl); db.savechanges(); it isn't working can't find addobject() pertaining trucktable . wordering if there way around make table save in dbml file. with linq-to-sql method add objects called insertonsubmit() , saving changes done through submitchanges() . db.trucktable.insertonsubmit(trucktbl); db.submitchanges();

string - c# split and reverse sentence with two languages -

i have sentence (in hebrew,rtl): ואמר here אוראל now, when insert array got: array[0] = אוראל array[1] = was array[2] = here array[3] = :ואמר now, because hebrew rtl language need reverse english letters , need switch positions. notice need take care of sentence (which means can have more 2 english words). how result following? ואמר ereh saw אוראל i thought maybe build time new string english words,reverse , build original string again, or maybe use in ref strings... thanks helping still got problem! had splited sentence said,i reversed array , got this: לארוא ereh saw רמאו after step 2 postions of hebrew words worng! in step 3 reversed hebrew words again , got: אוראל ereh saw ואמר and need switch position(one in one, said can have sentence lot of words..) so, didn't understand how "put array string together"(step 5) paolo did hard work of figuring out algorithm: split sentence array of strings reverse array if

oop - What pattern should I use to convert PHP associative arrays to/from complex Object graphs? -

my data arrives in form of associative arrays. works, code mess of nested arrays , start using proper oo/objects make data easier work with. cannot change way receive data, find clean way convert associative arrays instances of classes below. i have these classes model people in application: class person { /** * @var string */ private $_name; /** * @var array[dog] */ private $_dogs = array(); /** * @var array[hobby] */ private $_hobbies = array(); } class dog { /** * @var string */ private $_color; /** * @var string */ private $_breed; } class hobby { /** * @var string */ private $_description; /** * @var int */ private $_cost; } my data (in json) looks this: 'person': { 'name': 'joe', 'dogs': [ {'breed': 'husky', 'color': 'black'}, {'breed': 'poodle', 'color': 'yellow'} ] 'hobbies

UPDATE in mysql didn't work in my PHP page. -

first of i'm rookie programming, created php page update value mysql(myadmin) database, value not updating. tried retrieve values database it's working fine update code not working! don't know why, please check out code below. $qs=mysql_query("update staff set review=$newrate name=$rateuser"); $resu=mysql_query($qs); all variables double defined, assigned proper values, checked , tested variables using echo, table name checked, it's fine, think problem update query, searched internet syntax it's not different mine. please me out how $newrate , $rateuser set? mysql_query("update staff set review = '".mysql_real_escape_string($newrate)."' name = '".mysql_real_escape_string($rateuser) ."'"); http://php.net/manual/en/function.mysql-real-escape-string.php

mysql - Limit the number of records a table can have -

i created table, master-domain . table should have 3 records. how can limit mysql database allow no more number of records? there specific sql command acomplish this? this current sql: create table `mydatabase`.`master-domain` ( `domain` varchar( 50 ) not null comment 'domain name', primary key ( `domain` ) ) ps. have godaddy , includes phpmyadmin, in addition mysql databases. you can make table's primary key field of type enum . example: create table test ( id enum('1','2') not null, domain varchar(50) not null, primary key (id)); when update have explicitly set id "", "1", or "2".* can't null , there can 1 record each id. domain still stored in domain field, whatever external system querying database won't have problems getting results wants. if want replicate current restriction domain names have unique, add unique key (domain) . * note empty string allowed (and not same null)

Phonegap on Android: AJAX request fails when setting Accept: 'application/xml' on request header -

i making requests assembla rest api. can read here: http://www.assembla.com/spaces/breakoutdocs/wiki/assembla_rest_api the api requires set accept: 'application/xml' on request header receive xml data back. otherwise, html comes in response. my service calls work in ios , in safari, not return in android. my cordova.xml file has <access origin=".*"/> not think whitelist issue. have tried every variation think of here. sample ajax request: $.ajax({ url: 'https://www.assembla.com/spaces/my_spaces', username: usermodel.get('username'), password: usermodel.get('password'), headers: { accept: 'application/xml' }, success: onsuccess, error: onerror }); like said, request not hit either onsuccess or onerror in android. request works fine in ios , in safari. if take out headers property, request hit onsuccess in android return html. have inspected request , response in firebug

iphone - Will my app be rejected if it requires ios5? -

in iphone app, used api new in ios 5. since don't have code check ios version , provide fallback old ios versions, app not going run on ios older 5.0. will app rejected because of this? or can specify app requires ios 5 or later, upon submission app store? you should specify minimum os version in info.plist. set in xcode, click on project, select 'summary' tab , put 5.0 in 'deployment target' field. if upload app deployment target of 4.0, , app crash on 4.0 due attempting use unimplemented api grounds rejection.

c++ - Best way to compare input values to read values from files -

i relatively new c++ programming , have hit 1 of first major snags in of this.. i trying figure out how read value/character generic ".txt" file on notepad. comparison want determine whether or not read entire line, can't seem read single 1 or 2 digit number, got read whole line using { 'buffername'.getline(variable, size) } when try change 'size' specific number gives me comparison error saying invalid switch 'int' or 'char' (depending on how declare variable). any appreciated. thanks int length = 2; char * buffer; ifstream is; is.open ("test.txt", ios::binary ); // allocate memory: buffer = new char [length]; // read 2 char is.read (buffer,length); //compare character , decide delete[] buffer; return 0;

c - full duplex communication between server & client -

i want make code full duplex communication between server & client using code. got error in receive-message thread server side & in send-message thread client side. please me solve errors & suggest me if other changes required. :) server.cpp int newsockfd, n; void error(const char *msg) { perror(msg); exit(1); } void* recvfn( void* data ) { char buffer[256]; while(n==0){ memset( buffer, sizeof(buffer), 0); n = recv(newsockfd,buffer,255,msg_peek); if(n>0){ printf("cliet: "); printf("%s",buffer); } } return null; } void* sendfn( void* data ) { char temp[255], buffer[255]; while(n==0){ memset( buffer, sizeof(buffer), 0); fgets(temp,255,stdin); sprintf(buffer,"clent: %s",temp); n = send(newsockfd,buffer,strlen(buffer),msg_eor); } return null; } int main(int argc, char *argv[]) { int sock

model - Multiple M2M in django -

i have 2 models in django 2d map based game: class block(models.model): type = models.integerfield() class shopbuilding(models.model): house_blocks = models.manytomanyfield(block) street_blocks = models.manytomanyfield(block) river_blocks = models.manytomanyfield(block) decoration_blocks = models.manytomanyfield(block) npc_blocks = models.manytomanyfield(block) now want associate these 2 models using 1 table: class shopblockassoc(models.model): block = models.foreignkey(block) shop = models.foreignkey(shop) after set through field in shopbuilding model, django yiled multiple fails when syncdb, like error: 1 or more models did not validate: tnew.shopbuilding: accessor m2m field 'house_blocks' clashes related m2m field 'block.shopbuilding_set'. add related_name argument definition 'house_blocks'. tnew.shopbuilding: accessor m2m field 'house_blocks' clashes related m2m field 'block.shopbuilding_set'. ad

sql - Oracle : Swapping table names -

i need load table ~18m records in daily basis, , in order minimize down time on client side, have approach of loading temp swap table names after. see process below table orginal table, table tmp temporary table load table tmp rename table table a_v1 rename table tmp table a rename table a_v1 table tmp truncate table tmp in preparation next load is there other way of swapping table names? or other way achieve this? thanks lot. use synonym. firstly load tablea_yyyymmdd , recreate constraints etc. then, create or replace synonym tablea tablea_yyyymmdd lastly, if want to, drop previous tablea_yyyymmdd .

scripting - Scheduling Powershell changes ObjectType -

i've written little script checks differences between 2 text files. $new = get-content $outputfile $old = get-content $outputfileyesterday $result = $null $result = compare-object $old $new $resulthtml = $result.getenumerator() | convertto-html send-mailmessage -smtpserver 10.14.23.4 -from me@mail.com -to $toaddress -subject "difftest" -body "$resulthtml" -bodyashtml when run active powershell prompt, well. however, when try schedule run daily error on run-time (the block above in try catch mails execution errors): method invocation failed because [system.management.automation.pscustomobject] doesn't contain method named 'getenumerator'. how can fix this? the script may run in different user context when scheduled, potentially different set of read/write permissions on filesystem. however, in powershell arrays automatically enumerated when used in expressions, don't need call getenumerator(

ios5 - Different result when processing Audio Interrupt for audio unit -

i have searched related posts here , apple documents, without answers. apple's sample code "auriotouch", have handler this: static void riointerruptionlistener(void *inclientdata, uint32 ininterruption) { printf("session interrupted! --- %s ---", ininterruption == kaudiosessionbegininterruption ? "begin interruption" : "end interruption"); audioobjectimpl *this = (__bridge audioobjectimpl *)inclientdata; if (ininterruption == kaudiosessionendinterruption) { // make sure again active session xthrowiferror(audiosessionsetactive(true), "couldn't set audio session active"); xthrowiferror(audiooutputunitstart(this->riounit), "couldn't start unit"); this->ininterrupt = false; } if (ininterruption == kaudiosessionbegininterruption) { xthrowiferror(audiooutputunitstop(this->riounit), "couldn't stop unit");

c# - fluent nHibernate map YesNo when column is nullable -

i'm using fluent nhibernate map a database flag column "y"/"n" bool property: map(x => x.enabled).column("enabled_flag").customtype("yesno"); the question is, how 1 specify how map null? null mapped true, false, exception? update the default settings seems map null false. that, still wondering how override true? if want change functionality of null case have create own custom type - derive iusertype. i have done similar dates (where 0 date of 01-01-0001 cant save mssql) , guids want insert null instead of guid.empty) creating own user type gives ability override nullsafeset , nullsafeget methods - want (change handling of nulls @ read or write) might able inherit original yesno type a example http://lostechies.com/rayhouston/2008/03/23/mapping-strings-to-booleans-using-nhibernate-s-iusertype/

android - Can We Install an APK From a ContentProvider? -

i working on a library allow apps self-update , being distributed outside of android market. my original plan include code download apk file internal storage, , install there via contentprovider , content:// uri . however, when tried that, installer system dumped "skipping dir: " warning logcat , failed install it. once switched downloading apk external storage , using file:// uri action_view installer intent , worked. the "skipping dir:" message seems logged parsepackage() in packageparser , seems assume working file . suggest cannot use content:// uri values. has used action_view on application/vnd.android.package-archive intent content:// uri ? if so, there specific trick in setting contentprovider made work? thanks! i assume not possible, java api doesn't seem allow it. contentprovider's openfile() returns parcelfiledescriptor , can obtain java.io.filedescriptor . can use filedescriptor open either fileinputstream o

No output from Checkstyle in ANT -

i not using automated build tool. checkstyle 5.5 , ant 1.8. trying have checkstyle run in ant script. ant script executes without error, doesn't seem call checkstyle. no output except ant reports build successful. here ant script: <project name="ccu" xmlns:cs="antlib:com.puppycrawl.tools.checkstyle"> <target name="checkstyle" description="generates report of code convention violations."> <cs:checkstyle config="custom_check.xml"> <fileset dir="src" casesensitive="yes"> <include name="**/*.java"/> </fileset> <!-- <fileset dir="src" includes="**\*.java"/> --> </cs:checkstyle> </target> </project> what missing? it classpath problem. reason needed direct ant classpath class files not jar. final script looks this: <project name="ccu" xmlns:cs="antlib:com.puppycrawl.tools.

spring - Hibernate Lazy Loading HQL -

hibernate + hibernatetemplate + lazy loading + hql we using hibernatetemplate's find method passing hql query. how retrieve child elements have configured lazy loading? thanks. it depends. can elements of collection using join fetch in hql query, or can later call hibernate.initialize(entity.getsomelazycollection())

php - Order of insertion of array values at Amazon DynamoDB -

when adding array @ dynamodb put_item, there way tell preserve order of values of array? example: i'm adding array("2", "1", "4"), , it's added table 1, 2, 4. don't want dynamo mess array :) thanks in advance. no, arrays in dynamodb sets, don't preserve ordering. best alternative concatenate them string (using delimiter) , inserting string i.e. 2#1#4 , split them when read back.

call a javascript function from rails -

i trying populate list of cities , mark them on maps, using ajax updating div element list of cities , each city element trying call addmarker() function supposed add marker on top of google maps. using firebug can see javascript tag function call, addmarker() not being executed what best approach forcibly call javascript function , update dom element ? here how addmarker() looks like: function addmarker(lat,lng,title_new) { new_marker = new google.maps.marker({ position: latlng_new, map: map, title:title }); } here how html.erb file looks <%= post.content %> <script type="javascript"> addmarker( <%= post.lat_long%>, <%= post.title%>); </script> </div> the dom element being updated after document has finished loading. i'm not clear doing, ajax , how addmarker work? sure document has been loaded before f

python - How to update table row with SQLAlchemy? -

i want update row of table. to add used, session.add(unit) #here unit unit object of class unit session.commit() to update tried, session.merge(unit) session.commit() however, in database there other columns, e.g. create_by , created_on , updated_on , not set in unit object, these set null upon merge. you can modify properties of class use represent row , call session.commit() . example: # add new user user = user(name="john", age=20) session.add(user) session.commit() # modify user added user.age = 21 session.commit()

c# - Auto-properties with or without backing field - preference? -

i know when using auto-properties, compiler creates own backing field behind screen. however, in many programs read learn from, see people explicitly write private int _backingfield; public int property { { return _backingfield; } } what difference between above, , below? public int property { get; private set; } i understand obvious use property when have side-effects in getter or setter, that's not case. also, understand have explicitly use backing field in case of structs, can't access members via properties. the difference have been able find way of calling value different inside class defined in. simple preference, or there more calling value through property or directly accessing field? simple conventions? there's not difference between 2 snippets - can't pass property reference, example, that's issue. however, if want field readonly, this: private readonly int _backingfield; public int property { { return _backingfield; } } the

objective c - table view use customized cell file and how ot use segue -

i user master-detail created project. on masterviewcontroller , table cell use mastercell.h , mastercell.m build customized cell, code is: - (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath { static nsstring *cellidentifier = @"cell"; mastercell *cell = (mastercell *)[tableview dequeuereusablecellwithidentifier:cellidentifier]; cell = [[mastercell alloc] initwithframe:cgrectzero]; nsstring *value = [[mycontacts objectatindex:indexpath.row] valueforkey:@"name"]; cell.namecontentlabel.text = [nsstring stringwithformat:@"%@", value]; value = [[mycontacts objectatindex:indexpath.row] valueforkey:@"tele"]; cell.telecontentlabel.text=[nsstring stringwithformat:@"%@", value]; value = [[mycontacts objectatindex:indexpath.row] valueforkey:@"image"]; cell.myimageview.image = [[uiimage alloc] initwithcontentsoffile:value]; cell.access

deployment - Which is the most elegant way to start celeryd in a Django project? -

i'm starting out celery in django project , couldn't wonder: elegant way start start celery's workers project? let me explain reasoning question. currently, recommended way start celery seems python manage.py celeryd in simpler setups , along lines of /etc/init.d/celeryd start in more complex ones. however, in first case, process feels fragile since process wouldn't start automatically, while second require quite bit of project-specific configuration ( virtualenv , settings etc.) latter demonstrates general feeling celery worker tied codebase it's part of , it's tied main project process, since celery worker without create tasks in practially useless (with 1 exception being celerybeat ). problem init.d scripts they'd need advanced logic handling several projects per server (with separate virtual environments, settings, paths etc.) so figured, might quite elegant configuration-wise start celeryd main process, e.g. spawn mod_wsgi withing apache

asp.net - Bind data to grid view using LINQ with out adding DataClasses -

Image
i have seen many articles using linq bind gridview , in using dataclasses . possible bind data grid view using linq out adding dataclasses .. can 1 give me sample code or working example on this i think may missing point, whatever source of data, long it's form of collection, can use linq objects query data. example: public partial class webusercontrol1 : system.web.ui.usercontrol { private readonly list<dataitem> _items; public webusercontrol1() { _items = new list<dataitem> { new dataitem {name = "fred"}, new dataitem {name = "dave"}, new dataitem {name = "john"}, }; } protected void page_load(object sender, eventargs e) { // data , use linq objects var filtereddata = getdata().where(i => i.name.startswith("f")).tolist(); // bind dat

mysql - Server-side functionality depending on whether a user "likes" a Facebook page with PHP/JS SDK's -

i trying execute mysql database query on website depending on whether user has "liked" facebook page. have found few ways this, using php , js sdk's, namely using api /user_id/likes/page_id. when user has liked page, want add value data in database, thought of adding function called each time user visits site, , if it, add value database , have boolean value in there doesn't keep adding value. however, guessed waste of calls server if happened every time, not sure how go setting up, ideas? unless dealing huge volumes of users wouldn't worry because check on 1 row of indexed mysql table should quick (200 milliseconds or less entire request on normal internet connection.). , if data need stored on server, how possibly avoid trip server? unless store data in cookie.

iphone - StackScrollView issue with delegate ID MBProgressHUD -

i've got stack scroll view app (like twitter , facebook apps) using psstackedview it's creates view stack: appdelegate // set root controller stack controller menurootcontroller *menucontroller = [[menurootcontroller alloc] init]; self.stackcontroller = [[psstackedviewcontroller alloc] initwithrootviewcontroller:menucontroller]; self.window.rootviewcontroller = self.stackcontroller; [self.window makekeyandvisible]; root nav controller has uitable, cell touch loads next view // load home stories table psstackedviewcontroller *stackcontroller = xappdelegate.stackcontroller; uiviewcontroller*viewcontroller = nil; while ([stackcontroller.viewcontrollers count]) { //nslog(@"launchstories"); [stackcontroller popviewcontrolleranimated:yes]; } viewcontroller = [[testview alloc] initwithnibname:@"testview" bundle:nil]; ((testview *)viewcontroller).indexnumber = [stackcontroller.viewcontrollers count]; viewcontroller.view.width = roundf(

python - Changing the icon of the produced .exe, py2exe -

ive been googling none of results worked me. here setup file setup( windows = [ { "script": "start.py", "icon_resources": [(1, "myicon.ico")] } ], ) the icon of actual .exe file should "myicon.ico". not happen , default icon. "myicon.ico" 32 x 32. i using windows 7. i've had problem before (though i'm using windows xp). recent snippet of code worked me: from distutils.core import setup setup( options = {'py2exe': {'bundle_files': 1}}, zipfile = none, windows = [{ "script":"myprogram.pyw", "icon_resources": [(1, "myicon.ico")], "dest_base":"myprogram" }], ) this creates 1 .exe file can use distribute (even includes windows libs -- use caution there) my .ico file 64 x 64 , used tool create jpg (something http://www.favicon.cc/ ) phot

unix - Emacs cannot save customizations- init file not fully loaded -

when try check "do not show screen again" box , save @ emacs default start buffer, error: custom-save-all: cannot save customizations, init file not loaded my full output looks like: loading 00debian-vars... no /etc/mailname. reverting default... loading 00debian-vars...done loading /etc/emacs/site-start.d/50dictionaries-common.el (source)... loading debian-ispell... loading /var/cache/dictionaries-common/emacsen-ispell-default.el (source)...done loading debian-ispell...done loading /var/cache/dictionaries-common/emacsen-ispell-dicts.el (source)...done loading /etc/emacs/site-start.d/50dictionaries-common.el (source)...done loading /etc/emacs/site-start.d/50slime.el (source)... loading /usr/share/emacs23/site-lisp/slime/slime-autoloads.elc...done loading /etc/emacs/site-start.d/50slime.el (source)...done loading /home/nathan/elisp/autoloads...done information gnu emacs , gnu system, type c-h c-a. (new file) custom-save-all: cannot save customizations; init file not lo

string - Python merge items from two list -

i have following codes: j in range(4): print md_array[j:j+1] j in range(4): print y_array[j:j+1] j in range(4): print md_array[j:j+1]+y_array[j:j+1] j in range(4): print "%s%s" % (md_array[j:j+1], y_array[j:j+1]) the results are: ['12/1/']['12/2/']['12/3/']['12/34/'] ['2011']['2010']['2009']['2008'] ['12/1/', '2011']['12/2/', '2010']['12/3/', '2009']['12/34/', '2008'] ['12/1/']['2011']['12/2/']['2010']['12/3/']['2009']['12/34/']['2008'] but want output ['12/1/2011']['12/2/2010']['12/3/2009']['12/34/2008'] i tried append failed...so what's wrong codes?? array[start_index:end_index] gives slice, sub-list of list it's applied on. in case, want single item. try following code: fo

How Can I Recover PHP $_SESSION variables from within Objective-C / iOS? -

i have php scripts on server return cookies, html code, etc. interact ios app have been working on. things login, send item, receive item, etc. problem maintaining persistent connection. figured we'd use cookies, , php "start session" allow access $_session variables via cookie. however, i'm not able find of session data returned in cookie, other session id. i thought use session id + key grab elements off php session array calling script within app. app isn't problem much: i need know $_session variables can use them. may sound facetious, need. if start session, like: $_session['username']=$_get['username'] shouldn't able return variable set session using following: $session_id = $_get['session_id']; $key = $_get['key']; function getsessionvalue($session_id, $key) { session_start($session_id); return $_session[$key]; } echo getsessionvalue($session_id, $key); something isn't working...i appreci

Sanitize table/column name in Dynamic SQL in .NET? (Prevent SQL injection attacks) -

i generating dynamic sql , ensure code safe sql injection . for sake of argument here minimal example of how generated: var sql = string.format("insert {0} ({1}) values (@value)", tablename, columnname); in above, tablename , columnname , , whatever bound @value come untrusted source. since placeholders being used @value safe sql injection attacks, , can ignored. (the command executed via sqlcommand.) however, tablename , columnname cannot bound placeholders , therefor vulnerable injection attacks. since "truly dynamic" scenario, there no whitelist of tablename or columnname available. the question thus: is there standard, built-in way check and/or sanitize tablename , columnname ? (sqlconnection, or helper class, etc.) if not, way perform task without using 3rd party library? notes: all sql identifiers, including schema, should accepted: e.g. [schema].[my table].column "safe" table1 . can either sanitize identifiers

c++ - Transitioning between menu screens with QStateMachine -

i considering transitioning between menu screens in game using qstatemachine . however, i'm unsure how kick off code (e.g. show() qwidget ) upon transition between states occurring. can quite plain old signals (see commented out code), figure fancy animation upon switching screens using transitions. here's code: edit: updated per koying's suggestion. applicationwindow.h : #include <qtgui> #include <qstatemachine> #include "mainmenu.h" #include "loadgamemenu.h" class applicationwindow : public qmainwindow { q_object public: applicationwindow(); private slots: void mainmenubuttonclicked(); void loadgamemenubuttonclicked(); private: mainmenu* mainmenu; loadgamemenu* loadgamemenu; qstatemachine statemachine; qstackedwidget* stack; }; applicationwindow.cpp : applicationwindow::applicationwindow() { resize(800, 600); stack = new qstackedwidget(this); mainmenu = new mainmenu(); s