Posts

Showing posts from July, 2014

python - Increment a counter and trigger an action when a threshold is exceeded -

i have model this class thingy(models.model): # ... failures_count = models.integerfield() i have concurrent processes (celery tasks) need this: do kind of processing if processing fails increment failures_counter of respective thingy if failures_counter exceeds threshold thingy , issue warning, 1 warning. i have ideas how without race condition, example using explicit locks (via select_for_update ): @transaction.commit_on_success def report_failure(thingy_id): current, = (thingy.objects .select_for_update() .filter(id=thingy_id) .values_list('failures_count'))[0] if current == threshold: issue_warning_for(thingy_id) thingy.objects.filter(id=thingy_id).update( failures_count=f('failures_count') + 1 ) or using redis (it's there) synchronization: @transaction.commit_on_success def report_failure(thingy_id): thingy.objects.filter(id=thingy_id).update(

how to send email with attachment(.doc files) using php -

i have been struggling add attachment mail using thank you.php. generraly resume/cv subnission form.. here job application.php code: <form name="frm" action="thankyou.php" method="post" style="padding-top:10px;"> <table style="text-align: left; width: 100%; color: rgb(255, 0, 0); font-family: arial; font-size: 11px; font-weight: bold;" rules="all" border="0" cellpadding="0" cellspacing="0"> <tbody> <tr> <td>*mandatory fields</td> </tr> <tr> <td align="left" valign="top"><p><table id="table2" cellspacing="0" cellpadding="3" width="100%" align="center" border="0"> <tr>

smslib - Send SMS in java using site2SMS/way2sms -

