Posts

Showing posts from September, 2013

Detect a Variable Exists in jQuery -

hello rather new jquery , have situation here. i setting default position on document.ready below $('.categorytitle').scrollto($(".people .sants a.modeling").attr('href'), 750, {easing:'easeoutexpo'}); now works when placed on page containing .categorytitle class the issue arises when script cannot find .categorytitle class in document i tried below code did not work if($('.categorytitle').length!= 0){ $('.categorytitle').scrollto($(".people .sants a.modeling").attr('href'), 750, {easing:'easeoutexpo'}); } can on way can find if .categorytitle exists in page? many thanks! this complete code trying implement. if($('.categorytitle').length){ $('.categorytitle').scrollto($(".people a.modeling").attr('href'), 750, {easing:'easeoutexpo'}); } if($('.categorytext').length){ $('.categorytext').

c# - linq help for deep date list -

i have class list of 2nd class has list of dates. best way entire list of dates in top level class? given following: class 1 contains: public list<class2> class2list; class 2 contains: list<datetime> datelist; what best way entire list of dates in class 1? know can loop through each of class 2 items , list way, i’m hoping there cleaner way linq. list<datetime> tempdatelist; foreach (var class2 in class2list) { foreach (var dt in class2.datelist) { tempdatelist.add(dt); } } return tempdatelist; pretty simple really; var tempdatelist = class2list.selectmany(x => x.datelist).tolist(); selectmany(x => x.datelist) essentially performs inner loop here, creating continuous sequence (all of datelist first class, of datelist second class, etc) tolist() creates concrete list<datetime> data the var tempdatelist static typed, , infers list<datetime> expression

javascript - Evaluating JS from an Ajax response using JQuery -

i have ajax form submit, , response contains 2 divs, 1 containing html content , other containing dynamic javascript in script tag. i'm submitting form , receiving response ok, can't seem javascript evaluate. i've put alert inside never fires. code using submit form: $("#categoryformsubmit").live("click", function(event){ event.preventdefault(); var action = this.form.action + '?_eventname=' + this.name + 'ajax'; var params = $(this.form).serialize(); var xhr = $.post(action, params, function(response) { var responsedom = $(response); var contentdata = $('#content', responsedom).html(); var javascriptdata = $('#javascript', responsedom).html(); $('#content').html(contentdata); $('#javascript').html(javascriptdata); }, 'html'); }); in response trying convert response data dom object , pa

c# - SharePoint ashx handler file download Problem -

i have ashx handler gets file using, in sharepoint, , checks kind of file , writes using response.binarywrite . file server, contains of our files. when go download file thats 3mb works fine. when go download 30mb or 40mb file error. exception of type 'system.outofmemoryexception' thrown. @ system.string.getstringforstringbuilder(string value, int32 startindex, int32 length, int32 capacity) i checked application pool @ have set @ 1.5gb virtual , 1gb actual memory. out of ideas , dont know go next have ideas? case "pdf": context.response.contenttype = "application/pdf"; context.response.addheader("content-disposition", "inline; filename=" + asset.a_name); } context.response.binarywrite(content); you may want try response.transmitfile method, not buffer content in server memory.

regex - PHP preg_replace - How to get the same result without `/e` `eval` - improved security and speed performance? -

how same result without /e eval - improved security , speed performance? function finclude($file){ return include($file); } $str = "today {include 'date.php'}."; echo preg_replace("/\{include '(.*)\'}/e", 'finclude("$1")', $str); date.php: <?php return date('js \of f'); ?>, 2011 result: today 20th of july. you can use preg_replace_callback echo preg_replace_callback("/\{include '(.*)\'}/", function($m) { return include($m[1]); }, $str);

localization - Do the contents of java.lang.System.properties change with locale? -

i'm not used having take i18n stuff account. wrote method java program: boolean iswindows() { return system.getproperty("os.name").tolowercase().contains("windows"); } i need check in order provide workaround windows-specific jvm bug. it occurred me program may need run on systems not have english chosen language, going cause line of code break? maybe should clarify asked hoping see proof people dredge (so feel better letting code out wild). answers links documentation, experimental evidence, or kind of supporting rationale preference. let me straight, wondering whether os name (as returned os.name property) might internationalized , contain word windows in other language? i 99% won't microsoft windows trademark (or whatever, ianal ) , not translated , left as-is. however, looked up definition of is_os_windows property in apache commons lang systemutils class. after removing layers of indirection boils down to: system.getpr

javascript - using a tag to replace div -

my site has 2 pages both have hyperlinks each other when user click on hyperlink need div of page replaced div on other page, please guide me how program it. structure page1.html <div id="no_replace"> <a href="page2.html">page 2</a> <div id="replace"> //page 1 stuff </div> </div> page2.html <div id="no_replace"> <a href="page1.html">page 1</a> <div id="replace"> //page 2 stuff </div> </div> so on page 1 when usr clicks on link "page two" ... want 'replace' div of page 1 replaced 'replace' div of page2.html , there should fade in , fadeout use load() method. $('a').click(function(){ $('div').load($(this).attr('href')); });

ruby - Download an image from a URL? -

