Posts

Showing posts from April, 2012

Jquery like image changing mechanism is not working -

i created program in php , jquery . here jquery code: $(document).ready(function(){ $(".likethis").click(function(event){ event.preventdefault(); var id = $(this).attr("href"); $.ajax({ url: '<?php echo site_url().'users/likevideo/'; ?>'+id, success: function(data) { var d =data.split('~'); if(d[0]==2){ alert('you must login like-dislike video!'); }else if(d[0]==3){ alert('you liked video'); }else if(d[0]==1){ $(".like_ico").html(d[1]); $(".dilike_ico").html(d[2]); $("#like_box").html('<a href="#" class="likeedthis"><img src="<?php echo base_url(); ?>images/like.jpg" /

javascript - HTML & Regex, how to match text inbetween commas with keyword -

let have <b>location: </b> uk, england, london <br> to select line regex im using (location:+.*?<br\/?>) , doing job need return 3 elements between commas in seperate variables. the variables in javascript, so. var location = document.body.outerhtml.match(/(location:+.*?<br\/?>)/gi); //returns entire line location:**is working var country = document.body.outerhtml.match(/(location:[^,]*)/gi); //returns uk, usa etc **is working var state = document.body.outerhtml.match(/(location:???; //needs return 'england' etc var city= document.body.outerhtml.match(/(location:???; //needs return 'london' etc i have got country using (location:[^,]*) returns 'uk' expected, don't know how amend return 'england' , again return 'london'. i've seen examples of how select commas, can't find helps me specify how text after second , third commas, specific keyword of

Magento Variable Category Template -

i have numerous categories within magento store. each of these categories can described 'type a' or 'type b'. want each type of category displayed using different template file. templates dynamic - loading in content other sources given category key being displayed. to end, when creating category, administrator should able set whether category should rendered type or b. best way of going this? the simplest solution have come across far create 2 static blocks 'type block' , 'type b block' , dynamically load template file using following described on this blog post : {{block type="core/template" name="some_unique_name" template="myfolder/my_dynamic_php_content.phtml"}} this static block can assigned category , perform describe. although may work, i'm little uncomfortable surely making static blocks dynamic not intended for. i'd prefer make sure develop initial template in 'proper' way , identifyin

android - Switch Fragments inside a Tab -

how switch fragments inside tab? my application contains 3 fragments, afragment, bfragment, , cfragment. these fragments, in turn, correspond own layout files: afragment contains button, , bfragment , cfragment have textview. there fourth layout file named activity_main. now, have 4 classes, mainactivity, afragment, bfragment , cfragment. classes afragment, bfragment, cfragment typical contain oncreateview on each of them. mainactivity contains this: public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); appcontext = getapplicationcontext(); //actionbar actionbar actionbar = getactionbar(); actionbar.setnavigationmode(actionbar.navigation_mode_tabs); actionbar.tab playertab = actionbar.newtab().settext("fragment a"); actionbar.tab stationstab = actionbar.newtab().settext("fragment b"); fragment playerfragment = new afragment(); fragment

android - query method in SQLiteDatabase -

i want know how use query method have where clause like property. want select columns c_name column keyword. i've tried this, doesn't work: cursor = db.query(table, null, c_name, new string[] {"like '"+keyword+"'"}, null, null, null); look @ docs . say: selection filter declaring rows return, formatted sql clause (excluding itself). passing null return rows given table. so try this: cursor = db.query(table, c_name, new string[] {c_name + " '" + keyword + "'"}, null, null, null); also see answer see examples on how use selectionargs (4th argument above). keyword have go.

Generic extension method with an interface contraint -

i have made generic extension method (i.e asxml) still want constraint interface (ixmlable) on of classes. as have introduced constraint, of methods arguing me. one of methods returing list<interest> , compiler says: the type 'system.collections.generic.list' cannot used type parameter 't' in generic type or method 'mywebapp.entities.extension.asxml(t)'. there no implicit reference conversion 'system.collections.generic.list' 'mywebapp.interfaces.ixmlable'. this class: public class person : ixmlable { public string name { get; set; } public list<interest> interests { get; set; } // interest class implements ixmlable } my extension method looks this: public static class extension { public static string asxml<t>(this t entity) t : ixmlable { return makeitxml(entity); } } this method: return mymethodthatreturnsalistofpersons().asxml(); you need lik

jquery - Move <a> tag to new line if it's content flows out of the first line? -

i'm trying achieve following, move tag new line if content flow 1 line another, can see mean here http://jsfiddle.net/snyzx/ firs example (red) shows situation have , second example (orange) shows desired effect, without <br> tag. can achieved plain html , css, if not jquery solution well. <div id="example1"> hi there text , <a href="#"> link! </a> </div> <div id="example2"> hi there text , <br> <a href="#"> link! </a> </div> css: #example1 { background: red; width: 145px; } #example2 { background: orange; width: 145px; margin-top: 20px; } add: a { white-space: pre; }

Trouble in MySQL querying -

i developing digital mobile loyalty app , have face problem in querying mysql code... i have 4 tables: customer, card, redemption, merchant currently trying want system first check if customer possess loyalty card of merchant when making redemption if yes, can proceed if no, system create card them , proceed the redemption code generated merchant... the problem how should query code so? customer - customer_id - c_email - c_password - c_name card - card_id - chop_amt - customer_id* - merchant_id* merchant - merchant_id - merchant_name redemption - red_id - red_code - card_id* - merchant_id* i tried writing code own now...can some1 please me check? select * customer customer join card card on customer.customer_id = card.customer_id join redemption redemption on card.merchant_id = redemption.merchant_id card.merchant_id = redemption.merchant_id , redemption.red_code = 'a002' i recommend putting unique index on ca

java - How to have jtables values which are strings in alphabetical order using comparator and tablerowsorter? -

the title says clearly. wanted use quicksort algorithm 1 of friends said use comparator don't know how to. you must create comparator: comparator<string> comparator = new comparator<string>() { public int compare(string s1, string s2) { return s1.compareto(s2); } }; with comparator able sort data in alphabetical order. after create sorter , pass comparator , model of jtable. then: sorter.sort(); i think after data sorted.

c# - Why does the BackgroundWorker's ProgressChanged event work without calling RunWorkerAsync? -

i have question regarding backgroundworker . can call progresschanged event without having started thread runworkerasync . i don't understand why works. how can notify original thread if new thread didn't start yet? this seems work regardless, since updates gui without problem, wasn't before implemented backgroundworker . calling reportprogresschanged() raise progresschanged event regardless of thread called from. inside inplementation of reportprogresschanged() mechanism raises event on ui thread if wasn't called ui thread. if reportprogresschanged() is being called ui thread, raises event without needing marshalling.

checking/assigning from object tree in node.js / javascript -

doing following risking exception 'there no bar on undefined' var obj = o.foo.bar the way can think of doing above safely : var obj = (o && o.foo && o.foo.bar ) ? o.foo.bar : null; or putting entire thing in try/catch not option in cases me.. , results in more code if want different thing happen depending on property missing. is there concise way perform assignment safely? ** update ** tweaked @techfoobar's answer function resolve(obj, propertypath) { if (!propertypath) return; var props = propertypath.split('.'); var o = obj; for(var in props) { o = o[props[i]]; if(!o) return false; } return o; } var res = resolve(obj, 'apiresponse.commandresponse'); if (res){ (var in res){ seems it's going get... one way moving function can re-use in multiple scenarios regardless of depth need go: function resolve(_root) { if(arguments.length == 1) return _root; // in case

PHP: If String[Index] is in Array, PHP: String from String[1] to String[last] -

is there php call in_str? …something similar in_array.. am using if-else take each word ( string ) in array of strings (from form - input - text ) see if start index [0] equal single character string in array .. also, how 1 @ string string[1] string[last] ? (these 2 questions highlighted in code using format: **code** ) if(isset($_post['radiobuttonname']) && $_post['radiobuttonname'] == 'avalue') { $stringsarray = array($_post['forminputtext']); $vowels = array("a", "e", "i", "o", "u", "a", "e", "i", "o", "u"); foreach ($stringsarray $stringsarraystring) { if (**in_str**($stringsarraystring[0], $vowels)) { echo $stringsarraystring . "aword" . "<&nbsp;>"; } else { echo "**$stringsarrays

ruby - Why does having a literal space between regex tokens lead to different matchdata objects? -

for example, consider following expressions: no_space = "this test".match(/(\w+)(\w+)/) with_space = "this test".match(/(\w+) (\w+)/) the expression no_space matchdata object #<matchdata "this" 1:"thi" 2:"s"> , while with_space #<matchdata "this is" 1:"this" 2:"is"> . going on here? seems me literal space between tokens indicates ruby should match multiple words if possible, while not having space causes match limited 1 word. explanation or clarification on subject appreciated. thanks. \w doesn't match space, , + greedy unless follow ? , ruby tries match many \w possible, long rest of express matches, consuming thi in first capture, , s in second. when add space, ruby matches many \w until space character, , many \w , therefore matching this , is . please let me know if isn't clear.

php - Defer execution/completion in Twig -

i using twig separately symfony2 framework, smaller rolled suit (perceived) needs better. part of framework asset management library manages js/css dependencies, , after preprocessing, combining, minifying, gzipping, outputs appropriate <link> , <script> tags placed in <head> or in bottom of <body> . the asset helper has 3 public functions: require_asset($asset) , render_head() , render_bottom() . first 1 used sparingly throughout different template parts (i want keep loading of assets outside application logic, hence inside twig templates). 2 others need called after assets have been required, , (after asset manager thing) return appropriate , tags placed in template. all normal templates extend base template: base.twig: <!doctype html> <html> <head> <meta charset="utf-8"> <title>{{ title }}</title> <!--[if lt ie 9]><script src="//html5shiv.googlecode.com/s

Android Studio vs. Eclipse IDE? -

google announced latest release of newest android ide called android studio. http://developer.android.com/sdk/installing/studio.html so wondering, better features of eclipse? still in stages, wise shift new ide or stick eclipse currently? also, has " gradle-based build support ", eclipse has plug-in right? regards.

directoryservices - How to avoid WMI DirectoryEntry caching failed connections -

when making wmi call using directoryentry in c# appears failure cached retries fail without retrying. here's i've done reproduce this: directoryentry directoryentry = new directoryentry(); directoryentry.authenticationtype = authenticationtypes.secure; directoryentry.username = connectusername; directoryentry.password = connectpassword; directoryentry.path = "winnt://" + connectservername + ",computer"; newuser = directoryentry.children.add(username, "user"); make call vm has firewall blocking connection. it take while , fail "the network path not found" however, if enable firewall rule , try again, wmi throw same network path error. it's after wait (i'm unsure long, few minutes) can retry , notice network working. the code in wcf service every call should fresh new instances of everything. any ideas on caching occurring , how can ensure new directoryentry makes fresh call? update: tried iisreset (both site ,

sizeof - C++ fread: unsigned char and short mixture -

i have sample code here: unsigned char *m_fbytes; m_fbytes = (unsigned char*)malloc(m_ibytelen1framedecoded*sizeof(short)); int err; err = fread(m_fbytes, sizeof(short), 960, fin); curr_read = err; for(int i=0;i<curr_read;i++) { opus_int32 s; s=m_fbytes[2*i+1]<<8|m_fbytes[2*i]; s=((s&0xffff)^0x8000)-0x8000; m_in[i]=s; } int ilen = encode(m_enc, m_in, m_ibytelen1framedecoded, m_data, m_max_payload_bytes); i don't understand line: err = fread(m_fbytes, sizeof(short), 960, fin); the authors of code read bytes (aka unsigned char), pass sizeof(short). why use "sizeof(short)"? the code contains couple of tacit assumptions make unnecessarily fragile. way read bytes used s=m_fbytes[2*i+1]<<8|m_fbytes[2*i]; s=((s&0xffff)^0x8000)-0x8000; the assumptions are char_bit == 8 ; that's pretty safe assumption nowadays, unless 1 deals exotic hardware, it's not

Emacs regex search for lines with less then 20 characters -

so if have txt file variable line length, how search emacs regex lines fewer of number (let 20) of characters. this should job matches line between 0 , 20 tokens on it ^[^\n]{0,20}$ ^ start of line (or string) [^\n] not new line {0,20} previous between 0 , 20 times $ end of line (or string)

How do I create random numbers that are nonrepeating using applescript -

trying figure out how create non-repeating numbers using applescript. if want random numbers 1 or 2, want result [1, 2] or [2, 1] , never [1, 1] or [2, 1]. so need figure out way can make sure numbers non-repeating, else know how do. if there unix command can run in applescript, let me know. the next applescript generate non-repeating random-number pairs - range 1..100 set maxvalue 100 set thepairs {} repeat until (count thepairs) = 2 set randomnumber (random number 1 maxvalue) if thepairs not contain {randomnumber} set end of thepairs randomnumber end repeat thepairs i hope not modify question again other.

intuit partner platform - IPP Find All Accounts - Best Practice -

i trying pull accounts quickbooks online account. user has on 350 accounts pull. there way pull them @ once? if not, there way determine how many records there pull, pull them in group? here code: //pull list of accounts. can pull 100 @ time, need keep enumerating until hit 0 account acct = new account(); _accounts = new list<account>(); (int = 1; < 4; i++) { var alist = dataservices.findall(acct, i, 100); if (alist.count() == 0) { break; } _accounts.addrange(alist); } i guessed clients have no more 300 accounts. there way can replace 3 or use more efficient code? in qbo, paging option accounts. in qbd, can count using rest api.pfb link. https://developer.intuit.com/docs/0025_intuit_anywhere/0050_data_services/v2/0500_quickbooks_windows/0100_calling_data_services/0015_retrieving_objects#getting_a_record_count

javascript - Why this render function doesn't work? -

i have been playing backbone , trying learn it. i'm stuck @ point while. not able figure out what's wrong following code? render: function() { this.$el.empty(); // render each subview, appending our root element _.each(this._views, function(sub_view) { this.$el.append(sub_view.render().el); // error on line }); you have got context issue. this refering doesn't contain $el looking for. can fix declaring self variable points appropriate this . following code should work you. render: function() { var self = this; //added line declare variable (self) point 'this' this.$el.empty(); _.each(this._views, function(sub_view) { self.$el.append(sub_view.render().el); //used 'self' here instead 'this' }); side note: leaning backbone should know commong javascript problem document reflow. render view every single model in collection. can lead performance issues , on old computers , mobile devices. c

android - google-play-services_lib.jar missing after updating to latest version (3.1) -

i've been using google play services in app while no prob. i'm using eclipse. i've updated play services(and adt , sdk) latest version after i/o , can not app build. have added google-play-services_lib project app library project. when go java build path project red x next google-play-services_lib under android dependencies. looking in /bin/ dir google-play-services_lib.jar, never build. run issue? converting comment answer after updating android sdk , adt make sure have android build tools installed. goto android sdk manager check if andorid build tools installed. if not installed install same.

php - Peform an update if action selected is edit -

i have link <a href='test.php?action=edit&id=$id'>edit</a> if user clicks on link update form displayed, him/she update the $action=="edit"; is action perfomed in case must update, how ever not here in code if ($action == "edit"){ if ($_server['request_method'] == 'post') { $first_name = $_post['first_name']; $last_name = $_post['last_name']; $email = $_post['email']; $result=mysql_query("update user set first_name='$first_name',last_name='$last_name',email='$email' id = '$id'"); $sql = mysql_query($result) or die (mysql_error()); } sql=mysql_query("select * user id='$id'"); while ($row=mysql_fetch_array($sql)) {

web applications - Is there an Online XPath tester that does not require input XHTML to be perfect? -

i trying figure out answer question: why htmlagilitypack code stop working when dig deeper via xpath? playing xthml on xpath tester independent of htmlagilitypack seems reasonable first step getting feel document tree. however, have not been able find tester accept many characters in xthml document, overlook minor tag errors , such in document. i have not been able fix errors testers run successfully. if could, prefer test xhtml web request, is. any sites not validate xhtml, , still allow user test xpath, or @ least have option ignore xthml illegalities? i think http://xpather.com worth trying because works not xml documents html ones well.

c - what happened when using qsort function? -

i'm trying sort struct node variable a, result turns out wrong. my result: {5, 4}, {6, 2}, {7, 3}, {4, 1}, {3, 7}, {1, 3}, {0, 0}, my code: #include <stdio.h> #include <stdlib.h> typedef struct node { int x; int y; } n; int num = 7; int compare(const void *ele1, const void *ele2) { n *px, *py; px = (n *) ele1; py = (n *) ele2; return px->x < py->x; } int main() { n node[7] = { {4, 1}, {6, 2}, {1, 3}, {5, 4}, {7, 3}, {3, 7} }; int i; qsort(node, num, sizeof (node[0]), compare); (i = 0; < num; i++) printf("{%d, %d}, ", node[i].x, node[i].y); return 0; } if sort 6 pairs of elements, result is: {7, 3}, {6, 2}, {5, 4}, {4, 1}, {1, 3}, {0, 0}, which correct, when tried seven, shows results above. know why happens? thanks! the result of comparison function should return negative number, 0, or positive number. returning 0 or 1. your

makefile - Does order of linker flags matter when running linking step in C++? -

my original question below, evolved following related question: is there wrong putting linker flags after objects in linker statement? when build in eclipse, following linking statement run: g++ -fopenmp -lconfig++ -o "pc2" ./main.o ./sampling.o ./simulation.o which incorrect, because lconfig++ must follow, not precede, object file listing. so, modified makefile, automatically generated eclipse based on project settings. specifically, changed portion of makefile # tool invocations pc2: $(objs) $(user_objs) @echo 'building target: $@' @echo 'invoking: gcc c++ linker' g++ -fopenmp -lconfig++ -o "pc2" $(objs) $(user_objs) $(libs) @echo 'finished building target: $@' @echo ' ' to follows: # tool invocations pc2: $(objs) $(user_objs) @echo 'building target: $@' @echo 'invoking: gcc c++ linker' g++ -o "pc2" $(objs) $(user_objs) $(libs) -fopenmp -lconfig++ @

php - Executing a shell in CakePHP -

i executing shell on fedora 8 32 bit server php 5.2.6 , cakephp 2. getting these errors : php notice: undefined index: tag in path/lib/cake/console/consoleoutput.php on line 202 php notice: undefined index: emergency in path/lib/cake/console/consoleoutput.php on line 217 php notice: undefined index: alert in path/lib/cake/console/consoleoutput.php on line 217 php notice: undefined index: critical in path/lib/cake/console/consoleoutput.php on line 217 php notice: undefined index: error in path/lib/cake/console/consoleoutput.php on line 217 php notice: undefined index: warning in path/lib/cake/console/consoleoutput.php on line 217 php notice: undefined index: info in path/lib/cake/console/consoleoutput.php on line 217 php notice: undefined index: debug in path/lib/cake/console/consoleoutput.php on line 217 php notice: undefined index: success in path/lib/cake/console/consoleoutput.php on line 217 php notice: undefined index: comment in path/lib/cake/console/cons

Android: Line-limited textview with "..." to show that there is more content -

i displaying long (random) text in textview. want show 3 lines in textview , show dots (...) if there more content. know can limit lines of textview minlines , maxlines, don't know add dots in string. e.g. textview could/should like "this random text short 1 , more here..." "this 1 has loooooooooooooooong string ..." you don't need know add dots, textview can you. checkout android:ellipsize=end . note ellipsize's algorithm doesn't work reliably in older android versions. there might discrepancies between exact behavior between 2.3, 3 , 4+. example know not show more 2 lines in 2.3

Deploying maven project to glassfish with Netbeans -

this first post here hi wonderful community. tips found here helped me many times, in need ask question so here problem. i'm struggling deploy simple maven application glassfish server, check if configuration correct further developing. usenetbeans ide, since provides small , barely readable console log, try using system terminal (i use fedora). application i'm trying deploy consists of stateless ejb bean (called dziekanatbean , doing nothing) , maven pom project (simply called maven), includes ejb bean module. try deploy whole project using mvn -e glassfish:deploy project not deploy, occur following errors: [info] error stacktraces turned on. [info] scanning projects... [info] ------------------------------------------------------------------------ [info] reactor build order: [info] [info] maven [info] dziekanatbean [info] [info] -------------------------------------------------------------

javascript - Replace data only if new content is different -

i started out problem extremely similar one: jquery : remplace content if new content different i've tried accepted solution, , doesn't seem work way supposed to. tried first native solution, putting in div stuff. tried looking function on jquery's site here: http://api.jquery.com/data/ , fixed code accordingly last example. tried alerting data see going on, it's fair amount of data, why have md5 hashed. my problem first alert coming undefined, , second 1 is, in fact, defined going out. doing wrong? cause stored data disappear? my current code: function setdiv(data) { newdata = md5(data); if ($('#mydiv1').data('olddata') != newdata) { $('#mydiv1').fadeto("fast", 0, function () {$(this).html(data).fadeto("fast", 1)}); alert($('#mydiv1').data('olddata')) $('#mydiv1').data('olddata',md5(data)); alert($('#mydiv1').data('olddata')

javascript - Kinetic JS Mind Map -

i have make mind map project. using kinetic js . new kinetic js. i have implemented project when click , of button corresponding shape appears on screen. i have make the text editable, link different reasons claims generate reason. " http://jsfiddle.net/rahuls/se6mb/" this have tried. can 1 me possible solution? thanks

javascript - innerHTML for anchor tag not changing -

i trying change innerhtml anchor text not changing.... html: <div style="float:right;"> <a id="grablinkall" onclick="showall()" href="#">show all</a> </div> javascript: function showall() { var thedropposition = document.getelementbyid('grablinkall'); if (thedropposition.innerhtml == "show all") { thedropposition.innerhtml == "hide all"; } else { thedropposition.innerhtml == "show all"; } } use single equal set value thedropposition.innerhtml = "text"; instead double equal conditions if(var1==var2){ //.... and triple equal identical check var x=0; var y=false; if(x===y) alert('they identical'); in case alert not appear if double equal condition true

java - Creating a second applet(window) in processing -

hello guys trying code can create second applet in processing passing on sensible area. the code works fine except 1 thing. when passes on sensible area creates in loop same frame. here code. import javax.swing.jframe; pframe f; secondapplet s; void setup() { size(600, 340); } void draw() { background(255, 0, 0); fill(255); } void mousepressed(){ pframe f = new pframe(); } public class secondapplet extends papplet { public void setup() { size(600, 900); noloop(); } public void draw() { fill(0); ellipse(400, 60, 20, 20); } } public class pframe extends jframe { public pframe() { setbounds(0, 0, 600, 340); s = new secondapplet(); add(s); s.init(); println("birh"); show(); } } this code creates second applet clicking in region of frame, if keep clicking create more frames of same applet. what want once click creates 1 frame , no more. can me please? ;) the code posted won'

node.js - Group by date in mongoose -

this appointment collection { _id: objectid("518ee0bc9be1909012000002"), date: isodate("2013-05-13t22:00:00z"), patient:"john" } { _id: objectid("518ee0bc9be1909012000002"), date: isodate("2013-05-13t22:00:00z"), patient:"alex" } { _id: objectid("518ee0bc9be1909012000002"), date: isodate("2013-05-13t22:00:00z"), patient:"sara" } how can resualt this {date: isodate("2013-05-13t22:00:00z"), patients:["john","alex","sara"] } i try this appointments.aggregate([ { $group: { _id: '$date' } } ], function(err, doc) { return console.log(json.stringify(doc)); }); any please use $push aggregation operator assemble patients array in $group : appointments.aggregate([ {$group: {_id: '$date', patients: {$push: '$patient'}}}, {$project: {date: '$_id', patients: 1, _id: 0}} ], ...) to include patient id

Java XML Reading an XML file from top to bottom -

i want read xml starting top bottom using java. however, don't want use recursive functions because want able jump different element , start reading position. i've tried using getparent() , indexof() methods (all 3 libraries below have these methods) this, it's gotten messy, because methods don't distinguish between attributes , elements. i'm sure there must simple way this, after trying dom4j , jdom , , xom , still have not found solution. [edit] more information: my friend wants make console text-based game in question/answer type style. instead of hard-coding java, decided try , make read xml file instead, because xml has tree-like style convenient. here example of xml file might like: <disp>text displayed</disp> <disp>text displayed afterward</disp> <disp>what favorite color?</disp> <question> <answer name="orange"> <disp>good choice.</disp> <!-- more que

ipython notebook anchor link to refer a cell directly from outside -

i writing documentation notebook-based framework. when referring important cells in demo-notebook, can point particular cell using sort of anchor? for example if have demo-notebook @ 127.0.0.1/mydemo, possible refer input cell in[10] anchor tag 127.0.0.1/mydemo#in10 not on stable, , on header(1-6) cell on master. click on header cell , put right anchor in url bar, wich #header_title_sanitized using prompt number not idea might change. supported on nbviewer well, working on it.

How to display image after using setRGB(x,y,0) in Java? -

for(int x=0;x<20;x++) { for(int y=0;y<20;y++) { img.setrgb(x, y,0); } } i'm trying convert pixels in 20*20 region black colour. not working above code. need add more? try this int rgb=new color(0,0,0).getrgb(); // believe rgb black 0,0,0 cross check for(int x=0;x<20;x++){ for(int y=0;y<20;y++){ img.setrgb(x, y,rgb); } }

kiosk mode - Disable downloads in google chrome -

i using google chrome in kiosk mode. working fine. dont want users download files when click on download link. chrome extension api support this? bonus question: possible restrict users in fixed directory when uploading file( mean in upload dialog)? you can't disable downloads within chrome, operating systems offer ways software parental controls. maybe that.

php - Insert data if not exist -

i have 2 tables cw_users , ref_users , both have column named id . i'm using isam can't use foreign key. wanted insert id cw_users ref_users if didn't exist. this did, didn't help: $id = $_session['id']; $ref_code=md5($id); mysql_query("insert ref_users (id) values ('$id') not exists (select cw_users id='$id')"); the correct syntax insert ignore into insert ignore ref_users (id) values ('$id') it insert if value not exist, , ignore statement if does. note work if id primary key edit: seems comments better off using on duplicate key update . try query insert ref_users(id, ref_code) values ('$id', '$ref_code') on duplicate key update ref_code = '$ref_code'

wpf controls - C# WPF ToggleButton Changing more than one property in a trigger? -

i have togglebutton , when clicked want change background , content. content changes correctly, background changes, instead of specified background value, default (?) blue-ish. in previous struggles background change, not content. done differently, though, w/ datatrigger instead of method below. i'm using c# wpf , mvvm , bind content property , when binded ischecked property changed, change property in viewmodel, hoping not have that. maybe it's correct way? here's code 1/2 works: <togglebutton name="axis3absincbutton" ischecked="{binding path=usercontrolonestatic.motionparameters.axis3absorincoption, source={staticresource locator}}"> <togglebutton.style> <style targettype="{x:type togglebutton}"> <setter property="togglebutton.background" value="goldenrod"/> <setter

android - What is the analog of startActivityForResult() but using fragments -

i have 4 tabs, each runs fragment when selected. tab #2 fragment want start fragment run on tab #2 , results it. right way this? there examples around? if activities, , not fragments, know use startactivityforresult(). there's recommended pattern fragment interaction. each of fragments declares way needs interact others using interface: here's code first fragment: public class fragment1 { private listener listener; @override public void oncreateview(...) { bundle args=getarguments(); if (args!=null) { object arg=args.getparcelable("result"); //use result } //... someview.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { if (listener!=null) listener.onfragment2requested(); } }); //... } @override public void onattach(activit

Rails Database Entry, Values are all question marks -

i trying run create method in rails, insert items database. code create follows: def create @song = song.create ( { :song => params[:song], :artist => params[:artist], :album => params[:album], :song_id => params[:song_id], :longitude => params[:longitude], :latitude => params[:latitude], :stream_url => params[:stream_url], :art_url => params[:art_url] } ) respond_to |format| if @song.save format.json { render :json => @song, :status => :created, :location => @song } else format.json { render :json => @song.errors, :status => :unprocessable_entity } end end end however, following error message. how ensure insert want? started post "/create" 127.0.0.1 @ sun may 19 03:09:21 -0400 2013 processing songscontroller#create */* parameters: {"longitude"=>-72.6600766181946, "latitude"=>41.5570384662233, "album"=>"get lucky", "song"=>

android - How to write a query instead of the keyword OR? -

the case 1 works well, case 2 don't work, there simple way instead of keyword or ? case 1 public list<string> getsms(int pos) { list<string> sms = new arraylist<string>(); uri urismsuri = uri.parse(valuelist.get(pos)); cursor cur = getcontentresolver().query(urismsuri, null,"_id= '6' or _id= '4' ", null, null); while (cur.movetonext()) { string address = cur.getstring(cur.getcolumnindex("address")); string body = cur.getstring(cur.getcolumnindexorthrow("body")); sms.add("number: " + address + " .message: " + body+" cw "+cur.getstring(cur.getcolumnindex("_id")) ); } return sms; } case 2 public list<string> getsms(int pos) { list<string> sms = new arraylist<string>(); uri urismsuri = uri.parse(valuelist.get(pos)); cursor

xcode - iOS mapview auto layout issue -

im creating tab bar app storyboard. basically on secondviewcontroller, set mkmapview toolbar @ top changing views etc. i set span , added annotation shows when screen loaded, shows correctly when using autolayout:off shown below (sorry couldnt embed links im new here) http://img211.imageshack.us/img211/9359/mvautooff1.jpg when put autolayout on this http://img153.imageshack.us/img153/3736/mvautoon.jpg i have tried changing span etc , nothing changes when running simulator. how can change mapview shows when autolayout off? can please me autolayout on resizes devices etc need mapview show how when autolayout off. i new ios coding , totally newb any appreciated! thanks the code .m - #import "secondviewcontroller.h" #import "annotation.h" @interface secondviewcontroller () @end //coordinates of salon #define salon_latitude -33.427528; #define salon_longitude 151.341697; //span #define the_span 0.005f; @implementation secondviewcont

asp.net mvc - Pass method from MVC to WCF -

i made in controller method should creat product [httppost] public actionresult create(producttype product) { if (modelstate.isvalid){ servicereference1.service1client proxy = new servicereference1.service1client(); proxy.addproduct(product); return redirecttoaction("index"); } and addproduct in wcf service public void addproduct(producttype product) { product _product = new product(); _product.name = product.name; _product.adddate = datetime.now; _product.price = product.price; _product.isactive = product.isactive; _product.categoryid = product.categoryid; baseshopentities producttoadd = new baseshopentities(); producttoadd.addtoproduct(_product); } but have error saw infos in net can't find solution on problem. the server unable process request

javascript - Latest EmberJS doesn't recognize latest Handlebars -

when install both latest emberjs (1.0.0-rc.3) , latest handlebars (1.0.0-rc.4), error in console when visit page: uncaught error: assertion failed: ember handlebars requires handlebars 1.0.0-rc.3 or greater. include script tag in html head linking handlebars file before link ember. i error whenever 'vanilla' install downloading jquery, handlebars , emberjs. these errors when generate project yeoman (both generator-ember , generator-charcoal). up-to-date, i've ran npm update -g yo generator-ember generator-charcoal grunt-cli bower with no updates found. has experienced issue before, , how did solve it? to fix using bower , npm, need roll both packages handlebars 1.0.0-rc3 since templates precompiled in both ember , charcoal generators grunt-ember-templates package. this, need update bower.json (or component.json if have not updated it) , package.json. for bower.json (or component.json), change line handlebars "handlebars": "~1.0.0-rc.

adt - Android R.java doesn't generate -

i've updated android sdk version 22.0 (well, more fresh install) , started new project in eclipse. went through project wizard , went fine realised didn't generate build files (neither buildconfig.java nor r.java). i searched bit , found others similar problems , pointed out after updating new package should available called android build tools. had installed them , buildconfig.java generated afterwards still don't have r.java. some suggested cleaning project, editing manifest files , manually adding r.java file revert generated 1 none of these worked, though showed warning message in ide console when edited file didn't anything go windows->android sdk manager download or update android sdk build-tools open project's properties in right panel, choose java build path in left panel make sure android private libraries , android dependencies checked. clean , rebuild project

javascript - Adding OnClientClick to a button generated at runtime -

i have created button @ runtime , add onclientclick property of button,to execute javascript function, example alert(), in case. piece of code works in firefox , other browsers not chrome. appreciate here. button addbutton = new button { text = "test", cssclass = "btn", usesubmitbehavior = false}; addbutton.onclientclick = "javascript:alert('button has being clicked');";

performance - Does python logging flush every log? -

when write log file using standard module logging , each log flushed disk separately? example, following code flush log 10 times? logging.basicconfig(level=logging.debug, filename='debug.log') in xrange(10): logging.debug("test") if so, slow down ? yes, flush output @ every call. can see in source code streamhandler : def flush(self): """ flushes stream. """ self.acquire() try: if self.stream , hasattr(self.stream, "flush"): self.stream.flush() finally: self.release() def emit(self, record): """ emit record. if formatter specified, used format record. record written stream trailing newline. if exception information present, formatted using traceback.print_exception , appended stream. if stream has 'encoding' attribute, used determine how output stream. """ try:

checkbox - TriCheckbox in form? -

i'm trying make form allows tricheckboxes. for example, starts out blank, when click it, gets ticked, if click again becomes cross, , if click final time, becomes blank again. i've played around javascript , classes , managed graphics working, how tricheckbox work in php form? i'm not sure if there better way, can add <input type="hidden" ... /> field , set value in click event handler.

Html 5 Video Plugin for CKEditor 4.1.1 -

there html 5 plugin ckedior here http://ckeditor.com/forums/plugins/html5-video but unfortunately video plugin doesn't work correctly on ckeditor 4.1.1 it works until don't see source, if click on source , return editor write 'your browser doesn't support video. ...' could please guide me ? just got same issue. seems, because, in ckeditor 4.1, added advanced content filter. , in fact, if plugin doesn't explicitelly tag, <video></video> allowed, removed source editor !!! workaround disable acf in editor, adding following line @ begining of ckeditor/config.js file : ckeditor.config.allowedcontent = true; by way, source editor doesn't check anymore html content, accept !! consequence, <video>...</video> tag no more removed ! hopping helps cheers -christian

class - Unique keys mean they are primary keys? -

Image
a booking made single customer , can make several bookings. each room in .a booking can occupied 1 or 2 customers. customer can occupy several. rooms. meal in booking assigned table through tablenumber attribute. the attribute combination name , telephonenumber unique , attribute roomnumber unique. does unique key means primary key? mean both name , telephonenumber primary keys? additional question: can same key foreign key , primary key in table? does unique key means primary key? no. first of all, every key unique, therefore saying "unique key" on "key" redundant. keys in same table logically equivalent, convenience , historical reasons single out 1 of them , call "primary", while rest called "alternate". does mean both name , telephonenumber primary keys? no, there no 2 keys here (much less 2 primary keys). there 1 composite (aka. "compound", "complex") key, comprised 2 fields, happens