the following code send sms in java language, import java.net.*; import java.io.*; import java.util.scanner; public class site2sms { //replace site2sms username , password below static final string _username = "username"; static final string _password = "password"; static final string _url = "http://smsapi.cikly.in/index.php"; //static final string _url = "http://smsapi.cikly.in/index.php"; //static final string _url = "http://www.site2sms.com/user/send_sms_next.asp"; static final string charset = "utf-8"; //to build query string send message private static string buildrequeststring(string targetphoneno, string message) throws unsupportedencodingexception { string [] params = new string [5]; params[0] = _username; params[1] = _password; params[2] = message; params[3] = targetphoneno; params[4] = "site2sms"; stri

javascript - jQuery scroll to ID script only scrolling down -

i'm using following make anchor class of .jump-link scroll id it's referencing in href attribute: // scroll id $('.jump-link').click(function () { var el = $(this).attr('href'), elwrapped = $(el); scrolltoid(elwrapped, 40); return false; }); function scrolltoid(element, navheight) { var offset = element.offset(), offsettop = offset.top, totalscroll = offsettop - navheight; $('body,html').animate({ scrolltop: totalscroll }, 500); } unfortunately though seems work scrolling down page. i'd script work scrolling page. try this.. work. $(".jump-link").click(function(){ var id = $(this).attr('href'); $('html, body').animate({scrolltop: $("#"+id).offset().top}, 2000); });

c++ cli - Exception: Cannot marshal 'parameter #X': Pointers cannot reference marshaled structures. Use ByRef instead -

i'm working in vs2010 c++ , have c++/cli call formatmessage() draws strange exception. here block of code below below. if((m_hglrc = wglcreatecontext(m_hdc)) == null) { messagebox::show("wglcreatecontext failed"); char* lpbuffer; formatmessage( format_message_allocate_buffer|format_message_from_system, // it´s system error null, // no string formatted needed ::getlasterror(), // hey windows: please explain error! makelangid(lang_neutral,sublang_default), // in standard language (lptstr)&lpbuffer, // put message here 0, // number of bytes store message null); messagebox::show( nullptr, gcnew system::string(lpbuffer), "lastrrror",messageboxbuttons::ok); //messageboxw(null,(lpctstr)lpbuffer, _t("lastrrror"),mb_ok|mb_iconwarning); // free b

Allocating arrays in C++ -

this question has answer here: in c++ books, array bound must constant expression, why following code works? 2 answers when started programming c++ learned allocate array size using dynamic memory allocation follows: int main() { int narraylength; cout << "enter array length: "; cin >> narraylength; int *narray = new int[narraylength]; // contents delete[] narray; return 0; } now tried following code using code::blocks 12.11 mingw32-g++ // gnu gcc compiler. int main() { int narraylength; cout << "enter array length: "; cin >> narraylength; int narray[narraylength]; return 0; } this works fine. therefore, why should use dynamic memory allocation in case when easier method works fine? you should use neither. the first valid, it's c-style code.

symfony - Symfony2 invalid token with big files -

i'm having problem token , file field form. the validation of form this: public function getdefaultoptions(array $options) { $collectionconstraint = new collection(array( 'fields' => array( 'file' => new file( array( 'maxsize' => '2m', 'mimetypes' => array( 'application/pdf', 'application/x-pdf', 'image/png', 'image/jpg', 'image/jpeg', 'image/gif', ), ) ), ) )); return array( 'validation_constraint' => $collectionconstraint } when upload invalid size file(~5mb) error hope: the file large. allowed maximum size 2m bytes but when upload big file(~30mb) error changes: the csrf token invalid. please try resubmit form uploaded file large. please try upload smaller f

Splitting an integer up in original order and storing it in an array in javascript -

how can done? user enters integer 14865, how can cut integer , put array in exact same order so:[1, 4, 8, 6, 5]. i've tried using %10 method, returns front. one method turn integer string , use string .split() method create array containing each digit. @ point each element of array string, loop on array turn each array element string number (or use .map() ): var x = 14865, = x.tostring().split("").map(function(v) { return +v; }); // [1, 4, 8, 6, 5] note if integer entered user can skip .tostring() part, because string unless you've explicitly converted number. p.s. mentioned "the %10 method" returns values "back front" - don't show how implemented method, if current code extracts digits 1 @ time , adds them end of array "back front" why not avoid problem inserting digits @ beginning of array .unshift() method ?

extjs4 - Extjs. Close popup window by click not in window -

i have popup window, not modal. how can close window click on other part of page (not in window)? something this: function closewin(e, t) { var el = win.getel(); if (!(el.dom === t || el.contains(t))) { ext.getbody().un('click', closewin); win.close(); } } ext.getbody().on('click', closewin);

php - enable active/current state on forum menu/nav -

the current issue @ hand enabling current/active state on forum menu..enabling active/current state on forum css wont trick...my basic understanding of is...create php ,jquery script pulls page id...and nail down jquery..which i'm not sure how do..any ideas? using phpbb3 forum template css #underlinemenu{ margin: 0; padding: 0; height:80px; font-size:14px; background-color:#f6f6f6; } #underlinemenu ul{ margin: 0; margin-bottom: 1em; padding-left: 0; float: right; font-weight: bold; width: 100%; } * html #underlinemenu ul{ /*ie rule. delete margin-bottom*/ margin-bottom: 0; } #underlinemenu ul li{ display: inline; } #underlinemenu ul li a{ float: right; color: gray; font-weight:

recursion - Building tree from array -

i asked build tree array each element contained data node , level of node within tree. array preorder traversal of node. i think solution wrong (or @ least not best way of doing it) i'm not sure why , right solution be. my approach start level 0 on first call function , loop through array , when found level 1 greater level in current recursive call, make recursive call takes array starting @ index of element , increment level. then, result of recursive call child. i check if level of element in array equal level in current recursive call- if so, break out of loop because sibling , don't want return sibling because parent take care of in recursive call. does make sense? need change answer question correctly?

android - FrameLayout: is it possible to put child layout off-screen? -

Image
is possible have structure 1 below. , have linearlayout @ front off screen: <framelayout> <linearlayout> .. layout </linearlayout> <linearlayout> .. front layout </linearlayout> </framelayout> here image. have tried: have tried setting android:layout_marginleft="-300dp" linearlayout (front), test on phone layout inside of visible area. have tried pushing layout off screen translateanimation, after animation ends layout inside of visible area. please me solve problem. thank you. so in case needs here how solved it. sliding menu on top of content. layout structure described in question. here simple animation in xml: show_menu.xml <?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:shareinterpolator="false"> <translate android:fromxdelta="-100%"

smss - Change focus of SQL Server Management Studio -

Image
day # 2 of sql - i trying run function made yesterday, smss looking @ "master" database , not "metrics" database won't run - says "invalid object name". i know simple question, i'm not sure correct term is. need change "scope"? "focus"? "active database"? not sure how on google. add line use metrics before function call. you can change database using dropdown list on toolbar in top left of management studio. and of course, can qualify call this: select metrics.dbo.splitstringcomma() adding use yourdatabasename @ start of scripts habit into. that's own preference.

css - Force linebreak OutputLabel -

i have outputlabel contains lot of text (about 5000 characters of text), outputlabel has add new line after line 200px, possible? <p:outputlabel value="#{object.body}" /> <p:outputlabel value="#{object.body}" style="width: 200px" /> this code doesn't work: public string getbodywithlinebreaks(){ return body.replaceall("(.{100})", "$1<br/>"); } it not solution because method not if word finished, starts new line @ 100th character. some more code: <p:datatable id="datatable" var="object" value="#{notificationoverview.objects}"> <!--some more columns...--> <p:rowexpansion> <h:panelgrid id="display" columns="2" cellpadding="4" style="width:300px;" styleclass=" ui-widget-content grid"> <f:facet name="header&q

Python logging done/fail messages -

when using python logging library, standard approach write message this: logging.info("all right") but necessary show result status of (long) task (after while after output of main part of message). example: some long computing... [done] or some long computing... [fail] how can solve problem? total: ok. possible, in next line. output success message in same line must use other tool (probably, custom), not logging python library. it sounds might out. import logging logging.basicconfig(format = "%(asctime)s - %(levelname)s - %(message)s", level = logging.debug) logging.info("long task starting") try: startlongtaskfunction() logging.info("long task finished") except: logging.exception("long task failed") note logging.exception() different logging.error(). after log entry added logging.exception(), entire python error message included well. if want log critical ev

indexing - MATLAB correlation loop excluding specific column -

i'm trying write code perform correlation on data, each iteration exclude 1 specific column calculation. 1000x60x5 matrix , b 1000x1 vector. @ moment have out(60,5)= zeros; % preallocate loop output ques=1:size(a,2) rep=1:size(a,3) out(ques,rep) = corr(a(:,[(1:ques-1):(ques+1:end)],rep),b(:),... 'rows','pairwise','type','spearman'); end end is there way can specify (instead of [(1:ques-1):(ques+1:end)] ) exclude ques column calculation? i'm assuming way handling 3rd dimension have intended. think you've done fine here alternative won't error when ques == 1 or ques == size(a,2) yours will. on downside, might slower method, haven't tested it. out(59,60,5)= zeros; % preallocate loop output ques=1:size(a,2) rep=1:size(a,3) cols = 1:size(a,2); cols(ques) = []; out(:,ques,rep) = corr(a(:, cols, rep),b,... 'rows','pairwise','ty

php - phpbb poll - Enlarge Images on hover -

i'm using phpbb forum software. i have few images set of options in phpbb poll . display images using bbcode [img] path image [/img] what when user hvers mouse on image, should enlarge how can achieve ? tried few things - modifying css img in common.css , trying add styling img bbcode doesn't work... any appreciated. also there better way put images inside poll? in css file includes styling image can have main style like .poll_image { width: 50px; height: 50px } and on mouseover .poll_image:hover { width: 100px; height: 100px } that should double width & height of image whilst mouse on it, go normal when moves out.

How to select the id of the first div inside the div jQuery -

i have <div> <div id="category_choice"></div> when category item <div> clicked on, .appends <div id="sports" class="category_item" onclick="addcategory('sports/health')"> <div id="sports_thumb" class="category_thumb"></div> <p>sports/health</p> </div> inside of it. now, when click submit button, has pass id of "category_item" inside "category_choice" ajax. i have tried following code: $(document).on('click','#nsubmit', function () { var category = $('#category_choice:first-child').attr('id'); ajax... bla-bla-bla data: category: category... along other data haven't mentioned, because sends fine. "category" remains empty. please tell me mistake. may space?? $("#category_choice :first-child").attr('id') or as @david mentioned in c

c# - Replace a pattern in string only if a certain condition is satisfied - Regex -

how can replace ' \\' in string. (this can done using regex.ismatch(), regex.matches(), regex.replace() however, should done if ' doesn't have \ or \\ before already. (this stuck) that means find ' not have \ or \\ before , add same, i.e. ' replace \\' example string: 'abcd\'efg'hijkl'mno\\'pqrs' resulting string: \\'abcd\\'efg\\'hijkl\\'mno\\'pqrs\\' no need regex, even. var newstr = oldstr.replace("\\'", "'").replace("'", "\\'"); with regex, can find ' don't have \\ before them with: [^\\]'

netbeans - What is the best way to share the new version of Java source code between a group of programmers? -

i started work group of 5 new programmers on large project. i'm looking best way share source code between members. each person modifying different parts parts related. i'm looking platform or way when change parts of code can see on-line or possible. currently conflicted each other. instance worked on parts of source code , when finish job , went our subversion repository google code upload new version. realize else has been edited code! can in situation? we using netbeans , working far away each other can not have face face meeting. you write subversion repository: well, that's good, because version control software need. conflicts can appear when people work on same parts of code, doesn't happen often. if does, should talk team members , set policy update local working copies more often. idea set subversion send out e-mail notifications whenever commits changes. when conflict appears, 1 updates local working copy has resolve conflict. resolving d

xslt - How can I summarize nodes using calculation data from other nodes -

using xslt 1.0, how can summarize subnodes under given node while modifiyng content data set of nodes in elegant way? assume have xml: <root> <exchangerates> <exchangerate> <currencycode>usd</currencycode> <rate>6.4</rate> </exchangerate> <exchangerate> <currencycode>eur</currencycode> <rate>8.44</rate> </exchangerate> <exchangerate> <currencycode>sek</currencycode> <rate>1</rate> </exchangerate> </exchangerates> <prices> <price> <currency>sek</currency> <amount>10000</amount> </price> <price> <currency>eur</currency> <amount>1000</amount> </price> <price>

java - Data is getting displayed on the UI -

iam learing jsf ejb3.0 + jpa(hibernate) iam getting data tables on screen not displaying anything. here code. managed bean package retail.web.mbean; import java.sql.timestamp; import java.util.calendar; import java.util.date; import java.util.hashmap; import java.util.list; import java.util.map; import java.util.map.entry; import java.util.properties; import javax.faces.bean.managedbean; import javax.faces.event.ajaxbehaviorevent; import javax.naming.initialcontext; import javax.naming.namingexception; import retail.ejb.service.ordersessionbeanremote; import retail.model.vo.customer; import retail.model.vo.order; import retail.model.vo.products; @managedbean public class ordersmb { private order order = new order(); private hashmap<integer,string> customermap = new hashmap<integer,string>(); private hashmap<integer,string> productsmap = new hashmap<integer,string>(); private string customername; private string productname;

module - How to execute a jar file on jboss7 startup? -

i have simple java class displays "waiting" text on execution , in "tmscore" java project. package com.stock.bo; public class example { /** * @param args */ public static void main(string[] args) { // applicationcontext context = new classpathxmlapplicationcontext("applicationcontext.xml"); system.out.println("================================> waiting"); } } i have created tmscore.jar , have set example.class entry point ,of jar file. then have created module project in c:\jboss\jboss-as-7.1.1\modules\org\tms\main , , pasted jar in same path then have created module.xml , pasted in same path module.xml <?xml version="1.0" encoding="utf-8"?> <module xmlns="urn:jboss:module:1.1" name="org.tms"> <resources> <resource-root path="tmscore.jar"/> </resources> </modu

c - A strange behaviour of getchar() -

an odd behaviour of getchar() , scanf ocurred in code below: if insert, in line /*k1*/ ch = getchar(); code works in line /*k*/ . i mean, without calling getchar in line /*k1*/ compiler doesn't ask character keyboard. on other hand if getchar included program runs perfectly. ring me bell? int incoord(int n, int **coo){/*retorna quantidade de dados lida em coordpontos.dat*/ file *fp; /*arquivos de leitura e gravacao. */ char dummy[maxstr]; /*informacoes para o usuario nos arquivos de leitura.*/ int i, j; int m; char ch; printf("entrada por coordenadas de pontos.\n"); printf("leitura das coordenadas com numeros inteiros.\n"); printf("arquivo de leitura: coordpontos.dat\n"); if((fp=fopen("coordpontos.dat","r"))==null){ printf("arquivo não pode ser aberto.\n"); exit(1); } fgets(dummy,maxstr,fp); /*apresentacao arquivo*/ fgets(dummy,maxstr,fp);

php - When to process Markdown? -

i have flavored version of markdown implemented in social web application. works, question is: when should convert user input (markdown) html? before storing in database (so html stored in database) or when user requests view (store markdown in database)? both methods have pros , cons, come following arguments: storing processed input in database makes showing faster, because don't need convert anymore, it's ready display. processing when viewed allows me change markdown processor @ time, example adding feature automatically parses youtube urls embeds. what approach take , why? as rule, try store data in least processed state, because might change way it's processed. can recreate processed data, can't recreate original. what if want add "edit" feature? you'll need markdown. i'd store markdown , render on demand, putting in cache (which might simple "store both formats in database) if performance might problem.

Wordpress Plugin for Soundcloud giving "Track currently not available" -

so using wordpress build website soundcloud plugin. shortcode 3 out of 4 songs working fine fourth shows "track not available". track playable on soundcloud fine. here webpage happening: http://lostintheholler.com/epk/?page_id=13 and here track on soundcloud: https://soundcloud.com/lostintheholler/07-take-it-and-go the wordpress embed code soundcloud works fine doesn't have using plugin. thanks! in last embed track can find : <param name="movie" value="http://player.soundcloud.com/player.swf?url=%3c%2fcode%3e%3ccode%3ehttp%3a%2f%2fapi.soundcloud.com%2ftracks%2f20974440&amp;color=905c18&amp;theme_color=fbe8cf"> there characters in url parameter : %3c%2fcode%3e%3ccode%3e try find they're , delete them , work 3 other tracks.

java - How to read JSON object from URL query string -

i have url request this: http://localhost:8080:_dc=1367504213107&filter[0][field]=site&filter[0][data][type]=string&filter[0][data][value]=test&filter[1][field]=address&filter[1][data][type]=string&filter[1][data][value]=columbus this url request browser. from url, i need filter related data json object . basically have filter parameters these in requested url: filter[0][field]=site filter[0][data][type]=string filter[0][data][value]=test filter[1][field]=address filter[1][data][type]=string filter[1][data][value]=columbus i using spring mvc framework. those url parameters aren't in json format. i'm not sure question / problem here... can't read in each of parameters url , parse data out of strings need? take single parameter , tokenize based on custom character, or loop through parameters , parse each 1 , add them array. are saying need return data in json format? data using parsed parameters described above, when have dat

javascript - how to totally remove any kind of Thumbnails using Jquery FileUpload library? -

i'm using jquery fileupload upload files on server. i need remove kind of thumbnails in html area of upload, if configured javascript , php avoid thumbnails, still have them in 2 occasions: when add file, it's created canvas image when file uploaded, created html image thumbnail link i don't want space thumbnails in box, @ all. these configuration (i copy code of interest) this configuration javascript $('#fileupload').fileupload({ **previewsourcefiletypes: '',** url: 'tfnav?page=upload' }); and configuration php: $this->options = array( 'script_url' => $this->get_full_url().'/', 'upload_dir' => $this->_hattach->getuploadpath(), 'upload_url' => $this->get_full_url().'/files/', 'user_dirs' => false, 'mkdir_mode' => 0755, 'param_name' => 'files', 'delete_type' =

Loop / indexing query in MATLAB -

i have matlab code want use find output 50 sources randomly placed inside grid , summed; @ moment can work 1 source; code this; %required constants ro = 5*10^-6; po = 40; = 5.9336*10^-6; d = 2*10^-9; f = 2.6835*10^-7; mult = a/(4*f*d); rc = 6.0260e-05 pop = 5:1:495; %initialise 500 x 500 array 0 pp = zeros(500,500); = 1; while < 2 x(i) = randsample(pop,1); y(i) = randsample(pop,1); %randomly selections x,y point on grid - below if loop sets boundary of %+/70 %microns point examine. min lower point in x , y 1, max 500; if x(i) - 70 > 0 && x(i) + 70 <= 500 && y(i) - 70 > 0 && y(i) + 70 <= 500 xb(i) = x(i) - 70; xu(i) = x(i) + 70; yb(i) = y(i) - 70; yu(i) = y(i) + 70; elseif x(i) - 70 < 0 && x(i) + 70 <= 500 && y(i) - 70 > 0 && y(i) + 70 <= 500 xb(i) = 1; xu(i) = x(i) + 70; yb(i) = y(i) - 70; yu(i) = y(i) +

jquery - Img src changes but not the actual image -

i'm changing image clicking on button. can see in src code image changed, actual image isn't changing in browser. how come, , how solve it? // avatargenerator.eyes = 1; moverightbtn.on('click', function(){ var newimage = 'eyes' + (avatargenerator.eyes + 1) + '.png'; $('#eyesimg').attr('src','img/' + newimage); }); edit: created jsfiddle works, thing i'm using fabric.js (a canvas framework), may reason it's not working thought can't understand why. :( your fabric.js code: var canvas = new fabric.canvas('canvas'); var imginstance = new fabric.image(imgelement, { left: 100, top: 100, angle: 30, opacity: 0.85 }); canvas.add(imginstance); "stamps" visual copy of image onto canvas. canvas doesn't hold kind of reference of original image element, because canvas dumb grid of pixels. canvases don't know about represent, hold pixel data. thus, when o

knockout.js - Updating one observableArray while looping another observableArray -

given 1 observablearray, populated service call, used render checkbox list in view: orgchart = ko.observablearray(); id dept and observablearray, populated service, returns list of id's departments have been selected (in db) above array. selecteddepartment = ko.observablearray(); id how knockout bind second array when looping on first? i tried this, renders checkbox list, fails update selecteddepartment array. <div data-bind="foreach: orgchart"> <div><input type="checkbox" data-bind="checked: selecteddepartment, value: id }"/><span data-bind="text: dept"/></div> </div> i'm guessing need use mapping or computed value, can't find examples. my solution have 1 observablearray, not two. combine data received 2 service calls list of objects. for example, var orgchart = getdatafromfirstservicecall(); var selecteddepartments = getdatafromsecondservicecall(); var v

css - Android native browser doesn't update height on overflow auto when adding elements -

i'm making 1 page mobile web app. container fixed @ 100% height , article inside has overflow: auto height: 100% this works great on both ios , android, viewport stays static , content scrolls in middle. however, when add new dom element article, or unhide hidden div, android not update height of scrolling div, elements @ bottom of same div cut off @ scroll limit. is there anyway around this? ok managed fix forcing view repaint whenever altered dom $('<style></style>').appendto($(document.body)).remove(); a horrible horrible fix, works... the android browser new ie6.

Mvvm Light Dispatcher Helper -

how can use dispatcher helper progress bar in mvvm-light. i'm accessing ui element defined in viewmodel , think dispatcherhelper solved this, seems progressbar not updated when ran backgroundworker dispatcherhelper. please help: here's code : _worker = new backgroundworker() { workerreportsprogress = true, workersupportscancellation = true }; _grid = new grid(); _worker.dowork += (sender,e) => dispatcherhelper.uidispatcher.invoke(() => { try{ var vworker = (backgroundworker) sender; reportcolumns = new list<reportcolumn>(); #region set report item column for(var = 1;i <= _reportbal.reportitemcontent.columns.count - 1;i++) { var vcolumnsitems = reportparser.parsecolumnattributes(_reportbal.reportitemcontent.columns[i].columnname); var vcolumn = new reportcolumn();

python long number data loss -

i starting python (python3) because read euler project since can handle big numbers. now struggling quite simple problem of converting float int. why don't same result this: num = 6008514751432349174082765599289028910605977570 print('num {0} '.format(int(num))) num = num / 2 print('num /2 {0} '.format(int(num))) num = num * 2 print('num *2 {0} '.format(int(num))) output is: num 6008514751432349174082765599289028910605977570 num /2 3004257375716174771611310192874715313222975488 num *2 6008514751432349543222620385749430626445950976 you using float division, cannot handle large numbers precision, after flooring result casting int() . don't that, causes data loss. use integer (floor) division // instead: >>> 6008514751432349174082765599289028910605977570 // 2 * 2 6008514751432349174082765599289028910605977570 this still can lead rounding errors of course, if input value not divisible 2 without flooring:

javascript - How to properly hide selected dropdown? -

i'm trying achieve similar bootstrap button drop downs ( http://twitter.github.io/bootstrap/components.html#buttondropdowns ) need lightweight. basic functionality more or less this: on clicking link, corresponding dropdown div opens (works) on clicking link, previous dropdown closes css class removed (works) on clicking on link of opened dropdown, close dropdown (does not work (closes , reopens)) on clicking anywhere in body (so outside link , dropdown), close dropdown (does not work) what should logic behind this? demo: http://jsfiddle.net/fu2bz/ does code below make sense? $(document).click( function(){ $('.dropdownbox').hide(0); $('.dropdown').removeclass('active'); }); $('.dropdown').click( function(event){ event.stoppropagation(); $('.dropdown').removeclass('active'); $('.dropdownbox').hide(); $(this).addclass('active').find('.dropdownbox').slidetoggle(

ANTLRWorks, whitespaces, memory leaks, and crashing -

i wanted try tool, antlr, arrive parse code , refactor it. tried small grammars, ok, took next step , started parsing sort of simple c#. news: takes 10 minutes understand basics. extrememly bad news: takes hours understand how parse 2 spaces instead of one. really. things hates whitespaces, , has no shame in telling that. started think unable parse them, went right way... or @ least thought so. now problem of spaces comes after fact antlrworks tries allocate half gb of ram , cannot parse anything. the grammar not hard, being beginner: grammar newemptycombinedgrammar; tokenendcmd : ';' ; tokenglobimport : 'import' ; tokenglobnamespace : 'namespace' ; tokenclass : 'class' ; tokensepfloat : ',' ; tokensepnamespace : '.' ; fragment tokenemptystring : '' ; tokenunderscore : '_' ; tokenargssep : ',' ; tokenargsopen : '(' ; tokenargsclose : ')' ; tokenblockopen : '{' ; tokenblockcl

PHP exec unable to fork IIS 6.0 -

trying run exec() via: exec("wkhtmltopdf\wkhtmltopdf fedexdomestic.html fedexdomestic.pdf"); i following error message: warning: exec(): unable fork [wkhtmltopdf\wkhtmltopdf fedexdomestic.html fedexdomestic.pdf] ... it works on local server using xampp, not in iis 6.0 server. i have tried many things work, including following: 1) giving full control permissions iusr in cmd.exe, folder containing .php file, , program i'm trying execute. 2) running cacls %comspec% /e /g %computername%\iusr_%computername%:r via command prompt cmd.exe 3) giving full control permissions network service in cmd.exe, folder containing .php file, , program i'm trying execute (this because read w3wp.exe what's used running external programs, , user name responsible network service). 4) replacing exec() system() , shell_exec() i have been @ problem days, , have researched , tried many different things no avail. please help! got same issue, can't run fu

xamarin.android - Android Scheduled Timer - Mono for Android or Java -

i need run method every 5 seconds using mono android. there scheduled timer in android? have tried code, however, fails start: using system; using system.collections.generic; using system.linq; using system.text; using android.app; using android.content; using android.os; using android.runtime; using android.views; using android.widget; using glass.core.interfaces; using glass.core; using java.util; namespace glass.ui.an { [application(label = "glass", icon = "@drawable/icon")] public class glassapplication : application { context context; public glassapplication (intptr handle, jnihandleownership transfer) : base(handle, transfer) { this.context = basecontext; } public override void oncreate () { base.oncreate (); timer timer = new timer (); timer.scheduleatfixedrate (new customtimertask(context), new date(datetime.now.year, datetime.now.month, datetime.now.day, datetime.now.hour, dat

Rails custom foreign key not respected -

the relevant database tables have these schemas: sqlite> .schema structures create table structures( struct_id integer primary key autoincrement not null, batch_id integer, tag text, input_tag text, foreign key (batch_id) references batches(batch_id) deferrable deferred); sqlite> .schema residues create table residues( struct_id integer not null, resnum integer not null, name3 text not null, res_type text not null, foreign key (struct_id) references structures(struct_id) deferrable deferred, primary key (struct_id, resnum)); i have following models: class structure < activerecord::base set_table_name "structures" self.primary_key = "struct_id" attr_accessible :struct_id, :batch_id, :input_tag has_many :residues end class residue < activerecord::base self.primary_keys :struct_id, :resnum belongs_to :structure, :foreign_key => 'st

Tornado WebSocket closes once a minute -

i'm using closure client-side , tornado server side. create socket: this.socket = goog.net.websocket(true) and open it: this.socket.open(thesocketurl) every works fine including messages being passed correctly. however, once per minute (once every 60 61 seconds), socket closes , reopens. there no errors server-side , closure socket error event doesn't called. i've added logging tornado , seems calling on_connection_close() calls socket's method on_close(). close() method not called. any idea why might happening? are using nginx or other reverse-proxy in front of tornado server? i've seen happen when proxy timeout elapses , nginx closes connection, causing behavior you're seeing. you can change proxy_send_timeout , proxy_read_timeout in nginx prevent this. make sure when edit proxy.conf , include main nginx.conf .