i trying use http::get download image of google chart url created. this first attempt: failures_url = [title, type, data, size, colors, labels].join("&") require 'net/http' net::http.start("http://chart.googleapis.com") { |http| resp = http.get("/chart?#{failures_url") open("pie.png" ,"wb") { |file| file.write(resp.body) } } which produced empty png file. for second attempt used value stored inside failure_url inside http.get() call. require 'net/http' net::http.start("http://chart.googleapis.com") { |http| resp = http.get("/chart?chtt=builds+in+the+last+12+months&cht=bvg&chd=t:296,1058,1217,1615,1200,611,2055,1663,1746,1950,2044,2781,1553&chs=800x375&chco=4466aa&chxl=0:|jul-2010|aug-2010|sep-2010|oct-2010|nov-2010|dec-2010|jan-2011|feb-2011|mar-2011|apr-2011|may-2011|jun-2011|jul-2011|2:|months|3:|builds&chxt=x,y,x,y&chg=0,6.66666666666666666

NHibernate QueryOver with subquery or other ideas how this can work? -

i have following queries: model.rampactivehour rah = null; var defaultweekquery = queryover.of<model.rampadditionaldefaultweek>() .where(adw => adw.ramp == rah.ramp && adw.active && adw.fromdate <= date && adw.todate >= date) .select(adw => adw.id).take(1); var result = session.queryover(() => rah) .where(ah => ah.dayofweek == date.dayofweek) .whererestrictionon(ah => ah.ramp).isin((icollection) ramps) .withsubquery.whereproperty(ah=>ah.additionaldefaultweek) .eq(defaultweekquery) .list(); the result query is: select this_.id id3_0_, this_.dayofweek dayofweek3_0_, this_.active active3_0_, this_.slotscount slotscount3_0_, this_.slotid slotid3_0_, this_.slotlength slotlength3_0_, th

c# - how to locate and store character positions in a text file -

i trying create lexicographically sorted index of words along position in text file. with of experts in forum able create lexicographically sorted index of words. need storing position of lexicographically sorted index of words this have far:- text file (sometextfile.txt) containing data follows:- "this sample text file" private const string filepath = @"d:\sometextfile.txt"; using (streamreader sr = file.opentext(filepath)) { string input; //dictionary store position of characters in file long , lexicographically sorted value string var parts = new dictionary<long,string>(); while ((input = sr.readline()) != null) { string[] words = input.split(' '); foreach (var word in words) { var sortedsubstrings = enumerable.range(0, word.length) .sel

github - How to force a pull to a file in git? -

i having merge conflict, , can rename file , pull repo ti resolve or manually edit edit. time, committed changes file has conflicts, , in staging area. tried using git reset head <file> and using git pull again, still merge conflicts. there way force overwrite of troublesome file? here message get: error: local changes following files overwritten merge: db/profile_edit.php i change name of file profile_edit.phpbkup. git pull , still same error. why this? file doesn't exist anymore, how can replaced? thanks. if want throw away changes made concurrently upstream: git fetch origin git push -f . origin/brancha:brancha if want resolve conflicts favouring upstream instead: git fetch origin git merge -s recursive -xtheirs origin/brancha hope helps.

Ruby if shorthand + map shorthand -

how use map(&:name) shorthand inside a condition ? map(&:name) : name if shorthand? i got syntax error, ruby trying evaluate first colon. it's unclear problem here way use " map(&:name) " inside conditional: require 'ostruct' # demonstration using openstruct. arr = [openstruct.new(:name => 'foo'), openstruct.new(:name => 'bar'), openstruct.new(:name => 'gah')] name = 'testing' (true ? arr.map(&:name) : name) # => ["foo", "bar", "gah"] (false ? arr.map(&:name) : name) # => "testing"

How to parse mail in Ruby-Mail 2.3 like in TMail? -

given tmail seems have problems ruby 1.9.2 have tried use mail instead. in old code had gmail = net::imap.new(gmail_host, gmail_port, gmail_ssl) gmail.login(gmail_user, gmail_pass) gmail.select('inbox') gmail.uid_search(["not","seen"]).each |message_id| tmail::mail.parse(gmail.uid_fetch(message_id, 'rfc822').first.attr['rfc822']) .... how go implementing same in mail? i've tried mail.read(gmail.uid_fetch(message_id, 'rfc822').first.attr['rfc822']) , mail::mail.parse(gmail.uid_fetch(message_id, 'rfc822').first.attr['rfc822']) thinking sort of drop-in replacement no avail. yep, ran problem today. here's solution used: saving attachments rails 3 in case, it'd be: mail.new(gmail.uid_fetch(message_id, 'rfc822').first.attr['rfc822'])

javascript - Questions to create a nested list retrieved from an XML-file and displayed in xHTML -

the objective display list of urls in html page. list retrieved file (currently in xml-format). validator: proper xhtml mark-up list generated javascript , still validate properly? assume reason javascript-code inside [ul]'s not accepted. correct? there solution? code below produce list anticipated, creates warning (pls see below, 2.). <ul>list <li>item a1</li> <li>item a2</li> <ul>list b <li>item b1</li> <script type="text/javascript">/* <![cdata[ */ if (window.xmlhttprequest) { xmlhttp=new xmlhttprequest(); } // code ie7+, firefox, chrome, opera, safari else { xmlhttp=new activexobject("microsoft.xmlhttp"); } // code ie6, ie5 xmlhttp.open("get","/test-code/panorama-list2.xml",false); // xmlhttp.open("get","/test-code/panorama-list2.xml",true); /

php - How do I effectively use crypt() -

i don't understand documentation @ php.net . appears using encrypted version of password salt when testing against original encryption. when insert crypt out optional second parameter (the salt) different encrypted versions of same password. expected behavior? however if insert second parameter of 'd4' same encrypted passwords same password input. expected behavior. prior insertion on signup: $pass = crypt('$pass', 'd4'); // after insert $pass mysql table testing on signin: $pass = crypt($pass, 'd4'); // after test $pass against mysql table php.net documentation: <?php $password = crypt('mypassword'); // let salt automatically generated /* should pass entire results of crypt() salt comparing password, avoid problems when different hashing algorithms used. (as says above, standard des-based password hashing uses 2-character salt, md5-based hashing uses 12.) */ if (crypt($user_input, $password) == $password)

jquery - An array for deleting a group of items in a list.DIT: -

what i'm attempting have array of items checked made when user clicks on delete content pages. have array name in check boxes i'm thinking thinking wrong. http://jsfiddle.net/uvdec/ edit: $('.ask2').jconfirmaction( { question : "are sure want delete selected rows?", questionclass: "question2", onyes: function(evt){ contentpages(evt.target); } } ); function contentpagesarray(whatsthis) { $('#delete').click(function () { var delout = new array(); $('tbody') .children() .find('td>input[type="checkbox"]') .each(function () { if ($(this).is(':checked')) delout.push($(this).attr('value')); }); console.debug(delout); alert(delout); }); } well, of other js files, solution broke in practice (because couldn't edit file

geometry - find orthonormal basis for a planar 3D ( possibly degenerate) polygon -

given general planar 3d polygon, there general way find orthonormal basis planar polygon? the straight forward way assume take first 3 points of polygon, , form 2 vectors each, , these 2 orthonormal basis vectors looking for. problem approach these 3 points may line on same line in polygon, , hence instead of getting 2 orthonormal vectors, one. another approach find second orthonormal vector loop through polygon , find point forms different orthonormal vector first one, approach susceptible numerical errors (e.g, if second vector same first vector? numerical errors can significant). is there other better approach? you can use cross product of 2 lines connected 2 vertices. if cross product low you're in degenerate territory. you can take centroid (the avg of points, guaranteed lie on same plane) , pick largest of 2 cross products of vectors centroid vertex. accurate normal. please note if largest cross product small, may have inaccurate normal. if can't fi

How to write regex to handle multiple spaces? -

i need regex name of label. labels this: lbl labelname the regex need return labelname. manged make this: (?<=\slbl\s).+?(?=\s) this works fine long there 1 character between "lbl" , "labelname". if add 2 spaces or more spaces return spaces. i tried (?<=\slbl\s+).+?(?=\s) doesn't work either. does following regular expression work you? lbl\s+([^\s]+)

wordpress - Comment not being posted with xml-rpc wp.newComment php -

i have code this. <?php include('ixr_library.php'); $client = new ixr_client('http://127.0.0.1/wordpress/xmlrpc.php'); $data = array( 'comment_post_id' => 1, 'comment_author' => 'test_author', 'comment_author_email' => 'test@gmail.com', 'comment_author_url' => 'http://test.limewebs.com', 'comment_content' => 'test content', 'comment_type' => '', 'comment_parent' => 0, 'user_id' => 1, 'comment_author_ip' => '127.0.0.1', 'comment_agent' => 'mozilla/5.0 (windows; u; windows nt 5.1; en-us; rv:1.9.0.10) gecko/2009042316 firefox/3.0.10 (.net clr 3.5.30729)', 'comment_date' => $time, 'comment_approved' => 1, ); if (!$client->query('wp.newcomment','', 'username','password','12',$data)) { die('an error occurred - '.$client->geter

java - Independent JUnit Tests with Springs @Autowired -

as beginner in test driven development encountered problem. test class begins follows: @runwith(springjunit4classrunner.class) @transactional @dirtiescontext @contextconfiguration(locations = {"/web-test.xml"}) public class xxtest { @autowired xx xx; @autowired hibernatetemplate template; @test public void testsetgetxxvalue() throws exception { final map<string, yy> profilmap = new hashmap<string, yy>(2); profilmap.put("1", new yy()); profilmap.put("2", new yy()); simplecockpit.setvalues(profilmap); assertequals(profilmap, simplecockpit.getvalues()); } as can see, first test method alters autowired xx-class. affects following test methods, relies on xx having autowired-values. how can test getter , setter xx , make sure xx has autowired values rest of test methods? thoughts: reset right values @ end of test method. bad because if getter / setter not working, not work. place first test metho

Multithreading java -

i'm trying figure out how multithread in java. right now, program works fine no concurrency want implement multithreading speed along. the program runs several objects of separate sub class , 50% of time evaluation each of objects spent in process utilizes 1 core rather 8 available. these objects independent of 1 until used inputs in program. i trying multithread having subclass implement runnable , have program use thread each such object. correct way? however, how threads in java handeled? need dispose of threads after each run? how join work? thanks don't manage threads manually, take @ executors , thread pools in java

java - Accessing parent class object through thread -

my question is, in code have made jtable in main class. making thread task , collect data want fill in jtable thread collects it. thread should run while. can access jtable of main class through thread created. edit: i'm providing code here. test.java package test; import java.awt.event.*; import javax.swing.*; import javax.swing.table.abstracttablemodel; import java.awt.*; public class test implements actionlistener { thread t; jtable table; jscrollpane scrollpane; jbutton b; jframe frame; public void body() { frame = new jframe("tabledemo"); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setlayout(new flowlayout()); table = new jtable(new mytablemodel()); table.setpreferredscrollableviewportsize(new dimension(500, 70)); table.setfillsviewportheight(true); scrollpane = new jscrollpane(table); frame.add(scrollpane); b = new jbutton("ok"); frame.add(b); thread = new thread(new mytablemodel()); t = ne

c++ - Call API in particular windows credentials -

i want call api in particular windows credentials, one way is, write particular piece of code or api in exe , execute exe in particular windows credentials. please let me know if aware of other solution. thanks in advance. you use logonuser() , impersonateloggenonuser() , call code, call reverttoself() original credentials. can either in thread, or create separate thread , there. latter preferred have thread exited after , not skip reverttoself() call.

python - Can I avoid permission_required decorator on Django testing? -

i testing set of django applications make extensive use of 'permission_required' decorator. derives in 302 http response in of views have. my question is: there way avoid or deactivate 'permission_required' in testing, can 200 response when call views, instead of 302? thank you! just log in superuser in test case setup method django.test import testcase django.contrib.auth.models import user class testthatneedslogin(testcase): def setup(self): user.objects.create_superuser( 'user1', 'user1@example.com', 'pswd', ) self.client.login(username="user1", password="pswd") def teardown(self): self.client.logout() def test_something(self): response = self.client.get("/") self.assertequal(200, response.status_code)

html - Style attribute in <td> tag not working in Firefox -

i have html table , trying add gradient using style attribute on <td> . works in ie, not firefox, opera, or chrome. <td height="100%" width="10%" valign="top" style="filter:progid:dximagetransform.microsoft.gradient(startcolorstr='#6487db'‌​, endcolorstr='#003366', gradienttype='0');" > </td> how can work in firefox, etc.? this: filter:progid:dximagetransform.microsoft.gradient(startcolorstr='#6487db'‌​, endcolorstr='#003366', gradienttype='0'); is ie specific code. shouldn't work in other browsers. see css3please ways of doing in other browsers (that support css3). edit: copied link posted , modified correct colors background-color: #6487db; background-image: -webkit-gradient(linear, left top, left bottom, from(#6487db), to(#003366)); /* saf4+, chrome */ background-image: -webkit-linear-gradient(top, #6487db, #003366); /* chrome 10+, saf5.

asp.net - A process serving application pool '{0}' suffered a fatal communication error with the Windows Process Activation Service. How to get crash dump? -

i have live standalone server running windows server 2008 sp2 (64bit) , iis7. running asp.net website built against .net 3.5 in own application pool. randomly @ different times of day, above error. may occur once per day, or more. when occurs, occur 2 or 3 times in relatively quick succession. looking @ processes , logs leading crash there appears no real pattern or specific scenario causing it. from searches, recommendations appear to crash dump , analyse it, struggling one. i have debug diagnostics 1.2 installed, , have tried various crash rule setups, not create userdump. have 'crash rule iis/com+ related processes' default advanced configuration. can suggest why isn't creating crash dump when issue occurs? there way crash dump? edit: have installed debugging tools according useful link , running adplus using command: adplus -crash -pn w3wp.exe -o c:\adpluscrashdump hopefully crash dump when reoccurs . . . edit 2: found recursive method call, caused

c# - How can I compare the content of two files of different types? -

i've documents in mhtml format , in pdf format. want know whether content same or not in mhtml , pdf. how can compare difference? you need mhtml parser pdf parser library. traverse both documents in parallell , compare contents. not non-trivial have build mapping system between elements in different file formats. if want take account content can written in different ways (e.g. tables vs. tabs) , still same user things complicated quickly. my gut feeling way asking questions project way larger , more complex ready for.

c# - Changing wave format at runtime with NAudio -

i have initialized device using: static iwaveplayer waveout; static waveformat waveformat; static bufferedwaveprovider waveprovider; private static int audiodeviceinit() { waveout = new directsoundout(); waveformat = new waveformat(44100, 2); waveprovider = new bufferedwaveprovider(waveformat); waveout.init(waveprovider); waveout.play(); return 0; } i adding pcm stream using: waveprovider.addsamples(samples, 0, size); the above working fine long stream data of same configuration. i have function receives sample rate , number of channels , want reconfigure waveprovider use newly provided configuration. here code using: private static void audioconfigcallback(int rate, int channel) { waveformat = new waveformat(rate, channel); waveprovider = new bufferedwaveprovider(waveformat); waveout.init(waveprovider); return; } this not working , believe not correct way of doin

c# - mysterious runtime error in applying a template to wpf window -

i have hard problem dealing template. please me. app.xaml <application x:class="wpfapplication1.app" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> //note didn't set startupuri in application tag please. <application.resources> <style targettype="window" x:key="mywindowstyle"> <setter property="template"> <setter.value> <controltemplate> <grid> <rectangle fill="gray" radiusx="30" radiusy="30"/> <contentpresenter/> </grid> </controltemplate> </setter.value> </setter> </style> </

java - Axis2 problem with concurrent requests mismatch response object -

i'm facing problem on production server web service concurrent requests. the problem when web service receives (for instance) 2 requests 2 different methods (each method returning different object) in same service, web service return object type of second request. to replicate , problem create simple web service 1 service , 2 methods same environment of production server. code ( requestmethods.class ) package test; import beans.request1response; import beans.request2response; public class requestmethods { public request1response request1() { request1response output = new request1response(); try { thread.sleep(10 * 1000); } catch (interruptedexception e) { e.printstacktrace(); } output.seterror_code(1); output.seterror_msg("message1"); return output; } public request2response request2() { request2response output = new request2response(); output.se

Adding actions to Capistrano tasks -

how can add capistrano's deploy task? need create symlink in "public" directory. create new task create symlink, use hook add task capistrano deploy workflow appropriate. e.g. namespace :deploy desc "symlink file" task :symlink_file, :roles => :app run "ln -s file public/file" end end after 'deploy:update_code', 'deploy:symlink_file'

javascript - Why document.cookie is not working -

var curcookie = name + "=" + value + "; expires=" + ats_getexpire() + "; path=" + path + "; domain=" + domain ; document.cookie = curcookie; alert("your cookie : " + document.cookie); when use above code alert message coming empty. why document.cookie coming empty. please answer. see here live example you're using ; instead of , . use , deliminate cookie values var curcookie = name + "=" + value + ", expires=" + ats_getexpire() + ", path=" + path + ", domain=" + domain; document.cookie = curcookie; alert("your cookie : " + document.cookie);

iphone - Proper way to convert BOOL value into INT? -

everytime when tried convert bool value int. int value showing -8 true , 0 false. ideally should return 1 true. i have tried possible ways of conversion like int val=info.isattachementdownloadable; int val=[[nsstring stringwithformat:@"%d", info.isattachementdownloadable] intvalue]; int val=(int)info.isattachementdownloadable; where info.isattachementdownloadable return bool in ways showing -8 true. any suggestion ? maybe help(thought don't know why may needed in first place) nsinteger = @(yes).integervalue; hope helps you.

asp.net mvc - MVC3 Validation with Entity Framework Model/Database First -

i want use mvc 3 , entity framework application. the model stored in different assembly mvc app. the choice i'm making either use ef generate entities or use code first. with code first, can decorate members [required] etc... how go adding attributes if ef has generated entities db? having ef generate entities save lot of time, want mvc auto populate validation depending on how i've decorated members. make sense? if so, how that? in case, metadatatypeattribute used. can combine partial classes achieve desired results and way, in place more research when deciding between using database first , code first designs. not saving time when generating entities, there's more difference between 2 approaches. time saving purpose, can use ef power tools generate code first entities database - simple.

algorithm - To check whether a tree is binary or not -

given (n-ary) tree. how check whether binary or not? how check whether binary or not? check if every node has @ 2 children. some untested (!) pseudo-code: struct ntree { root: node boolean isbinary() { return isbinary(root) } private boolean isbinary(node n) { if (n has no child) return true elif (n has 1 child) return isbinary(n.children[0]) elif (n has 2 children) return isbinary(n.children[0]) && isbinary(n.children[1]) else return false } struct node { children: list } }

java - How to record/use selenium handling combobox and choose item used by dijit? -

is easier way using selenium click on combobox written dijit , choose item list? source: <div id="widget_ofertaform_offerelements_1_" class="dijit dijitreset dijitinlinetable dijitleft areastd dijitcombobox" tabindex="-1" wairole="combobox" dojoattachpoint="combonode" dojoattachevent="onmouseenter:_onmouse,onmouseleave:_onmouse,onmousedown:_onmouse" role="combobox" style="width: 420px;" widgetid="ofertaform_offerelements_1_"> <div style="overflow: hidden;"> <div class="dijitreset dijitright dijitbuttonnode dijitarrowbutton dijitdownarrowbutton" dojoattachevent="onmousedown:_onarrowmousedown,onmouseup:_onmouse,onmouseenter:_onmouse,onmouseleave:_onmouse" wairole="presentation" dojoattachpoint="downarrownode" role="presentation"> <div class="dijitarrowbuttoninner">&thinsp;</div> <div cl

java - How to Identify Publishers and Consumers using Red5 API -

public boolean connect(iconnection conn, iscope scope, object[] params) { iclient client = conn.getclient(); log.info( "app connect " + conn.getclient().getid() ); client.setattribute( "stamp", new long( 0 ) ); return true; } this method being called every time client connected @ custom application in red5 server ,so there way identify if client subscriber (consumer ,viewer) or publisher (user streams @ server). bests to disallow or allow publish or subscribe user, can use methods inside appstart callback method: registerstreamplaybacksecurity registerstreampublishsecurity for more, the: http://dl.fancycode.com/red5/api/org/red5/server/adapter/multithreadedapplicationadapter.html i'm using jruby, , it's easy so: registerstreamplaybacksecurity |scope, name, start, len, flush| false # no playback allowed end registerstreampublishsecurity |scope, name, mode| rand(1) % 1 == 0 #

moles - value generation in pex parmeterized unit test -

i'm building unit testing using pex. problem not code branches being tested, pex keep generating parameter values fails same condition make code after condition not run. my method goes this: public void setup(dbsyncscopedescription syncscopedesc, basicinfo info, string dbcontext = "mydbcontext") { // <pex> contracts validation // </pex> string localdbconnstr = string.empty; //this condition never parameter results in true if (iscontextexist(dbcontext)) { localdbconnstr = configurationmanager.connectionstrings[dbcontext + "context"].connectionstring; } else { throw new missingfieldexception("dbcontext not exist"); } // part never being reached provisionlocalscope(syncscopedesc, info.farmid, localdbconnstr); info.tables = getsynctablesassynctableinfo(syncscopedesc); adminorm.create(

java me - Eclipse workspace ? I have a problem when Eclipse start -

i have problem eclipse. use eclipse on linux code j2me program. choose workspace different default workspace, , set eclipse show dialog choose workspace every start. create j2me project , run it, close when done. when re-start eclipse, eclipse don't show workspace diaglog ! choose default workspace: /home/username/workspace ! try re-start, re-install lot, still not work right way. can me ? ! you should able choose in windows > preferences > general > startup , shutdown > workspaces, , check "prompt workspace on startup" edit : off course, if not work expected, it's bug, can submit it...

php - How do i make sure that my mail($to,$subject,$msg); delivers the mail -

my computer has got apache installed(localhost), made signup option, , there email option send mail activation of account. have internet connection, if in php script, write mail($to,$subject,$msg); code deliver mail desired recepient because not sending it. there no way 100% sure email received recipient. the mail() function returns value depending on whether there problem sending email or not. this: $successful = mail($to,$subject,$msg); if (!$successful) { // email not sent } if value of $successful false server had issue sending email. add code , see happens. if $successful true server sending email ok , problem may lie spam filters receiving email , deleting it. can learn more how prevent in this question .

php - Transfer form data from a form to an external form -

i trying find way can have user fill out small form on site , on submit link external form (that have no control over) , populate information has been entered. is possible? initial though using javascript append information url how retrieve it? maybe using iframe? any appreciated! edit: wanted clarify. tthe fields of external form autopoulate information entered on site visitor enter other info dont need. can curl? it's possible in javascript. if know output in 'external submit' can filter , print out on site. it's ajax related. another way curl, php. regular expression can filter out information need on own site.

javascript - JSONRequest.get unresponsive -

i trying send requests google places api code: <script type="text/javascript" src="json2.js"> var googlequery; function load() { googlequery = jsonrequest.get( "https://maps.googleapis.com/maps/api/place/details/json?reference=3af0d044d45cd8587d9a3522bc98a95d4f60c6a8&sensor=true&key=xxxxxxxxxxxxxxxx", function (googlequery, value, exception) { if (value) { processresponse(value); } else { processerror(exception); } } ); } </script> and calling load function in body onload. <body onload="load()"> </body> i including src="json2.js" in <script> instead of in own <script> , since getting "jsonrequest undefined" error...but still getting strange "load undefined" error. am going json request correctly? try: <script type="text/javascript" src

php - unable to connect mysql database after working long -

i not able connect mysql database after working approx 5 hours on mysql database... cache problem or type of limit i blank page... static html only $hostname_localhost = "localhost"; $database_localhost = "akhai"; $username_localhost = "root"; $password_localhost = ""; $localhost = mysql_pconnect($hostname_localhost, $username_localhost, $password_localhost) or trigger_error(mysql_error(),e_user_error); mysql_select_db($database_localhost); you can errors script turning on error reporting (in case isn't fatal error) error_reporting(e_all); ini_set("display_errors", 1); it give answer you can trigger error handler on mysql_connect(); mysql_connect("localhost", "name", "pass") or die(mysql_error()); are sure mysql database , running?

Mock an object in a method that is not a parameter in java similar to the following python code? -

following cool mocking python, there anyway in java? mockpath = os.path mockpath.isdir = mock(return_value=false) myobj = myclass() myobj.invoke_some_method() myobj.some_other_method.assert_called_with(false) is possible in java? meaning updating return values , behavior of objects instantiated inside other object methods in such convenient way? framework nicely? thanks mockito supports partial mocks mocking out method in real class . latter looks more similar python example. i believe easymock supports same thing i'm having trouble finding in documentation.

vb.net - Cannot Debug In Visual Studio -

i have form in vb.net project , when try debugging - there nothing going on besides form being loaded - error: no symbols loaded call stack frame. source code cannot displayed. i've tried using this solution stackoverflow , either oudated or pertains c++. i've tried using this article msdn forum , however, did not seem wasn't quite sure answer telling me do. has else came across problem , found solution? it's frustrating i'm receiving error , have form showing up. edit: found solution here don't quite know means ... yet. going i'd know why doesn't work when application framework enabled. make sure running in debug , not release. build>configuration manager>active solution configuration = debug

jquery fullcalendar : operation after data add -

when add event jquery fullcalendar (in selectable mode)on click or selecting dates. how read added event in jquery ? edit - after comment think must use select function: select: function(start, end, allday) { var title = prompt('event title:'); if (title) { alert('start:'+start+' end: '+end); calendar.fullcalendar('renderevent', { title: title, start: start, end: end, allday: allday }, true // make event "stick" ); } calendar.fullcalendar('unselect'); }, look @ fiddle here, alerts start , end date, have access tile , allday parameters.http://jsfiddle.net/sybsq/

database - category text file to php array with explode -

i need import large category .txt file mysql database. text file has categories 3 levels. my text file likes example below (+/- 362 entries): business business = business innovation & ideation = innovation business = economics business = economics = global economics my database table structure: | id | cat | sub_cat | sub_sub_cat | what want do, insert categories in database php. separator between cat, sub , sub_sub cat '='. want reach loop insert data database. thanks in advice. with kind regards, nicky $lines = file('category.txt'); // slurp file , split array lines foreach($lines $line) { $parts = explode('=', $line); // decompose line individual sections $cat = mysql_real_escape_string(trim($parts[0])); // prepare sections sql $subcat = mysql_real_escape_string(trim($parts[1])); $subsubcat = mysql_real_escape_string(trim($parts[2])); $sql = "insert yourtable (cat, sub-cat, sub_sub_cat) values ('

git - Merge branches without checking out branch -

i have 3 branches. master [ live server] \ stage [ stage server test changes; merge commits ] \ dev [ local machine ] i downstream changes to. each of these branches set tracking each other. normally, downstream changes this: git checkout stage && git merge master then checkout dev , same git checkout dev && git merge stage then push them all: git push origin --all is there way downstream changes without checking out each branch? i maybe using wrong terminology. i'm not totally sure if i'm using upstream/downstream terminology correctly. you can indeed "merge" branch b branch without having check out branch a, but if it's fast-forward merge . you can use refspec fetch "merge". if merging branch b branch using git merge result in fast-forward merge, can following without having checkout a: git fetch <remote> b:a the documentation the above matches refspec fo

Is there a free C++ IDE for Linux with these features? -

list methods in class, preferably options enable/disable methods superclasses. option "go source" once select variable. i'm trying use cgal , can't make sense of whole lot documentation or compiler errors, despite using many flags possible in gcc, downloaded source code take @ try see if can find methods need. these 2 options make things lot easier. when used netbeans java had both options, maybe it'd have c++ well? or expecting out of it? or maybe ide work better? have no idea. use gedit make. i recommend eclipse cdt .

A simple socket app in Android needs some special permissions to connect through the internet? -

a simple socket app in android needs special permissions connect through internet? whats wrong code? exceptions when tryes connect input text ip, or host. package what.httpserver; import java.io.bufferedreader; import java.io.ioexception; import java.io.inputstreamreader; import java.io.outputstream; import java.io.printwriter; import java.net.socket; import java.net.unknownhostexception; import android.app.activity; import android.os.bundle; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import android.widget.edittext; import android.widget.textview; public class whathttpserveractivity extends activity implements onclicklistener { /** called when activity first created. */ @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); button button = (button)findviewbyid(r.id.button1); button.setonclicklistener(this)

c++ - unknown type name namespace in xcode (Awesomium) -

why xcode insist on "unknown type name 'namespace'" in c++ header ?!! bascially trying use "awesomium" http://awesomium.com/ sdk in mac application , keep getting "unknown type name 'namespace" in hearder files #ifndef __keyboardcodes_h__ #define __keyboardcodes_h__ namespace awesomium { any ideas? if wish use awesomium objective-c, need use ansi c api instead. more information: http://support.awesomium.com/kb/wrappers-integration/ansi-c-api if have other questions, please drop line in our support forum: http://support.awesomium.com

Starting external process in QT without command prompt in Windows -

i'm try start external process in qt qprocess.startdetached(). able start process, when see ugly windows command prompt pop up. there way prevent happening? i use method , not have problem. there applications create command prompt when started. may not qt code that's @ fault. can validate setting code start different application , checking if still creates command prompt. qstring program = "client.exe"; qstringlist arguments; clientprocess = new qprocess( ); // exit calling application on called application start connect( clientprocess, signal( started() ), this, slot( exit() ) ); // receive errors connect( clientprocess, signal( error( qprocess::processerror ) ), this, slot( error( qprocess::processerror ) ) ); clientprocess->startdetached( program, arguments );

c# - Can you use variables in their own initialization line (tryGetOrElse in a dictionary)? -

consider following code: private dictionary<robotsettings, trader> createtradersfor(ienumerable<robotsettings> settings) { var traderset = new dictionary<tuple<igateway, ibroker>, trader>(); return settings.todictionary(s => s, s => { var key = tuple.create(s.gateway, s.broker); trader trader = traderset.trygetvalue(key, out trader) ? trader : traderset[key] = new trader(s.gateway, s.broker); return trader; }); } i'm talking initialization of trader variable in closure, uses in same line being instantiated. i've been using pattern of dealing dictionaries lot lately, cause don't uninitialized variables :) , know if guaranteed compile in future. beside looking odd, there nothing wrong - technically. first, declaration of trader executed, there exists trader object without value assigned. second, trygetvalue part evaluated , returns either true or false. if ret

jquery - z-Index Issue with jqGrid and Wijmo WijMenu -

Image
i trying use jquery-based wijmo wijmenu control jqgrid in order create dynamic grid toolbar. getting menu appear works fine. however, menuitem1 has submenu, , submenu falls behind jqgrid when hover on 'menuitem1'. i've tried setting z-index on menu , individual menu items, no luck. behavior happens on ie9, chrome, ff , safari. work when turn compatibility mode on ie9, makes me think may have z-index...but i'm not sure. feel i'm missing obvious. i created jsfiddle demonstrate issue. can me submenu fall in front of jqgrid? thank in advance help/advice. it's not z-index issue. .ui-jqgrid .ui-userdata has overflow:hidden on it. try making overflow: visible. although i'm not sure if cause problems on grid when doing this.

Django: How to save a formset with a custom model form? -

trying save bunch of objects custom form: class customform(forms.modelform): class meta: model = widget complexify = models.booleanfield() when complexify checked, need complex operations on widget object. i can't do: for object in formset.save(commit=false): ... because won't have complexify flag. and going through each form seems wrong way: for form in formset.forms: ... because includes (empty) forms , deleted forms. any ideas on how done? the best answer find problem overriding save on form: class customform(forms.modelform): class meta: model = widget complexify = models.booleanfield() def save(self, *args, **kwargs): obj = super(customform, self).save(*args, **kwargs) obj.complexify = self.cleaned_data.get("complexify") return obj then available when handle them: for object in formset.save(commit=false): if object.complexify: object.do_complic

Substring() for Fields in MYSQL -

i don't understand why didn't work out: select id,name,concat(substring(description,0,30),'...') desc_shortened, created_date,added_by products even though there data inside of description field. didn't see field example on mysql documentation tho. used pure strings instead of column names. concat(susbtring(description,0,30)) returns ... , that's all. use substring(description,1,30) instead.

sockets - Implementing simple authentication on a TCP Server from NodeJS -

i sure don't understand basic concepts of tcp server , i'm not treating data streams, , worse that, might not using events well. i wanted tcp server write socket 'username: ' can type in username (on tcp client netcat or telnet), , tcp server must treat next data username. far work (although i'm sure there better ways this), , next should write 'password: ' type in password, , if it's right one, should validate credentials , more stuff... happens when type in password, writes again 'password: ' because socket.write('password: '); inside socket.on('data',function(){//etc}); here's code have far: var net = require('net'); var server = net.createserver(function (socket) { socket.addlistener("connect", function () { socket.write('username: '); socket.on('data',function(data){ var username = data.tostring().replace('\n',''); so

c++ - Why does dereferencing a string vector iterator need parentheses? -

vector<string> mystrings; vector<string>::iterator itstr; i'm using c_str() return pointer string. why need dereferenced parentheses? doesn't compile: *itstr.c_str(); error c2039: 'c_str' : not member of 'std::vector<_ty>::iterator' compiles/works parentheses around iterator: (*itstr).c_str(); if point me (no pun intended) in right direction appreciate it.thanks! . has higher precedence unary * . *itstr.c_str() if had said *(itstr.c_str()) . you can, of course, use itstr->c_str() , since (*x).y equivalent x->y (at least pointers , iterators; can, of course, overload operators own types such not consistent, you'd crazy so).

notserializable exception when trying to serialize java map converted from scala -

i have method serialize java map map<uuid,string> . works fine. can serialize , deserialize in java. but have call method scala , calling code. def customserialize:unit = { serializer.serialize(modmap(scalamap)) def modmap(oldmap : map[uuid,someobject]) : java.util.map[uuid,java.lang.string] = { oldmap map { case(k,v) => (k->v.name)} } the scala map scala.collection.map , using import scala.collection.javaconversions._ doing conversion. when run code error java.io.notserializableexception: scala.collection.javaconversions$mapwrapper @ java.io.objectoutputstream.writeobject0(objectoutputstream.java:1180) @ java.io.objectoutputstream.writeobject(objectoutputstream.java:346) it looks need 1 more conversion javaconversions$mapwrapper java.util.map . correct? there way this? personally, i'd open enhancement issue requesting these wrappers serializable. not in short term, but... have tried stuff in javaconverters instead?

.NET WPF: Problems repeatedly calling WPF form from a WinForm application -

as title states, i'm calling wpf form winform app, (with several classes on call stack between) numerous times. initially, wpf worked once. after googling, found had add shutdownmode.onexplicitshutdown wpf application create. now, after adding that, upon exiting first wpf form, control never returns 'run' call , focus given winform dialog. if exit that, control returned wpf run. winform: application.enablevisualstyles(); application.setcompatibletextrenderingdefault(false); mainform form = new mainform(); application.run(form); wpf pre-init: application = new system.windows.application { shutdownmode = system.windows.shutdownmode.onexplicitshutdown }; calling wpf form: confirmform form = new confirmform(); application.run(form); what going on here?: application.run (in both winforms , wpf) blocking call runs message loop , returns when application ready exit. you should call show() , shows form or window , returns immediately. h

ListData.svc REST issue in Sharepoint 2010 -

im having big problem in sharepoint 2010. im thinking bug in product. i need search 2 form libraries, 1 in site in english, , other in site in portuguese, listdata.svc rest service. the problem lies when try filter form library contenttype. in english library, goes well, in portuguese one, contenttype spelled "tipodeconteúdo", think breaking because of special char. here urls english: http://pc55861/_vti_bin/listdata.svc/consultas ?$filter=contenttype eq 'consultajuridico' portuguese: http://pc55861:81/_vti_bin/listdata.svc/consultas ?$filter=tipodeconteúdo eq 'consultajuridico' i tried use "contenttype" instead of "tipodeconteúdo", no avail. anyone have ideas? i hope you've found answer now, since question doesn't have answer, here goes: when query non-english site rest service need provide display names of lists , fields, this: var url = "/_vti_bin/listdata.svc/páginas?$filter=" + encodeurico

java - Run class in Jar file -

if have jar file called myjar.jar located in /myfolder , want use class called myclass it, how go doing command line? i thought go directory , java -cp myjar.jar.myclass isn't working. appreciated. use java -cp myjar.jar com.mypackage.myclass . if class not in package java -cp myjar.jar myclass . if not within directory myjar.jar located, can do: on unix or linux platforms: java -cp /location_of_jar/myjar.jar com.mypackage.myclass on windows: java -cp c:\location_of_jar\myjar.jar com.mypackage.myclass