Posts

Showing posts from June, 2015

gruntjs - Adding a task with in a task in a gruntfile -

i have gruntfile below: concat: { options: { banner: '<%= banner %>', stripbanners: true }, one: { src: ['src/**/*.js'], dest: 'dist/<%= pkg.name %>_ac.js' }, two: { src: ['/types/**/*.js'], dest: 'dist/<%= pkg.name %>_lib.js' }, all: { } },..... , on now if register task like: grunt.registertask('basic', ['concat:all']); i want both 1 , 2 run. how shall add option in all: { // need add here include 1 , 2 both? } no need add target if you're registering task point 2 targets. do: grunt.registertask('basic', ['concat:one', 'concat:two']); otherwise if you're intending on concatenating files 1 , 2 do: grunt.initconfig({ concat: { one: { src: ['src/**/*.js'],

network programming - SIP Over TCP versus SIP over UDP [ SIP: Session Initiation Protocol ] -

what difference between sip on udp , sip on tcp? what sip on tcp means? means: sip on tcp means both sip , underlying rtp protocol use tcp or run sip on tcp , udp rtp ? which one? "sip on tcp" means "send sip messages on tcp stream". sip largely transport protocol agnostic, same protocol can run on sctp, dtls, , on. from user's perspective there's no difference. from perspective of using sip stack/writing sip application, there's little difference: sip on udp implements various reliability mechanisms (resend+backoff starters). the session descriptions may use rtp media streams, sdp not tied using rtp. may use plain tcp streams if wish, or other protocol (provided there's way of describing protocol in sdp, , useful clients understand transport protocol, of course). rtp transport protocol usually runs on udp (because timeliness more important in real-time transport protocol reliability), can run on tcp (p

java - how does a compiler knows which class need to be serialize -

if declare class serializable, how compiler know class needs serialized using serializable keyword. public class domain implements comparable<domain>, serializable{ } compiler not serialize class, need write code write/ read object output stream. if class trying serialize not implementing interface, jvm throw run time error. as marked class seriablizable implementing serializable interface, jvmwill treat serializable class. serialzable marker interface, means there no method need implemented when add interface class. marker interfaces treated specially jvm, flag class serializable.

c++ - Widgets within a QGraphicsScene -

i'm trying add qgraphicsview(qcolordialog) widget onto palette dialog, qgraphicsscene corresponding qcolordialog widget blank , of great if readers me correct mistake. qt-4.8.4-linux(centos) the graphicsview widget included in pallettedialog clrwidget::clrwidget(qwidget *parent) : qgraphicsview(parent) { sethorizontalscrollbarpolicy(qt::scrollbaralwaysoff); setverticalscrollbarpolicy(qt::scrollbaralwaysoff); setframestyle(qframe::noframe); setscene(new qgraphicsscene(this)); _dialog = new qcolordialog(); _dialog->setoption(qcolordialog::nobuttons, true); setminimumsize(_dialog->size()); setmaximumsize(_dialog->size()); qgraphicsproxywidget *proxywidget = new qgraphicsproxywidget(); proxywidget->setwidget(_dialog); //scene()->additem(proxywidget); //scene()->setscenerect(proxywidget->geometry()); scene()->addwidget(_dialog); scene()->setscenerect(_dialog->geometry()); } palettedialog constructor pale

sql server 2008 - Problems In Connection String with different Users in System for Windows Authentication -

hi connection string: windows authentication: <add name="strconnection" connectionstring="data source=murali\sqlexpress;initial catalog=ecowhisk28113;integrated security = true" providername="system.data.sqlclient;"/> i run applications in system's administrator means working correctly same application run in system's users means error. 'cannot open database "ecowhisk28113" requested login. login failed. login failed user 'murali\murali'. ' i want know whether connection string error or system settings problem... please solve bug.... thanks..... you need login ssms , grant users accessing database proper permissions database. can check opening ssms connecting sql server expanding security folder right click on logins , create new login 'murali\murali'and add new login access ecowhish28113 database. depending on type of access required need add login database roles in db well.

if statement - Smart job board top menu items restriction for user -

i'm working on smart job board script customization. here thing: i want restrict menu item guest , job seaker i'm writing follow script not working. {if $globals.current_user.group.id != "jobseeker"} {if $globals.current_user.group.id != "guest"} <li><a href="{$globals.site_url}/search-resumes/" >[[search resumes]]</a></li> {/if} {/if} can tell me i'm going wrong ? i forgot check weather user logged in or not. following code helped me hide menu item in smart-job-board {if $globals.current_user.logged_in} {if $globals.current_user.group.id != "jobseeker"} {if $globals.current_user.group.id != "guest"} <li><a href="{$globals.site_url}/search-resumes/" >[[search resumes]]</a></li> {/if} {/if} {/if} this helped me hide menu item.

node.js - How do I format jade forms? -

i'm trying refactor app use jade instead of ejs running problems setting login form. here's original form in ejs: <% if (message) { %> <p><%= message %></p> <% } %> <form class="form-horizontal" action='/login' method="post" id="loginform"> <fieldset> <div id="legend"> <legend class="">login</legend> </div> <div class="control-group"> <!-- username --> <label class="control-label" for="username">username</label> <div class="controls"> <input type="text" id="username" name="username" placeholder="" class="input-xlarge"> </div> </div> <div class="control-group"> <!-- password--> <label class="control-label"

c# - Update bound property in ItemsControl -

quick description of setup: disclaimer: code show want do. command binding instance done event triggers etc. i'm pretty sure wouldn't build, didn't want waste space. my view: <itemscontrol itemssource="{binding items}"> <itemscontrol.itemtemplate> <datatemplate> <stackpanel> <textblock text="{binding isfavorite, converter={staticresource favoriteconverter}" tap="{binding favoritecommand, commandparameter={binding}}"/> <textblock text="{binding title}"/> </stackpanel> </datatemplate> </itemscontrol.itemtemplate> </itemscontrol> my viewmodel: public class viewmodel : viewmodelbase { public ilist<item> items { get; set; } public relaycommand<item> favorite { { return new relaycommand<item>(item => {

linux - Is using timers/signals in c static libraries bad practice? -

i'm building 2 static c libraries. each of libraries have routine needs run once every second after calling mylib_init(); i implemented in each library using setitimer, uses itimer_real resource , sigalrm signal. void start1mstimer() { struct itimerval new; memset(&new,0, sizeof(new)); new.it_interval.tv_sec=1; new.it_value.tv_sec=1; signal (sigalrm, onesectimeout); setitimer (itimer_real, &new,null); } ok far working. now i'm building sample application uses both of these libraries, , conflicts arising. have realized application can have 1 handler each signal, , itimer_real can used 1 timer, not both. things not working now. what better way me implement timing in each of libraries? in general, bad idea have signal handlers inside of library? you use threads + syncronization method. instead of writing signal handler, write thread. using semaphore, can run event thread either on timeout or on demand (ie app calls libra

sidekiq - MultiJson::LoadError (795: unexpected token -

i getting kind of weird behaviour. using sidekiq background processing. whenever perform_async on sidekiqjob post data rails app, multijson::loaderror , when create instance of , call perform on works charm. don't know exact culprit. sidekiqjob.perform_async(:id => blog.id) (having multijson::load error) sidekiqjob.new.perform(:id => blog.id) (everything works fine) sidekiqjob perform method looks this: def perform(params) body = {'status' => 'completed', 'results' => result.find(params['id']).build_results} httparty.post(some_callback_url, :body => body.to_json, :headers => {'content-type' => 'application/json'}) end need direction resolve issue. adding charset utf-8 in request header resolve issue

android - ViewFlipper with just one view -

i have viewflipper contains linearlayout contains textviews. when go previous or next item (textviews updated other values), want viewflipper full animation. example fade_in, fade_out. for example: <viewflipper android:id="@+id/viewflipper01" android:layout_width="wrap_content" android:layout_height="wrap_content" > <linearlayout android:id="@+id/linearlayout1" android:layout_width="320dp" android:layout_height="435dp" android:background="@drawable/ic_launcher" android:orientation="vertical" > <textview android:id="@+id/textview01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="flipper content 1" > </textview> </linearlayout> </viewflipper> when click on ne

jquery - How to pass values from JSTree Menu to MVC controller -

i using example in - http://codemyne.net/articles/populating-treeview-with-checkboxes-using-mvc3razor-jstree-jquery.aspx?visitid=149&type=2 i want pass values of selected node controller. author of article displaying values in message box; i want show selected item's text or id in textbox in same page or pass to controller . can me it? thanks, try (untested): function getchecked(){ divid = []; $("#onflycheckboxes").jstree("get_checked", null, true).each(function () { divid.push(this.id); }); $.ajax({ url: "/mycontroller/action", type: "post", datatype: "json", data: {divids: divid}, contenttype: "application/json charset=utf-8" }) } mvc controller ( mycontrollercontroller.cs ) [httppost] public actionresult action(object[] divids=null) { //break here , view results of divids. return json("success");

android swipe on ListView doesn't get the correct row -

i using following( android swipe on list ) code detect swipe on listview, , using customcursoradapter populate listview cursor. however, when print value of row view swiped, gives me random values list , not swiped row. swipe detecetor in other question , customcusrsoradapter looks this: class customcursoradapter extends simplecursoradapter { public void bindview(view view, final context context, cursor cursor) { final swipedetector swipedetector = new swipedetector(); //holder.logrow.setontouchlistener(swipedetector); v = (linearlayout)view.findviewbyid(r.id.logsrow); v.setontouchlistener(swipedetector); } } this detects motionevent.action_down doesn't swipes left , right. ideas ?

go - Show text in the center of terminal screen in golang -

i playing golang , want create simple terminal tool (on mac, should work on linux too). need display character "x" in center of terminal window. how can detect width , height of terminal window , detect changes? a terminal package exists in go crypto repository: in particular, check out getsize function

c# - Inserting into Table 'User' with Dapper.Rainbow -

i using dapper.rainbow , have come across issue when inserting table named 'user'. i can other tables work perfectly, when try insert users table fail. i have used sql query inspector determine generated query not have [ ] around table name. once recraft query square brackets, works fine. when use table<user>(this, "[users]"); set private property likelytablename correct value ( [user] ). however database.init(dbconn,3); change likelytablename string user . i have been checking out dapper-dot-net github project , looked through database.cs source dapper.rainbow, @ loss parts of in il. is there way dapper.rainbow work table named user ?? it bad idea use reserved words table (or field, view etc) names. think causing problems. better bite bullet once , change name, fight forever. for reference, here list of reserved words (to avoid): http://msdn.microsoft.com/en-us/library/ms189822.aspx

android - What is the best way to load files from an expansion file in the NDK -

i wrote native android app use opengl es , apk expansion file because it's greater 50mb. textures in .obb file , load in java (with apkexpansionsupport). here method load image expansion public static bitmap getimagewithname(string a_path) { bitmap t_image = null; try { inputstream t_inputstream = expansionfile.getinputstream(a_path); t_image = bitmapfactory.decodestream(t_inputstream); t_inputstream.close(); } catch (exception e) { log.e(log_tag, e.getmessage()); } return t_image; } and here jni method image : bimage * wfileloader::getimage(const bstring& a_path, filelocation a_location) { ... jmethodid javamethod = env->getstaticmethodid(cls, "getimagewithname","(ljava/lang/string;i)landroid/graphics/bitmap;"); if( javamethod ) { jobject t_bitmap = env->callstaticobjectmethod(cls, javamethod, t_path, t_location); if(t_bitmap)

objective c - Core Data prepareForDeletion woes -

i'm interested how preparefordeletion works. i have pretty simple object graph. 1 class called individual , 1 class called group . relationship between them many-to-many. what have done far when delete group, check if individuals belong group belong group being deleted, if delete individuals well. it looks this: group.m - (void)preparefordeletion { //individual check: if group last associated individual, delete individual (individual *individual in self.individuals) { if ([individual.groups count] == 1) { [self.managedobjectcontext deleteobject:individual]; } } } now had idea same approach individual . is, when individual deleted check if individual deleted last 1 in group. if it's last individual group should deleted well. individual.m - (void)preparefordeletion { // group check: if individual last associated group, delete group (group *group in self.groups) { if ([group.individuals count] == 1

css - Making a table with only divs -

i want make table divs cell-1 cell-2 , cell-3: the table fluid: width: 90%; max-width: 960px; cell-1 , cell-3 fixed: width: 100px; cell-2 fluid: width: (current table width - 200px) , can smaller. just in table 2 cells fixed width , other fluid covers rest of table width. how that? thanks. while bad answer without op posting code show @ least trying something, here solution (had near ready doing): html <div class="table"> <div class="table-row"> <div class="table-cell">100</div> <div class="table-cell">fluid</div> <div class="table-cell">100</div> </div> </div> css .table { display:table; width: 90%; max-width: 960px; border:1px solid blue; /* looks */ } .table-row { display:table-row; } .table-cell { display:table-cell; border:1px solid red;/* looks */ } .table-row > .table-cell:

ruby on rails - RSpec 'change': Braces or brackets? -

i following michael hartl's rails tutorial , there rspec testing code snippet: expect click_button 'follow' end.to change(user.followed_users, :count).by(1)` according rspec documentation , how learned on codeschool , should be: expect click_button 'follow' end.to change {user.followed_users.count}.by(1) obviously both valid, there seems no documentation first way of doing change matcher in rspec documentation , wondering why/how works. i couldn't find in relish documentation either, rspec open source after all, let's dig in. in the current version of change matcher : module rspec module matchers module builtin class change def initialize(receiver=nil, message=nil, &block) @message = message @value_proc = block || lambda {receiver.__send__(message)} @expected_after = @expected_before = @minimum = @maximum = @expected_delta = nil @eval_before = @eval_after = false

Find next empty row for automatic data entry from excel userform -

private sub commandbutton1_click() nextrow = 2 sheets("data").cells(nextrow, 2) = sheets("data").cells(nextrow, 3) = sheets("sheet1").cells(nextrow, 2) sheets("data").cells(nextrow, 4) = thisworkbook.sheets("sheet1").range("b3") sheets("data").cells(nextrow, 5) = thisworkbook.sheets("sheet1").range("b4") sheets("data").cells(nextrow, 6) = thisworkbook.sheets("sheet1").range("b5") sheets("data").cells(nextrow, 7) = thisworkbook.sheets("sheet1").range("b6") sheets("data").cells(nextrow, 8) = thisworkbook.sheets("sheet1").range("b7") sheets("data").cells(nextrow, 9) = thisworkbook.sheets("sheet1").range("b8") sheets("data").cells(nextrow, 10) = thisworkbook.sheets("sheet1").range("b10") sheets("data").cells(nextrow, 11) = thiswo

angularjs - Angular js testing with Grunt -

i having problem running test in angularjs project -when run "grunt test" referenceerror: io not defined running server localy throug port 3000 wich node.js socket.io server , impliment in index.html <script src="http://localhost:3000/socket.io/socket.io.js"></script> this function testing: $scope.editproject = function (dat) { $http({ method: 'put', url: 'http://some.net/api/project/' + $routeparams.id, data: angular.tojson(dat), headers: {'content-type': 'application/json'} }) .success(function(d) { var time = $filter('date')(new date(), 'dd/mm hh:mm:ss'); var loc = '/project/' + $routeparams.id; var head = { user : $rootscope.userinfo.username, message: 'some message ', name : dat.projectname, url: loc, date: time, icon : 'icon-th-list'

c# - Calling .NET dll from native C++ -

i have problem calling .net dll ( mclnet.dll ) using com wrapper. third part dll not have source code of. want use mclnet.dll in pure native c++ application, developing c# wrapper. mclwrapper.dll , makes methods in mclnet.dll visible. here did: in mclwrapper.dll , added mclnet.dll reference, define interface make mclnet.dll methods visible. here of code: using system; using system.collections.generic; using system.linq; using system.text; using mclnet; namespace mclwrapper { public interface mclcontrol { void mclconnect(string serialnumber); void mclset_switch(string switchname, int val); void mcldisconnect(); }; public class mclcontrolclass:mclcontrol { private usb_rf_switchbox _sb = new usb_rf_switchbox(); public void mclconnect(string serialnumber)

itextsharp set bookmarks to fit page -

i'm starting out itextsharp , i've managed answer questions one: how bookmarks set open fitpage zoom/view? i apologize if has been answered elsewhere. here's code if helps. //edit: below working code. has been modified using bruno's example. public sub mergepdffiles(filelist system.collections.generic.list(of modifieditemforlist), pdfname string, pagecount integer) dim reader pdfreader dim mergedpdf byte() = nothing dim n integer dim page integer dim par paragraph dim pagemode integer dim pagelayout integer dim pagezoom pdfdestination dim outlinezoom pdfdestination dim pdfaction pdfaction dim root pdfoutline dim pdfoutline pdfoutline using ms new memorystream() using document new document() using copy new pdfcopy(document, ms) 'dim copy new pdfcopy(document, ms) document.open() root = copy.rootoutline pagemode = copy.

javascript - How to test a disconnection when testing an AJAX application? -

i'm testing ajax application need handle temporary loss of connection server or other errors (i.e. in gmail or google calendar.) what's way simulate in testing? for example, there browser plugin allow 1 temporarily "turn off" internet connection tab? debugging in chrome particularly helpful if offer suggestion browser. other options i've tried toggling network connection vm server, or shutting down server , restarting it, neither of lightweight or easy testing (the latter doesn't preserve state.) clarification: i'm not interested in how test disconnection handling in test code. want create disconnection test when running app. ideally, toggled in 1 tab of browser doesn't involve borking entire internet connection. on question, knowing framework using test thing. rest, if ajax stuff handled xmlhttprequest object, there little can do, once request has fired, cannot control anymore. if using framework such jquery, consider juking events

java - Getting JavaFX to run via Browser for Simple HelloWorld app -

i tried following various tutorials getting javafx hello world app running in browser. can't believe it's hard, i'm looking insight may have done wrong. things i've tried , resolved (to rule out obvious): had download 32-bit jre browsers , ensure using that thus using latest jre (7u21); running on win 7 64-bit checked windows control panel -> programs -> java verify jre being used signed jar file tried running local file, found drive letters weren't recognized, moved running via tomcat 6 tried various changes codebase , url hrefs, believe correct. tried in both ie 10 , chrome what ended loading .html (which references jnlp using javafx default javascript) spin while fail. if try load .jnlp file directly, exception: classnotfoundexception: javafx.application.application i verified jfxrt.jar in lib folder of jre browser using. any insight/suggestions may missing @ point? seems must obvious/basic @ point, i'm not seeing it. thanks.

c - How to trap unaligned memory access? -

i working on pet open-source project implements stream cipher algorithms , having trouble bug triggered when run on arm processor. have tried running arm binary in x86 under qemu, bug isn't triggered there. the specifics mechanisms of bug remains elusive, best shot believe caused unaligned memory access attempt made in program, fulfilled qemu, silently ignored real arm processor in development board. so, since problem showing hard diagnose, know if there tool use trap unaligned memory access made running program, can see problem happens. i use way of enabling, on arm development board, signal (sigbus, maybe?) issued if process violates memory alignment restrictions, sigsegv when accessing unmapped memory address. running linux 2.6.32. linux can fixup or warn access. you can enable behavior in /proc/cpu/alignment, see http://www.mjmwired.net/kernel/documentation/arm/mem_alignment explanation of different values. 0 - nothing (default behavior) 1 - warning in k

html, javascript: scrolling through list box items - and display prompt for each item -

so need following: when select item list box need able dynamically display additional information item in separate box. i.e. let's i'm scrolling through list of cars, each car select display price, color, mileage etc. idea similar in , feel prompt pops next element when use hovers-over. in other words ideally i'd see small box magically pops-up right next item required information. recommendations on how implement that? update: clarify i'm looking for. ended implementing responding change() event , manually updating html element defined particula purpose, 1 of answers below suggests: $('#available-elements').change(function() { var id = $(this).val(); var element = find_element(id);//retrieve complete element info $('#the_prompt').show(); $('#prompt_name').find('td').text(element.title); $('#prompt_datatyp').find('td').text(element.datatype); $('#prompt_groupcode').find('t

Spring REST: HttpMediaTypeNotSupportedException: Content type 'application/json;charset=UTF-8' -

i getting above error, due problem jackson attempting deserialize pojo. i've debugged code , returns false within jackson's objectmapper: public boolean canread(type type, class<?> contextclass, mediatype mediatype) { javatype javatype = getjavatype(type, contextclass); return (this.objectmapper.candeserialize(javatype) && canread(mediatype)); } this.objectmapper.candeserialize(javatype) returns false causes error my controller follows: @controller public class cancelcontroller { @autowired private cancelservice cancelservice; @requestmapping( value="/thing/cancel", method=requestmethod.post, consumes="application/json" ) public @responsebody cancelthingresponsedto cancelthing(@requestbody cancelrequestdto cancelthingrequest) { return cancelservice.cancelthing(cancelthingrequest); } my cancelrequestdto implements serializable: public class cancelrequestdto implements serializable{ /**

ruby on rails - Undefined paperclip method -

i getting method undefined error in rails project. method used plugin paperclip. can tell me i'm doing wrong? here beginning of picture class: require "paperclip" class picture < activerecord::base validates_attachment_content_type :photo, :content_type => ['image/jpeg', 'image/png', 'image/pjpeg', 'image/gif','image/bmp'] validates_attachment_presence :photo, :message => 'is required' belongs_to :incident belongs_to :user ... here's error: extracted source (around line #122): 119: <%= link_to 'printable', { :action => 'print', :id => @incident.id }, { :target => '_blank', :class => "button" } %> 120: <% if isviewable?(@incident) %> 121: 122: <%= link_to "pictures (#{@incident.pictures.count})", incident_pictures_path(@incident), :class => "button" %> 123: <%= link_to "suspects (#{@incident.

jsf 2 - jsf2 don't work ,url pattern -

i created application jsf2 spring , hibernate, when run obtain error : tag library supports namespace: http://primefaces.org/ui, no tag defined name: clock javax.faces.webapp.facesservlet.service(facesservlet.java:606) take inside web.xml , make sure have : <context-param> <param-name>javax.faces.default_suffix</param-name> <param-value>.xhtml</param-value> </context-param> also view files ending .xhtml now can change default extension : <servlet-mapping> <servlet-name>faces servlet</servlet-name> <url-pattern>*.jsf</url-pattern> </servlet-mapping> finally, make sure changed welcome file : <welcome-file-list> <welcome-file>index.jsf</welcome-file> </welcome-file-list> hope helps!

linux - Comparing and displaying hash values -

i able print of lines /etc/passwd uid , username. i compare values of uid , display corresponding usernames <150 , >150 . this while loop , count while(<passwd>){ chomp; @f = split /:/; sort @f; @{$passwd{$f[3]}}=@f; print @f[3 , 0], "\n"; } $count = keys(%passwd); print $count, "\n"; sort @f nothing - sort returns list sorted, not change in place. if added use warnings; programme, perl tell you. this how it: #!/usr/bin/perl use warnings; use strict; open $passwd, '<', '/etc/passwd' or die $!; %passwd; while (<$passwd>) { chomp; @f = split /:/; @{ $passwd{ $f[3] } } = @f; } $reported = 0; $k (sort { $a <=> $b } keys %passwd) { if ($k > 150 , not $reported) { $reported = print "over 150\n"; } print "$k\n"; } you can grep keys small ones: my @under150 = grep $_ < 150, keys %passwd; print $_->[0], "\n&q

datetime - Rails don't generate created_at for fixture -

i have model question "question_id", "elapsed_time", "allowed_time" , "status" fields , controller named reporting receive json containing questions , save it. ("question_id" not related of models) so far there no problem. until try run tests. i've error when rails trying load question's fixture : activerecord::statementinvalid: sqlite3::constraintexception: questions.created_at may not null: insert "questions " here's fixture : one: id: 1 question_id: mystring app: mystring guid: 1 status: 1 elapsed_time: 1 allowed_time: 1 and model : class createquestions < activerecord::migration def change create_table :questions |t| t.string :app t.integer :guid t.string :question_id t.integer :elapsed_time t.integer :allowed_time t.datetime :happened_at t.integer :status t.timestamps end end end any idea ? my model's nam

oauth 2.0 - Oauth2 in Restlet with a JAXRS Application? -

i trying create rest service (in jax-rs) restlet protected oauth2. our rest service has been written jax-rs , after investigation oauth2 implementation of restlet seems best. anyone knows how use oauth2 restlet jax-rs service (also in restlet if possible)? i have tried: jaxrsapplication.setauthenticator(new authenticator() { public boolean authenticate(request request, response response) { oauthauthorizer auth = new oauthauthorizer("http://localhost:9090/oauth/validate"); return auth.authorize(request, response); } }); but doesn't seem work.

Replace Text in jQuery -

html: <textarea></textarea><br /> <a href="#">generate</a> <span id="output"></span> jquery: $('textarea').bind('keypress', function(event) { var charcode = event.which; var keychar = string.fromcharcode(charcode); return /[a-za-z ]/.test(keychar); }); var replacements = { 'a': '1', 'b': '2', 'c': '3' } $('a').click(function() { $('textarea').val(function(i, val) { val = val.split(''); $.each(val, function(i, e) { val[i] = replacements[e] ? replacements[e] : e; }); return val.join(''); }); return false; }); http://jsfiddle.net/sta75/ how can modify existing code display replacement in $('span#output'); ? , side question, modifications can made make code more efficient? here solution display replacement in #outp

java - Kryonet connection successful but not receiving messages -

hi using kryonet network library game i'm developing. i've got code in server side: public class myserver { kryo kryo; server server; connection connection; public myserver(){ server = new server(); server.start(); try { server.bind(59990, 59900); } catch (ioexception e) { system.out.println("fatal error"); } kryo = server.getkryo(); kryo.register(message.class); server.addlistener(new listener() { public void received (connection con, message str) { system.out.println("message recieved client server"); message m = (message)str; system.out.println(m.text); } public void connected(connection con){ system.out.println("hey, connected!"); connection = con; con.sendtcp("hola cliente!!"); }

c# - Binding my changing data context in WPF -

i've seen slight variations on request - i'm having hard time getting work situtaion. have application user selection of combobox drive event. grabs data database , want bind data ui. thought had binding set correclty, can't happen. can see code calculation firing correctly, don't see feedback regarding binding. i'm pretty new wpf , still trying wrap head around (i come mvc web world) pointers appreciated. thanks. mainwindow code behind: public mainwindow() { initializecomponent(); datacontext = new mainwindowviewmodel(); } private void cboallclients_selectionchanged(object sender, selectionchangedeventargs e) { mainwindowviewmodel vm = datacontext mainwindowviewmodel; listclient selectedclient = e.addeditems[0] listclient; credit.calc c = new credit.calc(); c.calccredit(selectedclient.clientname); vm.ffcredits = c.fundfamilycredits; vm.fundcredits = c.fundcredits; datacontext = vm; } main window xaml (abbreviate

time series - d3.js and nvd3.js how to show graph for number of clicks on a website -

i want give user flexibility choose datetime range , see graph of number clicks during period. range 1 year, 6 month, 1 month, 1 week , 1 day or last 6 hours... @ point of time there 1 click. so, dataset : time click 2012-01-01 01:00:00 1 2012-01-01 02:00:00 1 2012-01-01 03:10:00 1 2012-01-01 03:20:01 1 2012-06-02 11:00:00 1 2012-12-01 01:00:00 1 2013-05-01 12:00:00 1 the graph should able adjust it's x-axis per data available it. example if checking days data should show hh:00 range , if looking week data should mon-tue-wed range. my sample code looks this: `chart.xaxis.showmaxmin(false).tickformat(function(d) { return d3.time.format('%x')(new date(d)) }); chart.yaxis.tickformat(d3.format(',.2f')); d3.select('#chart1 svg') .datum(jsondata) .call(chart);` how handle aggregation of data point? have provide data set agg

css - How to use Twitter Bootstrap correctly ( adding styles )? -

i trying figure out bulletproof way of using bootstrap correctly. here example: <style><!-- own class in separate stylesheet --> .myclass {border:1px solid #666;} </style> <!-- , structure made bootstrap --> <div class="container"> <div id="fullbox" class="row-fluid"> <div id="halfbox1" class="span6"> life </div> <div id="halfbox2" class="span6"> good! </div> </div> </div> this create 2 containers in row equal width and: 1.) style container (fullbox), give background, shadow , border; if wrap around fullbox container myclass (my styled div), work. in case myclass has 1px border, brake bootstrap layout 2 pixels both horizontally , vertically adding 1px border around. <div class="container"> <div class="myclass"> <di

entity framework - AddOrUpdate throws "A foreign key value cannot be inserted" with one to many relationship -

my application targets .net 4.5 , uses entityframework 5.0, sql server compact 4.0. i'm trying seed database entities, keeps throwing: "system.data.sqlserverce.sqlceexception: foreign key value cannot inserted because corresponding primary key value not exist. [ foreign key constraint name = fk_dbo.user_dbo.account_accountkey ]" here simplified version of domain entities: public class account { public int accountkey { get; set; } public string name { get; set; } public icollection<user> users { get; set; } } internal class accountmap : entitytypeconfiguration<account> { public accountmap() { this.haskey(e => e.accountkey); this.property(e => e.accountkey).hasdatabasegeneratedoption(databasegeneratedoption.identity); this.property(e => e.name).isrequired(); } } public class user { public int userkey { get; set; } public string name { get; set; } public account account { get; s

c# - Copy key values from NameValueCollection to Generic Dictionary -

trying copy values existing namevaluecollection object dictionary. have following code below seems add not accept keys , values strings idictionary<tkey, tvalue> dict = new dictionary<tkey, tvalue>(); public void copyfromnamevaluecollection (namevaluecollection a) { foreach (var k in a.allkeys) { dict.add(k, a[k]); } } note: namevaluecollection contains string keys , values , want provide here method allow copying of generic dictionary. it doesn't make sense use generics here since can't assign string s arbitrary generic type: idictionary<string, string> dict = new dictionary<string, string>(); public void copyfrom(namevaluecollection a) { foreach (var k in a.allkeys) { dict.add(k, a[k]); } } although should create method create new dictionary instead: public static idictionary<string, string> todictionary(this namevaluecollection col) { idic

java - Make a JDialog sit until user has disposed properly -

i extended jdialog , made modal, etc. how make not return dialog until user has selected ok button or cancel , dialog has been disposed? i don't want add thread , have spinning. want wait until user disposes. you can override setvisible() function, , check status before allow setvisible(false); .

Rails, sprockets, google closure and advanced opts -

i've added closure-compiler gem gemfile , set config.assets.js_compressor = :closure in config/environments/production.rb file. i believe defaults using simple_optimizations compilation level , wondering if there config variable can set somewhere specify advanced level instead. i tried digging through sprockets code haven't found way pass options js_compressor yet. check out issue: https://github.com/rails/rails/issues/2693 to put in simple terms, given solution is: # config.assets.js_compressor = :closure require 'closure-compiler' config.assets.js_compressor = closure::compiler.new(compilation_level: 'advanced_optimizations')

java - Trouble with using a simple boolean -

sorry if stupid question, im new , trying hand. code stuck....after point, program ends, no matter whether 1 or 2 selected. know simple im missing....any input appreciated. have copy , pasted section in think problem lies below. system.out.println("is information correct? enter 1 if correct, , 2 change"); scanner inputcorrect = new scanner(system.in); int pick = inputcorrect.nextint(); boolean iscorrect = false; while (iscorrect = false){ while (!(pick == 1) && (!(pick ==2))) system.out.println("that not valid entry please try again"); if (pick == 1){ iscorrect = true; } if (pick == 2){ system.out.println("enter 1 change name, 2 change age or 3 change gender"); scanner inputchange = new scanner(system.in); int change = inputchange.nextint(); if (change ==1){

apache camel - ActiveMQ starts to fail in Fuse Jboss when a feature is deployed -

im having problem when deploy feature. feature contains 3 bundles, , karaf deploys these bundles, when deployed activemq starts having problems. the deployed bundles simples. "complicated" camel route expose cxf endpoint , call endpoint mock. attached threar .kar, zip of kar , fuse log. service running, problem activemq happend the error same: 2013-05-14 15:19:48,046 | info | vemq broker: amq | activemqservicefactory$$anon$1 | ? ? | 106 - org.springframework.context - 3.1.3.release | refreshing org.fusesource.mq.fabric.activemqservicefactory$$anon$1@33c91e: startup date [tue may 14 15:19:48 art 2013]; root of context hierarchy 2013-05-14 15:19:48,048 | info | vemq broker: amq | xbeanxmlbeandefinitionreader | ? ? | 105 - org.springframework.beans - 3.1.3.release | loading xml bean definitions file [/home/ramiro/tecplata/jboss-fuse-6.0.0.redhat-024/etc/activemq.xml] 2013-05-14 15:19:48,095 | i