Posts

Showing posts from March, 2013

Possible to change an image color palette using javascript? -

i've seen questions here none of them provide answer. what need javascript (or perhaps kind of plugin using php/apache) can find colors in image , replace them closest color custom palette, in case nes palette . how can done? yes, can done using javascript, following these steps : load image canvas get imagedata (which array of rgba values each pixel) loop through array , convert rgba values hex values convert resulting color nearest color in pallette convert new colors rgba values restore new imagedata array canvas

c++ cli - Why can't i see some C++ DLL ( support CLR ) in C# project ? -

i wrote simple c++ dll ( win32 ) , change properties 'common language runtime support (/clr)' - i created new simple winform project ( c# 4.0 ) , created reference c++ project ( c++ dll ). now can't see c++ dll in c# project - cant use , dont know why. if have, example, unmanaged function: bool foofunction(int firstparameter, int secondparameter); if want make visible managed code have wrap (as first, simple, step) managed class: public ref class myclass abstract sealed { public: static bool foo(int firstparameter, int secondparameter) { return foofunction(firstparameter, secondparameter); } }; this simple exam, if have interop complex type may need wrap them all. example if have interop function accepts string have manage this. use class this: ref class unmanagedstring sealed { public: unmanagedstring(string^ content) : _content(content) { _unicodeptr = _ansiptr = intptr::zero; } ~unmanagedstring() ...

c# - WCF / Entity framework update -

i building n-tier application have wcf service (not data / ria services) hosted on web project on iis server, , windows phone client service reference pointing on wcf service. my wcf service access database through entity framework. here problem : when update database anywhere client, update cannot seen in clients. when update database specific client, modifications can seen him. but after while, clients have access updated data. i believe can caused iis caching of wcf's datas, or caching @ linq level, problem remains after disabling iis caching. any idea on how fix this? thanks so turn in formal anwer: the framework attempt cache values (not iis). so, ensure not extending unit of work beyond scope of transaction (i.e. using both same , retrieve method(s)). also, try re-establishing context between store/retrieve calls should remove existing caching may occurring within framework. i.e. [operationcontract] public void save(myobject entity) { using (my...

dns - JBOSS 7 start domain as a service using Java Service Wrapper -

has managed run jboss 7 domain setup service using java service wrapper? appreciated yes, please try this: #encoding=utf-8 set.jboss_home=e:\jboss-as-7.1.0.final (<---insert jboss-home path here, if it's not globally defined) set.java_home=c:\program files\java\jdk1.6.0_26 (<---insert java-home path here, if it's not globally defined) # specify specific java binary: wrapper.java.command=%java_home%/bin/java wrapper.java.mainclass=org.tanukisoftware.wrapper.wrappersimpleapp #classpath (all classes dynamically loaded, except wrapper's library , jboss' initialization class no other libraries needed. wrapper.java.classpath.1=%jboss_home%/jboss-modules.jar wrapper.java.classpath.2=%jboss_home%/lib/wrapper.jar # java library path (location of wrapper.dll or libwrapper.so) wrapper.java.library.path.1=%jboss_home%/lib # java bits. on applicable platforms, tells jvm run in 32 or 64-bit mode. wrapper.java.additional.auto_bits=true # java addi...

json - PHP json_encode errors messages for JQuery -

i have following method in php class processes messages , sends jquery. works fine if there single message send if there more one, sends them separate json objects. messages sent ok jquery gives me error. messages this: {"error":true,"msg":"message 1 here..."}{"error":true,"msg":"message 2 here"} my php method looks this: private function responsemessage($bool, $msg) { $return['error'] = $bool; $return['msg'] = $msg; if (isset($_post['plajax']) && $_post['plajax'] == true) { echo json_encode($return); } ... } i don't know how change multiple error messages put single json encoded message work if single message. can help? thanks looks need appending onto array , when messages have been added, output json. currently, function outputs json time called: // array property hold messages private $messages = array(); // call $this->ad...

Scale parts of the image in ImageView android -

i need scale part of imageview (say x y), rather whole image. setscaletype() function happens work whole image rather on specific parts. please let me know if there way in android. thanks in advance. you can achieve 2 ways. create separate part of image(photoshop) create new bitmap(rect) , draw on new canvas , play it. i prefer go 2 option.

python - search times of "x in []" vs "x in {}" -

i ran problem have go through proxy logs see if users have visited list of sites. i wrote small script read proxy logs, matching visited host against list: for proxyfile in proxyfiles: line in proxyfile.readlines(): if line[4] in hosts_list: print line the hosts_file large, talking ~10000 hosts, , noticed searching took longer expected. i wrote small test: import random, time test_list = [x x in range(10000)] test_dict = dict(zip(test_list, [true x in range(10000)])) def test(test_obj): s_time = time.time() in range(10000): random.randint(0,10000) in test_obj d_time = time.time() - s_time return d_time print "list:", test(test_list) print "dict:",test(test_dict) the result following: list: 5.58524107933 dict: 0.195574045181 so, question. possible perform search in more convenient way? creating dictionary of list seems hack, want search key , not value contains. "as want search key , not value contains...

.net - RabbitMQ Pub/Sub: Closing the last consumer closes the publisher's channel/model. Why? -

i'm using .net rabbitmq pub/sub (publisher/subscriber) code. works fine until start closing consumers. consumers handle published data until close last consumer. after consumers, open new consumer, nothing happens. application opens, doesn't receive data publisher. i checked publisher code , found out when last consumer closes, channel's isopen property becomes false. don't know if there setting keep channel open after consumer closed. here publisher code: edit pasted wrong code. and here consumer code: public myconsumer { private readonly connectionfactory _factory; private readonly iconnection _connection; private readonly imodel _channel; private readonly timer _timer; private subscriptionconsumertype(string ipaddress, string exchangename, timespan tspullcycle) { //set connection this._factory = new connectionfactory(); this._factory.hostname = ipaddress; this._connection = this._factory.createconnection(); this._channel = this...

How to set up twitter open source mysql file after getting it from Github? -

another noob question. downloaded open source mysql file link: https://github.com/twitter/mysql . after that, have no clue how set up. have wamp installed in pc. i'm trying study twitter mysql tables file. please help, thanks. that doesn't contain tables used twitter; contains modified version of mysql server used twitter. if want use it, need build source. however, readme states, should not use it.

c# - Supply ObjectDataSource with custom list/collection to load -

i know experience linqdatasource has selecting event can supply our own data assigning r.result i'm looking same behavior objectdatasource. although implemented getalldata() method within custom class: systemsettinglist : list<systemsetting> now, maybe i'm not thinking here getalldata method within systemsettinglist class have instantiate on page later down line in page load. how tell objectdatasource fetch that object? you need use selectmethod , typename . this: <asp:objectdatasource id="objectdatasource1" runat="server" selectmethod="getalldata" typename="yournamespace.systemsettinglist" />

asp.net - How do I use an existing browser window from an email link? -

i'm trying develop signup/verify email process. user will signup web-page called /signup.aspx , enter email address (this page tells them check email. they receive "verify email address" email they click on link in email send them /verified.aspx this works, user ends 2 browsers open. ideally when user clicks on email link, i'd verified.aspx page opened in same window signup.aspx in. i've tried using still opens in different windows you can't. there no way reference specific window "page" delivered via email. the time specific window can referenced when window opened same site link targeting it.

virtual machine - Using a VPS with 64MB Ram to run a process that takes maximum 600+ MB of Ram -

i'm new cloud computing , vm thing. have vps 768mb ram (1gb burstable), when check dashboard processing, see average usage 178mb , maximum 618mb. what happen if run same script on vps, vps has 64mb. kill process? or use virtual memory disk space? the script in php, , crawling web pages , saves text. it may kill process , set off alarms, or go swap (which slow entire system down , noticeable anyways); it's hard say, depends on host's configuration. if host though, , ended using ram on vps that's supposed have just 64mb, you'd have account terminated entirely.

php - More efficient way of inserting using PDO? -

hi inserting image data database each time image uploaded server. code using looks bit 'chunky' binds. can done differently reduce amount of text , execute more or should not worry it? here code using: function($file_name, $cat, $year, $desc, $title, $image_size, $image_width, $image_height){ //test connection try { //connect database $dbh = new pdo("mysql:host=localhost;dbname=mjbox","root", "usbw"); //if there error catch here } catch( pdoexception $e ) { //display error echo $e->getmessage(); } $stmt = $dbh->prepare("insert mjbox_images(img_file_name,img_cat, img_year,img_desc,img_title,img_size,img_width,img_height) values(?,?,?,?,?,?,?,?)"); $stmt->bindparam(1,$file_name); $stmt->bindparam(2,$cat); $stmt->bindparam(3,$year); $stmt->bindparam(4,$desc); $stmt->bindparam(5,$title); $...

mysql statement not working -

i'm trying create secure session management each user gets hash , if user logs in somewhere else checks user has logged in hash. way if user forget's log out, system log out account them. sql statement wrote , it's giving me error. can tell me why? thank you "select * 'v_pos_user_session userid='$userid' , hash='$hash' , admin='0' time=(select max(time) v_pos_user_session userid='$userid' , admin='0')" qlstate[42000]: syntax error or access violation: 1064 have error in sql syntax; check manual corresponds mysql server version right syntax use near 'time=(select max(time) v_pos_user_session userid='6' , admin='0')' @ line 1 you have escape time backticks , forgot and select * v_pos_user_session userid='$userid' , hash='$hash' , admin='0' , `time`=(select max(time) v_pos_user_session userid='$userid' , admin='0') and le...

ImageMagick/PHP Resizing Issue: Image Wont Resize, but ImageMagick is installed -

i having odd issue imagemagick. in same script, have following code: $ct = system("convert -version"); echo $ct; and displays following response: version: imagemagick 6.6.0-4 2012-04-26 q16 http://www.imagemagick.org copyright: copyright (c) 1999-2010 imagemagick studio llc features: openmp however, when attempt this: $ct2 = system("convert -resize 800x600 test-image.jpg test-image2.jpg", $retval); echo $retval; it returns 1, image not resized. shouldn't second image created, resized, under file name "test-image2.jpg"? checked directory permissions, , they're set 0777, shouldn't issue. idea going on here? a return code of 1 considered error. 0 means "no error occurred". i think because have arguments in wrong order. imagemagick wants input file, bunch of operations , output file. try switch order on arguments: convert test-image.jpg -resize 800x600 test-image2.jpg a idea check out imagick ...

jQuery mobile fixed toolbar workaround for BlackBerry? -

Image
i'm building webworks application using jquery mobile. i want use jquery mobile fixed toolbar doesn't seem supported in bb7. does know of work around similar toolbar behaviour in bb7? edit: this application fixed header + footer in android, works on models i've tested. this how works on 9860 on bb 7.1. can confirm same problem happens on following devices bb7.1(9860, 9810, 9320), bb6(9700). i've tested far. though attribute work on bb7.1(9930) & bb7(9930) @jasondscott points out. i've found work on bb7(9360-att). try - $(document).bind("pagecreate", function() { $.support.cors = true; $.mobile.allowcrossdomainpages = true; $("[data-role=header]").fixedtoolbar({ taptoggle: true }); $("[data-role=footer]").fixedtoolbar({ taptoggle: true }); $("[data-position='fixed']").fixedtoolbar('show'); });

internet explorer 8 - CSS Sprites work in FF12 but not IE8 -

this html-code... <a href="link" class="testclass"></a> ...works ccs-code... a.testclass { background: transparent url(sprite.png) no-repeat -125px -671px; display: block; width: 378px; height: 150px; } ...in firefox 12 not in internet explorer 8. the code inspired question regarding anchors, sprites , css . i've found similar questions , since code placed within rather complex drupal installation, still hope there's easier way fix issue going through code find "absolutely positioned outer div , menu styles", had been responsible issue in 2 . thanks help. edit-1: this firebug html-log: <div id="banner-area"> <div id="banner-left"> <div class="region region-banner-left"> <div> <a href="link"> <img width="378" height="150" alt="alttext" src="image.gif"...

Python for loop with a more intuitive upper bound? -

sometimes little confusing me keep in mind upperbound for loop excluded default. there way make inclusive? yes, for in range(upper + 1) or if like, for in range(lower, upper + 1) work, a lot of programming languages use zero-based indexing, non-inclusive upper bound common practice (this due memory addressing , adding offset) just example: if had array of size 5, ar , starting index 0 , your largest valid index value 4 (i.e., 0, 1, 2, 3, 4), loop construct refer size of array (5) so: for in range(5): or more common , better: for in range(len(ar)): .. ensuring legal index values 0 .. 4.

android - Pre made functional camera available? -

i creating android application need capture images front camera function far not main purpose of application. i wondering if there pre made custom views manage , make use of android camera object take picture wraps basic camera functions (zoom, focus etc. including interface) within , returns me final image when user has captured photo. such thing exist? i know seems lazy benefit me focus on unique parts of application instead. thanks in advance you can use intent task :: intent intent = new intent(android.provider.mediastore.action_image_capture); startactivityforresult(intent, camerarequestcode); and inside onactivityresult :: protected void onactivityresult(int requestcode, int resultcode, intent data) { if ( (resultcode == activity.result_ok) && (requestcode == camerarequestcode)) { bitmap mypicture = (bitmap) data.getextras().get("data"); imageview.setimagebitmap( mypicture ); } }

google chrome - watching the html source after manipulation -

i have changed html source using jquery - added lot of textfields. when view page source using chrome still see original source. there way view modified html ? use firebug plugin of firefox , right click > select all, right click again "show selected source". or can right click on changed element of page > "inspect element"

javascript - Backbone Collection.reset() doesn't work on extended Collections -

i have backbone collection jquery -> class app.collections.list extends backbone.collection model: app.models.listitem i trying initialize collection on page load: var list = new app.collections.list; list.reset(<%= @data.to_json.html_safe %>) this throws js error in backbone lib. uncaught typeerror: undefined not function application.js:597 f.extend._preparemodel application.js:597 f.extend.add application.js:591 f.extend.reset application.js:595 (anonymous function) however, if change code to: var list = new backbone.collections; list.reset(<%= @data.to_json.html_safe %>) the reset works, , collection populated -- thought objects in collection don't appear know should listitem objects. have special reset of custom collection? the _preparemodel stacktrace line gives hint have model declared after collection. you have code set this: class app.collections.list extends backbone.collection model: app.models.listitem clas...

Bootstrap like - HTML documentation -

i've tried searching forum, not find answers question i'm asking here. do know tool make twitter bootstrap documentation? i know many uses md format documenting code, need not code displayed how looks in browser. in example if write down <input class="custom-input"/> shows input field on right side, in bootstraps documentation. thank you i believe use kss style guides http://warpspire.com/kss/styleguides/ ruby interface.

How to Use two different users in bash scripting -

hi everyone, writing bash script on redhat v5.1. in script have run 1 command using dbadmin , right after have switch again root user run other commands. can tell me how can in bash scripting. thanks in advance.... you need run script root.then in part of code this: su - dbadmin -c "command" replace command whatever want run under dbadmin user. this exact way how redhat init scripts run services under specific users, eg. oracle db

node.js - Run code in a Proxy context -

i'm experimenting harmony proxies , i'd run code in proxy context, means global object of code proxy. example, if call function foo() in code, managed proxy get() method. but using proxy.create() , vm.runinnewcontext() doesn't work, seems proxy object overwritten new context object , looses properties. var vm = require('vm'); var proxy = proxy.create({ get: function(a, name){ return function(){ console.log(arguments); } } }); vm.runinnewcontext("foo('bar')", proxy); // referenceerror: foo not defined is there way achieve i'm trying do? // edit (function() { eval("this.foo('bar')"); }).call(proxy); the above code works well, i'd able not use this statement, , directly refer global context. this possible in 2 ways. in node, able modified contextify. contextify module allows turning arbitrary objects global contexts run similar vm module. creating global obje...

C# generics: using class generic in where clause of method generic -

can explain why isn't possible (at least in .net 2.0): public class a<t> { public void method<u>() u : t { ... } } ... a<k> obj = new a<k>(); obj.method<j>(); with k being superclass of j edit i've tried simplify problem in order make question more legible, i've overdo that. sorry! my problem little more specific guess. code (based on this ): public class container<t> { private static class pertype<u> u : t { public static u item; } public u get<u>() u : t { return pertype<u>.item; } public void set<u>(u newitem) u : t { pertype<u>.item = newitem; } } and i'm getting error: container.cs(13,24): error cs0305: using generic type container<t>.pertype<u>' requires 2' type argument(s) actually possible. code compiles , runs fine: public class a<t> { public void ...

php - how to select items that concatenation of two rows is like input -

i have mysql table, users: (id, first_name, last_name, ....) i'd pseudo query select * users first_name.' '.last_name = 'john doe' limit 10") i want cause have lots of trouble spliting string (then don't know in order user typing' this current, not working good $phrase = explode(' ',$term); $last_name = ''; if($phrase[1] != '') $last_name= " or last_name '%".$phrase[1]."%'"; $qstring = "select usuarios.first_name,usuarios.last_name, usuarios.id id usuarios first_name '%".$phrase[0]."%' or last_name '%".$phrase[0]."%' $last_name limit 5"; any suggestion achieve (by concatenating @ query or spliting @ php) apreciated you can concatenate in mysql query using concat : select * users concat(first_name,' ',last_name) = 'john doe' limit 10 in code become: select * usuari...

PHP code working beyond PHP tags (<?php ... ?>) -

i've been reading book on zend framework , there's html/php code section can't figure out. it's contained in views part of mvc methodology: <select name="genre"> <?php foreach ($this->genres $genre) { ?> <option value="<?php echo $genre ?>"><?php echo $genre ?></option> <?php } ?> </select> the genre ( $this->genres ) refers array('rock', 'r&b', 'country', 'rap', 'gospel', 'rock n roll', 'techno') . the code runs perfectly, producing drop-down select menu, don't understand how second line legal, let alone work. how php code work beyond enclosing tags? php unusual (templated) language in context. parser considers between ?> , <?php being weird kind of echo. ignored part of program code, although parser run (it outputs , skips part of program code). from php manual : everything outside of pair of openi...

caching - /cache/recovery folder in android -

what cache/recovery folder hold in android filesystem? have single file inside - last_log seems have log infomation last bootup. can explain in detail? /cache contains dex information apps installed on device. information populated @ first boot of android. android uncompresses each app, optimizes launch, , save /cache . should @ least see 1 file per app weird name: /recovery contains files needed boot in recovery mode. recovery mode special boot mode allow (not limited): wipe /data, wipe /cache, install update package some files contain commands recovery tool execute if ask so. example, recovery mode entered when select factory reset on device. when doing so, android writes commands file in /recovery , asks system reboot in recovery mode. when recovery program being executed, reads file , executes commands written. in case (factory reset), erase /data , /cache , reboot. those links might interesting you: what odex files in android? http://www.android...

php - Not able to stop processing form when image file has not been chosen -

i have form use submit new post images in. don't want post proceed submitting data server , database if user has not chosen image upload. @ moment try letting code continue processing form. heres of code: //check if submit button has been clicked if( isset( $_post['submit'] ) ){ //validate title , description $title = validate_title($_post['title']); $desc = validate_desc($_post['desc']); //get other posted variables $cat = $_post['cat']; $year = $_post['year']; if($title && $desc != false){ //check if image has been submitted if( $_files['files']['name'] != ""){... i have tried using following methods, neither stop code when no file has been selected: if( $_files['files']['error'] == upload_err_ok){... if( $_files['files']['name'] != uplo...

ajax - How can I handle different json data for each of the jquery tabs? -

i have 3 three (jquery) tabs: overview pricing destination info each of these tabs have entirely different data. can specify url in href make ajax call. however, how handle data received each of these tabs (so can render them depending on context) ? should use load event manipulate data ? if so, how can handle on returned json data in load event ? i have little experience jquery ui, know can data ajax request json ( here ): $.ajax({ url: "http://example.com/page.html", datatype: "json", }).done(function ( data ) { // stuff data }); or use jquery.getjson . there jquery.parsejson . edit: far can figure out, best you're going get: $(window).load(function(){ $(function() { $( "#tabs" ).tabs({ ajaxoptions: { error: function( xhr, status, index, anchor ) { $( anchor.hash ).html( "couldn't load tab. we'll try fix possible. ...

mysql - Django : DoesNotExist: matching query does not exist -

i'm in process of moving django (v1.1) project mysql postgresql (fun!) , transferring of data. attempted use manage.py dumpdata option, server we're using rather old , take long time (it seems want load memory). came small script process each app , each model under it, simplified version shown below: def dumpjson(model, outfile): try: data = serializers.serialize("json", model.objects.all(),indent=4) except model.doesnotexist: print model.__name__ , "does not exist (not object)" except objectdoesnotexist: print model.__name__ , "issue data, not sure what...." data = serializers.serialize("json", model.objects.all(),indent=4) data = data.decode("unicode_escape").encode("utf8") out = open(outfile, "w") out.write(data) out.close() def main(): app in get_apps(): ...

sending JSON to PHP using jquery ajax -

i'm sending simple compilation of object php script using jquery's .ajax . want extract 1 value each object in php script. javascript is: var obj = [{id:1, name:"val1"}, {id:2, name:"val2"},{id:3, name:"val3"}]; $.ajax({ type: "get", url: "call.php", contenttype: "application/json", data: {type: "stream", q: json.stringify(obj)}, success: function(response){ alert(response); } }); the call.php file written as: if($_get['type']=='stream'){ $obj = json_decode($_get['q']); for($i=0;$obj[$i];$i++){ echo $obj[$i]->{'name'}." "; } } however returns 0, , cannot figure out why. secondly attempted using type:"post" in javascript, , $_post in php, failed altogether. data: {type: "stream", q: json.st...

objective c - UITableView populating only after keyboard is called -

i complete ios beginner. i have uitableview , uitextview subview of uiscrollview . when .xib loaded, nothing appears uitableview should be. only after clicking in edit uitextview , , calling keyboard. uitableview appear populated. i have tried calling [self.tableview reloaddata]; no avail. i know vague question, i'm hoping on off chance trivial issue. many thanks. set tableview.datasource = self; in viewdidload. if doesn't solve issue, check if datasource returning 0 rows in numberofrowsinsection method. it'd if can post code.

android - MediaPlayer prepare fail IOException -

my question having many mediaplayers cause ioexception preparefailed: status= 0x1 log? the way program running use separate instance of media player each video want play. @ end of run stop videoplayer, release it, , turn null; ok other times when move between video's fast io exception , video not play. have mediaplayer playing background music in service. basically video activity gets new call each time file ends playback. error , should try reuse same media player different file? thanks in advance i found own answer. don't know if way but: if(videofile != null) { log.i("initplayer", videofile); afd = getassets().openfd(videofile); instructionvideoplayer = new mediaplayer(); instructionvideoplayer.setdatasource(afd.getfiledescriptor(), afd.getstartoffset(), afd.getdeclaredlength()); instructionvideoplayer.setdisplay(holder); instructionvideoplayer.prepare(); ...

perl - "Uninitialized value" false positive -

i think perl (5.8.8 on centos kernel 2.6.18-308.8.1.el5) giving me false positive 'uninitialized variable' warning. of searching turns legitimate uninitialized value problems. perhaps mine too, , if that's case explanation of what's going on (and how correctly i'm trying do) awesome. i've looked @ many references hex() , correct function argument idioms, , think i'm doing of correctly. my script reads 2 text files: 1 contains 32bit hardware address , other contains 32bit data read address. values in each file 8 hex digits long , both files 100% matched (line 1 in address file corresponds line 1 in data file). when data value non-zero fine, when data value 0 warning: use of uninitialized value in string eq @ ../vmetro_parser.pl line 248. use of uninitialized value in hex @ ../vmetro_parser.pl line 250. relevant code: sub ppreg_tx_mode_reg { my( $data ) = @_; # first arg should data field $ret = "\t"; if( $data eq "000000...

gnuplot tics disappear when using 'with image' -

i have simple script: set term postscript portrait color set output 'output.ps' plot 'data_file' using 1:2:3 image, 'data_file2' using 1:2 lines the problem with image command makes tics disappear in both axis , can't make gnuplot show them unless remove command, can't since i'm plotting cbrange (the third column range) thanks. pm3d not same "plot ... image", workaround maybe not best solution. seems, gnuplot sets tics automatically background, when use "with image" option, so set tics front should solve problem (at least did in case).

c# - Reuse the Same Variable For Multiple TryParse() Calls -

i did reading on this, , questions similar mine, looks ask might not (easily) possible... wanted verify anyway. maybe questions older version of c#/.net, , thing has been implemented recently. anyway. have switch-case statement in 1 of classes, purpose take int ( typeid ) , string ( value ) , check whether value can parsed data type indicated typeid . example, here part of have now: case 1: char charret; return char.tryparse(value, out charret); case 2: regex re = new regex(constants.regex_alphanumeric); return re.ismatch(value); case 3: bool boolret; return bool.tryparse(value, out boolret); //and on... what able avoid char / bool instantiation see in cases 1 & 3. ideally, have return statement. it's not big deal (obviously), nice if make more (even more) compact. that's inherently impossible. variables passed out parameters must match parameter type.

Change player in javascript game -

game: onclick startbutton > mathrandom first player starts game. 4 pictures: 2 of > player1 , player2. 2> player turn. need help: on button click > next player turn function game(){ var playerturn; playerturn=parseint(math.random()*2); if(playerturn==0){playerturn=1;window.document.player1.src="cache/player3.png";} else{playerturn=0;window.document.player2.src="cache/player4.png";} } any appreciated. function game(){ var playerturn; if (math.random()>0.5){ playerturn=1; window.document.player1.src="cache/player3.png"; } else { playerturn=0; window.document.player2.src="cache/player4.png"; } }

java - Mocking contains() with a String[][] -

i have 2 sql tables. after grabbing both tables in resultsets , i've stored them in string[][]s , ordered common id column. these tables should contain same data, 1 may have duplicates of same row other. in order check if every string[] in table present @ least once in table b, need construct efficient contains() -esque method string[] . this have far, stumped (also not sure if there's more efficient solution). give source table , target table. takes each string[] in source table , (should) go through each string[] in target table , find instance of source string[] somewhere in target string[][] checking if there's @ least 1 string[] matches original string[] , element element. can point me in right direction and/or fill in blanks? isn't homework or assignment, i'm refactoring code , having major brain fart. thanks! public boolean targetcontainssource(string[][] s, string[][] t) { boolean result = true; //for each string[] in string[][] s...

f# - FizzBuzz with Active Patterns -

i'm trying understand active patterns, i'm playing around fizzbuzz: let (|fizz|_|) = if % 3 = 0 fizz else none let (|buzz|_|) = if % 5 = 0 buzz else none let (|fizzbuzz|_|) = if % 5 = 0 && % 3 = 0 fizzbuzz else none let findmatch = function | fizz -> "fizz" | buzz -> "buzz" | fizzbuzz -> "fizzbuzz" | _ -> "" let fizzbuzz = seq {for in 0 .. 100 -> i} |> seq.map (fun -> i, findmatch i) is right approach, or there better way use active patterns here? shouldn't able make findmatch take int instead of int option? your findmatch function should be: let findmatch = function | fizzbuzz -> "fizzbuzz" (* should first, pad pointed out *) | fizz -> "fizz" | buzz -> "buzz" | _ -> "" you can rewrite last few lines: let fizzbuzz = seq.init 100 (fun -> i, findmatch i) your active patterns fi...

objective c - Unrecognized selector sent to class 0x89e40 -

my app crashing error: +[accountservice createmockaccountdata] unrecognized selector sent class 0x89e40..please advise how can resolve error? i'm new objective c. here's code: @interface accountservice : nsobject + (nsmutablearray *)accounts: createmockaccountdata; @end #import accountservice.h" @implementation accountservice +(nsmutablearray *)accounts: createmockaccountdata{ nsmutablearray * accounts = [[nsmutablearray alloc] init]; useraccount *mockuseraccount1 = [[useraccount alloc] init]; *mockuseraccount1 setname:@"stella"]; [accounts addobject:mockuseraccount1]; useraccount *mockuseraccount2 = [[useraccount alloc] init]; [mockuseraccount2 setname:@"marko"]; [accounts addobject:mockuseraccount2]; [mockuseraccount1 release]; [mockuseraccount2 release]; return accounts; } .... in controller...i'm invoking class method this: nsmutablearray *accounts = [accountservice createmockaccountdata]; n...

qt - And so a QVariant instantiation silently registeres a (previously declared) metatype -

take program (adapted exploratory test-case, noticed custom metatype bahaves if registered, although qregistermetatype had not been called): #include <qmetatype> #include <qvariant> #include <iostream> class c1 { }; q_declare_metatype(c1) int main() { std::cout << qmetatype::type("c1") << std::endl; qvariant v = qvariant::fromvalue<c1>(c1()); std::cout << qmetatype::type("c1") << std::endl; return 0; } this outputs: 0 256 (and further tests show metatype indeed registered -- can construct 'ed (even in places q_declare_metatype(..) not visible), etc) is behaviour well-known? relied on? (probably not, attempting failing test following "official" rule register metatype first got me puzzled, hence question) p.s. of course, 1 can see qregistermetatype called within q_declare_metatype(..) , question still holds (at least to). thanks in advance. q_declare_met...

Perl and MongoDB: Returning find results in a String -

relatively simple question, not 1 i've found exact answer - let's have cpan'd mongodb driver, set db data, , want capture results of find text string manipulate in perl script. use mongodb; use mongodb::database; use mongodb::oid; $conn = mongodb::connection->new; $db = $conn->test; $users = $db->x; $parseable; #ran in mongoshell earlier: db.x.insert({"x":82}) $string = $users->find({"x" => 82}); @objects = $string->all; print "len: ".(@objects.length())."\n"; #returns 1....hmmmm...would imply has entry! print @objects[0]."\n"; print $objects[0]."\n"; print keys(@objects)."\n"; print keys(@objects[0])."\n"; print "@objects[0]"."\n"; these output following on command line, none of them wanted )-=: len: 1 hash(0x2d48584) hash(0x2d48584) 1 2 hash(0x2d48584) what want bson string - want mongoshell returns in string in perl! dream output followin...

Trying to pass value from form that is not a part of rails model -

i trying pass variable, determines whether or not user has clicked on particular checkbox, , variable not part of model. want make on controller update function, can have access variable, , see set to. have seen other stack overflow answers type of problem, , suggested using hidden_field_tag, this: <% hidden_field_tag "blah", params[:test] %> or <% hidden_field_tag :example, "test" %> when trying this, did params.inspect , not find "test" param variable, using both of above options. should trying retrieve hidden field tag in different way? available in update request controller? if not, know way possible? open suggestions, --anthony you either this <%= hidden_field_tag 'test' , 'blah' %> or this <%= hidden_field_tag :whatever_you_want , 'blah', {:name=>'test'} you had name , value reversed in post. important thing make sure form element has name want show in para...

Sharepoint 2010 How to use "File Size" column value in a formula? -

i trying use "file size" (aka "filesizedisplay") in calculated column formula. "file size" existing column (default sp not custom). not available in "insert column" list of library. , sp displays error message states not exist if added formula manually either [file size] or [filesizedisplay]. all want inform user image big. not trying prohibit file size upload or technical that. want calculated column display message. if column value available following work: =if([file size]>50000,"image big","image sized correctly") or =if([filesizedisplay]>50000,"image big","image sized correctly") any 1 know why column not available? cheers you'll want file size first: get file size can display of message in pop or how ever you'd like using system; using system.io; class program { static void main() { // name of file const string filename = "test.txt"...

python - output scipy dendrograms to TreeView files -

i've written python script using pylab , scipy output hierarchical cluster heatmaps , dendrograms expression matrix based on post: plotting results of hierarchical clustering ontop of matrix of data in python now export array , gene (column , row) dendrograms text files such program treeview can view data (e.g., cdt, gtr, atr files). have experience this? thanks

javascript - Why Wont My HTML5/JS App Work On My iPhone? -

how's going guys? recently, given site, i've learned how draw rectangle on html5 canvas @ click of button... that's not problem:) problem this... unfortunately, didn't work @ when tried use on iphone... why:(? here's code: javascript: // "rectangle" button function rect() { var canvas = document.getelementbyid('canvassignature'), ctx = canvas.getcontext('2d'), rect = {}, drag = false; function init() { canvas.addeventlistener('mousedown', mousedown, false); canvas.addeventlistener('mouseup', mouseup, false); canvas.addeventlistener('mousemove', mousemove, false); } function mousedown(e) { rect.startx = e.pagex - this.offsetleft; rect.starty = e.pagey - this.offsettop; drag = true; } function mouseup() { drag = false; } function mousemove(e) { if (drag) { rect.w = (e.pagex - this.offsetleft) - rect.startx; rect.h = (e.pagey - this.offsettop) - rect.starty...

javascript - How to prevent scrolling to the top after unhiding/hiding text? -

there old stackoverflow question on how unhide/hide text using +/- symbols. cheeso posted nice solution sample code . looking for, although original poster didn't agree. :-) i'm using code on web site intended used on mobile devices. problem page jumps top of screen whenever +/- tapped. is there anyway around that? thanks. in click event handler, return false. $('a.selector').click(function() { return false; });

PHP image watermark only displaying image on page -

i testing script watermark image in webpage. the script works fine , image watermark problem image displayed on page. as add script page it's web page converted image i'm watermarking. i think it's because of header("content-type: image/jpeg"); code. i need watermark image on webpage need rest of webpage displayed too. how done? i'm quite confused on how works. the script i'm using here here's code i'm using: <?php $main_img = "porsche_911_996_carrera_4s.jpg"; // main big photo / picture $watermark_img = "watermark.gif"; // use gif or png, jpeg has no tranparency support $padding = 3; // distance border in pixels watermark image $opacity = 100; // image opacity transparent watermark $watermark = imagecreatefromgif($watermark_img); // create watermark $image = imagecreatefromjpeg($main_img); // create main graphic if(!$image || !$watermark) die("error: main image or wat...

vba - VB Form and MS Access SQL Wildcard Search -

my table table1 has 3 fields: fname , lname , phone . using microsoft access 2010 running sql query. rows has empty / null phone values. i have vb form accepts search parameters. user can enter (fname , lname) or (phone) , not both @ same time. when try: select table1.lname, table1.fname, table1.phone table1 table1.lname ('*' & forms!frmsearchmain!lname & '*') , table1.fname ('*' & forms!frmsearchmain!fname & '*') order table1.lname, table1.fname; it gives me list of user matching given ( fname , lname ) parameters. works fine. similarly, when try: select table1.lname, table1.fname, table1.phone table1 table1.phone ('*' & forms!frmsearchmain!phone & '*') order table1.lname, table1.fname; it gives me list of user matching given ( phone ) parameter. works fine too. but, when combine both these queries: select table1.lname, table1.fname, table1.phone table1 table1.phone ('*' & f...

c# - How can I prevent visual studio from poping up when my BackgroundWorker throws an error -

when debugging application see messages time: an exception of type 'xxxx.xxxxx' occurred in xxxxx.exe not handled in user code. the problem have backgroundworkers throw exceptions in dowork, these handled checking runworkercompletedeventargs.error in runworkercompleted event - , works great @ runtime. is there way prevent visual studio showing these "unhandled"? is not correct way return errors dowork ui? i tried making exception extend applicationexception , unticking box next applicationexception in exceptions dialog still shows up. you need catch , handle exceptions inside methods dowork method calls. recommendation catch exception , use reportprogress event report interface smooth handling/notification. don't ever want "swallow" exception, reporting allow gracefully log exception or notify user in less intrusive manner. keep in mind, you'll need to use overload of reportprogress allows use of custom userstate can e...

agile - How do you do Test Driven Development on Mobile Android project? -

tdd requires automated testing, hear others how have applied tdd in android projects? worked/did not work team? how did automate visual testing in particular? can see tdd service layer , model how tdd , activities, visual changes layouts etc? the monkey tool, called ui/application exerciser monkey, can useful in identification of ui bugs , errors. practice run against apk before release of android application. how works the monkey command-line tool can run on emulator instance or on device. sends pseudo-random stream of user events system, acts stress test on application software developing. control have list of options. the options give control on : basic configuration : number of events constraints : restriction on packages event types , frequencies debugging options this generic command run monkey : adb shell monkey [options] //example adb shell monkey -p your.package.name -v 500 for more information see link on officiel android developer website ...

android - Receiver, service, alarmmanager and status bar notification -

i have receiver , service run on device start up, let`s user never turn off device, how should handle this? how schedule status bar notification alarmmanager receiver/service? package it.bloomp.service; import android.app.service; import android.content.intent; import android.os.ibinder; public class eventsnotificationservice extends service { @override public ibinder onbind(intent intent) { return null; } @override public void oncreate() { super.oncreate(); system.out.println("service created."); } @override public void ondestroy() { super.ondestroy(); system.out.println("service destroyed."); } @override public void onstart(intent intent, int startid) { super.oncreate(); system.out.println("service started."); } } ... package it.bloomp.service; import android.content.broadcastreceiver; import android.content.context; import android.c...

updates - Versioning? Future Proofing? Updating? -

so, title pretty expresses confusion. looking recommendations online or in book form learn how use visual studio and/or other software accomodate updates and/or version control of custom programs write work. i assistant, , 1 within our 3 man department, programming experience. have written number of custom programs on years accomplish specific goals existing data. however, limited experience programming (3 years aas degree in focus on programming) , little exposure other programmers advice (basically none said, no 1 in 3 man office knows programming) leaves me these questions. as being realized can produce things in-house benefits many, skills being put more use (and 1 welcome , enjoy it....not knock admins, heart lies in programming). however, issues still lie on how use visual studio create programs, in future need update class here or there, or function within class.... any references books or articles appreciated!

star schema - Dimensional design: not sure about fact vs. dimension for a certain types of data -

i'm having trouble deciding should go in particular dimension , should go in fact table star schema i'm developing. for sake of example, let's project keeping track of houses property management company. dimensions various dates, renter, contract, etc. straightforward. house, no matter data lives, want keep track of current owner, current renter, current rental contract, things neighborhood, address, current rental price, current market value, , forth. note owner, renter , contract dimensions (and neighborhood , address may dimensions, don't care much). a lot of data kept houses used in filtering queries, or row , column headers of cube. of needed ancillary information, looked @ on house house basis, not in aggregate. given data, , need it, have (at least) 3 options: dimhouse: house table dimension, lot of attributes might better in fact table, since used browsing , filtering, need here. snowflaking/outriggers required attributes current renter. facthouse...

c# - Rewrite Recursive algorithm more simply - Euler 15 -

i rewrite functionality of algorithm (which used solve projecteuler problem 15) in non recursive way. yes, realise there many better ways solve actual problem, challenge simplify logic as possible. public class solverecursion { public long combination = 0; public int gridsize; public void calculatecombination(int x = 0, int y = 0) { if (x < gridsize) { calculatecombination(x + 1, y); } if (y < gridsize) { calculatecombination(x, y + 1); } if (x == gridsize && y == gridsize) combination++; } } and tests: [test] public void solverecursion_giventhree_givesanswerof20routes() { solverecursion.gridsize = 3; solverecursion.calculatecombination(); var result = solverecursion.combination; assert.areequal(20, result); } [test] public void solverecursion_givenfour_givesanswerof70routes() { solverecursion.gridsize = 4; solverecursion.c...

mongodb get count without repeating find -

when performing query in mongodb, need obtain total count of matches, along documents limited/paged subset. i can achieve goal 2 queries, not see how 1 query. hoping there mongo feature is, in sense, equivalent sql_calc_found_rows, seems overkill have run query twice. great. thanks! edit: here java code above. dbcursor cursor = collection.find(searchquery).limit(10); system.out.println("total objects = " + cursor.count()); i'm not sure language you're using, can typically call count method on cursor that's result of find query , use same cursor obtain documents themselves.