Posts

Showing posts from January, 2014

php - How to know whether request has come via jQuery $.ajax() -

i determine whether or not request rest api has been made jquery $.ajax() method. before answering question 1 of obvious answers of adding boolean data sent server, or adding header, not want this... obviously can achieved so: $.ajax({ data: { sentviaajax: 'true' } }); however, various reasons boolean/additional header remain hidden code. therefore, know jquery send other data in particular form server when makes request? i have tried printing out $_request array not contain other data sent. there unique headers out for? if so, reliable, in, there? jquery sends following header on non-cross-domain ajax requests: x-requested-with: xmlhttprequest so header on request.

c# - Unit Testing Methods With File IO -

i'm trying habit of writing unit tests, i've written few before they've been quite basic...i'd start making move tdd want improve quality of code (design , structure) - reducing coupling, while @ same time reduce number of regressions slip through testable build. i have taken relatively simple project work on begin with. resultant program watches folder , acts on files within folder. here typical example of code extracted project: private string restoreextension(string file) { var unknownfile = path.getfilename(file); var ignoredir = path.getdirectoryname(file) + "\\unknown"; string newfile; //we need library determining mime if (checklibrary("urlmon.dll")) { addlogline("attempting restore file extension"); var mime = getmimetype(bufferfile(file, 256)); var extension = fileextensions.findextension(mime); if (!string.isnullorempty(

RSA Algorithm (private key calculation) in bash -

looking on how calculate rsa secret key in bash script 'd' when p, q & e given. although know query has come before, seem find theoretical advice on calculation of rsa private key when p, q & e given. i trying put calculation in bash script , explanation on calculations possible in bash (with expr or bc) i found site advised following; (with 't' being totient of p*q, or rather totient of 'n') d=$(echo "((2 * $t) + 1) / $e" | bc) but seems work on specific case , did not provide correct output when trying on different cases. any on how write bash formula calculation ? from defition of rsa |e*d| = 1 (mod fi(p*q)) where fi(n) euler function so need calculate inversion of e in modulo. don't forget check if gcd(e,fi(p*q))=1 or may not find inversion of e in given modulo. you can achieve using extended euclidean algorithm. there lot of pseudocodes on web. need more help?

php - Setting up the crontab on amazon ec2 cloud (Linux server) -

i need run php file on every 2 hours, using command * */2 * * * /usr/bin/php /var/www/html/sports/webservices/rss-insert.php i using * */2 * * * php /var/www/html/sports/webservices/rss-insert.php but both not working. can me. thanks the crontab have made run every minute of every second hour rather every 2 hours. in order run every 2 hours need this: 5 */2 * * * /usr/bin/php /var/www/html/sports/webservices/rss-insert.php which run 5 minutes after every second hour e.g 2:05, 4:05... this assuming script able run. try running command portion cron hand @ command line , make sure want.

image - WPF ZoomControl and Adorners -

this first post on stack overflow, hope right. using zoomcontrol wpf extensions display image pan , zoom support: <dockpanel grid.row="1" x:name="canvas"> <controls:zoomcontrol x:name="zoomcontrol"> <canvas x:name="canvas"> <image x:name="imagecontrol" stretch="none" /> </canvas> </controls:zoomcontrol> </dockpanel> when user selects image bowse dialog, load image so: bmp = new bitmapimage(new uri(filename)); this.imagecontroul.source = bmp; i added rectangles\adorners specific locations (pixel coordinates) on image user loaded based on image processing. var r = new rectangle(); r.strokethickness = 5; r.stroke = brushes.black; r.fill = brushes.transparent; r.width = width; r.height = height; canvas.setleft(r, y); canvas.settop(r, x); canvas.children.add(r); however, rectangles not placed in expect

java - Lazy initialization Singleton class with volatile variable -

this question has answer here: what point of making singleton instance volatile while using double lock? 5 answers i came across singleton class {lazy initialization}. code below // singleton reference class private static volatile fileproperties instance = null; public static fileproperties getinstance() { if (instance == null) { synchronized (fileproperties.class) { if (instance == null) { instance = new fileproperties(); } } } return instance; } my question benefit getting making instance volatile since taking care of thread safety synchronized. there benefit of volatile in scenario ? that because double-checked locking without volatile not thread-safe in java. the simplest way make thread-safe lazy-

web platform installer - Unable to Install Webmatrix -

Image
error occurs microsoft web platform installer couldn't find product tried install. either link clicked incorrect or may overriding feed different feed the link microsoft webmatrix not work. when web installer tries download , error occurs: microsoft web platform installer couldn't find product tried install. either link clicked incorrect or may overriding feed different feed. i error when try install microsoft webmatrix [www.microsoft.com/web/webmatrix/‎] on window 7 os. can help! could post log file %localappdata%\microsoft\web platform installer\logs\webpi - try find log file matches date/time when clicked link , got error message - thanks chris

php - salesforce not expected object returned calling query -

i using sforce-php toolkit objects salesforce. have following code: $mysforceconnection = new sforcepartnerclient(); $mysoapclient = $mysforceconnection->createconnection(soap_client_basedir.'/partner.wsdl.xml'); $mylogin = $mysforceconnection->login(username, password.security_token); $query = "select firstname contact"; $response = $mysforceconnection->query($query); $queryresult = new queryresult($response); foreach ($queryresult->records $record) { print_r($record); echo "<br/>"; } and expect objects returned in form: stdclass object ( [type] = contact [id] = array ( [0] =&gt; 003i0000009gzvzaao [1] =&gt; 003i0000009gzvzaao ) [firstname] = "some string" [any] = <sf:firstname>some string</sf:firstname> ) so can firstname of object $record->firstname but is: stdclass object ( [type] = contact [id] = array ( [0] =&gt; 003i0000009gzvzaao

html - CSS Inliner in Javascript (premailer) -

i use ckeditor 4 , want filter html content insert style directly in html elements mailchimp css inliner ( http://beaker.mailchimp.com/inline-css ). have in javascript must, idea? i can use jquery , prototypejs. i can't use external api. my test jsfiddle ckeditor (on paste) : http://jsfiddle.net/epokk/utw8k/7/ in : <style> .test { outline: 1px solid red; } </style> <div class="test">hello</div> out : <div style="outline: 1px solid red;">hello</div> i find solution : http://tikku.com/scripts/websites/tikku/css_inline_transformer_simplified.js trick opens tab , blocked default in firefox ... api solution : http://premailer.dialect.ca/ i created simple css styles inliner - styliner . it works on firefox , chrome. may work on ie9+ , safari 6, haven't tested yet. version not need new window - uses iframe (so may not work on ie - needs tricks make iframes work :). it lacks suppo

ruby on rails - Integrating ROR community engine to my existing app -

am trying integrate community engine application.but showing dependency error.i tried correct dependencies,but not integrating. c:\sites\example>bundle install omniauth fetching source index https://rubygems.org/ have requested: omniauth = 0.3.2 bundle has omniauth locked @ 1.1.4. try running `bundle update omniauth` c:\sites\example>bundle install omniauth fetching source index https://rubygems.org/ have requested: omniauth = 0.3.2 bundle has omniauth locked @ 1.1.4. try running `bundle update omniauth` please me integrating one.

python - When trying to run a method, get 'NoneType is not callable' -

i'm new programming please gentle. on past few days or i've messed around code trying work, , i've done lot of research (well, lot me guess) in , out of stackoverflow, won't repeating question billionth time. also, apologies poor , difficult read code. i'm doing teach myself using classes , methods. the problem somewhere between return self.rm3 in rm1 method, , code rm3 itself. my code this: from sys import exit random import randint def death(): print 'you "dead", guess.' exit(0) def inp(prompt='what do? '): to_return = raw_input(prompt).lower() if to_return == 'q' or to_return == 'quit': print "bye now~" exit(0) else: return to_return class rooms(object): def __init__(self): current_room = self.rm1 self.items = [] while true: current_room = current_room() def rm1(self): print "=== in room 1 ==="

java - double field type declaration as zero -

what significant difference between following 0 double variable declaration: 0.0 vs 0d double d1 = 0.0; double d2 = 0d; i understand both these better 0 ,because more obvious code reader. however 0.0 vs 0d difference not clear me. there no difference. have @ java language specification, section 3.10.2 decimalfloatingpointliteral: digits . digits opt exponentpart opt floattypesuffix opt . digits exponentpart opt floattypesuffix opt digits exponentpart floattypesuffix opt digits exponentpart opt floattypesuffix ... floattypesuffix: 1 of f f d d both decimalfloatingpointliteral , first 1 type 1, second 1 type 4

tomcat - How to make Glassfish use different configuration for every application -

i using glassfish, jboss, tomcat application servers. i want use different log4j.properties applications on local, dev, test , prod envirment. every project's application should have different log4j.properties file. for example: local don't want log4j send mail on test env send email x@domain.com on prod send email y@domain.com. on other example: project x send mail : -dapp_conf_dir/projectx/log4j.properties project y don't send mail : -dapp_conf_dir/projecty/log4j.properties how can it? by way using jenkins(hudson) re/deployment. thanks. sample log4j.properties file project x: log4j.rootlogger = debug, console, file_out_debug, mail # email appender log configuration log4j.appender.mail=org.apache.log4j.net.smtpappender #defines how othen emails send log4j.appender.mail.buffersize=100000 log4j.appender.mail.smtphost=10.11.12.13 log4j.appender.mail.smtphost=smtp.domain.com log4j.appender.email.smtpusername=user@domain.com log4j.appender.email.smt

How do I make a TabularInline required in Django admin? -

i want tabularinline field in django admin required. how proceed? here's code: admin.py class schoolinline(tabularinline): model = school.labs.through = 1 class laboratoryadmin(modeladmin): inlines = [schoolinline] register(lab, laboratoryadmin) i simplified lot problem, that's it. in result drop-down list schools. problem field isn't required, want required. how can simple way? forms.py # 1 form required django.core.exceptions import validationerror django.forms.models import baseinlineformset class atleastoneformset(baseinlineformset): def clean(self): super(atleastoneformset, self).clean() non_empty_forms = 0 form in self: if form.cleaned_data: non_empty_forms += 1 if non_empty_forms - len(self.deleted_forms) < 1: raise validationerror("please fill @ least 1 form.") forms.py # first form not empty , can not deleted django.forms.models impor

c# - SQL Server CE Incompatible Database Version -

i have sql server ce 4.0 database ( .sdf file) , when trying doing query on database application (wpf) following error. incompatible database version. if compatible file, run repair. other cases refer documentation. [ db version = 4000000,requested version = 3505053,file name = \?\c:\database\shortagereport\mrpdatabase.sdf] i have checked sql server ce 4 sp1 installed. i have tried creating database in both database.net 4 , in connection setup in vs2012. i'm running windows 7 64bit my connection string stored in app.config . i using sql server compact toolbox generate context , mappings. my app.config : <connectionstrings> <add name="databasecontext" providername="system.data.sqlserverce.4.0" connectionstring="data source=c:\database\shortagereport\mrpdatabase.sdf"/> </connectionstrings> any ideas? add reference version 4.0 system.data.sqlserverce.dll ado.net provider then i

system calls - valgrind give error when printing the second line to file -

i'm using valgrind find faults in code. command use valgrind --leak-check=yes ./a.out and compile code -g code alone. many errors pointing single write line (the 3 printed values initialized , defined). write (22,*) avlength, stdlength, avenergy all conditional jump or move depends on uninitialised value(s) error. said line second line bunch of lines printing single file. @ end of errors, 2 more, 1 pointing line opening file resstep = int(conf*100/iterate) if (resstep.lt.10) write (resfile, "(a5,i1)") "res00",resstep elseif (resstep.lt.100) write (resfile, "(a4,i2)") "res0",resstep else write (resfile, "(a3,i1)") "res",resstep endif open (unit=22,file=trim(resfile),status='replace', c action='write') resstep integer. error syscall param w

multithreading - Creating/Using FileStream Thread Safe -

in application when write text files (logs, traces, etc), use tfilestream class. there cases write data in multithreaded environment, steps: 1- write cache data 2- each 1000 lines save file. 3- clear data. this process repeated during processing. problem description: with 16 threads, system throws following exception: access violation - file in use application. guess happening because handle used 1 thread not closed yet, when thread needs open. i changed architecture following: (bellow new implementation) in previous way, tfilestream created filename , mode parameters, , destroyed closing handle (i wasn't using tmyfilestream) tmyfilestream = class(tfilestream) public destructor destroy; override; end; tlog = class(tstringlist) private ffilehandle: integer; firsttime: boolean; fname: string; protected procedure flush; constructor create; destructor destroy; end; destructor tmyfilestream.destroy; begin //do not close handle, yet! fhandl

ldap - Active Directory: Map a domain user with a username from ForeignSecurityPrinciple group and check if user is part of another specific group -

i have problem: try authenticate user against active directory uses foreignsecurityprinciple map users different domains. we have several groups stored inside single domain , users coming different domains. the problem have here cannot real user name foreignsecurityprinciple. we tried use guidelines here: http://www.brandonclaps.com/?p=57 but no luck. when tried edit entry group had 3 members, found next member field: cn = s-1-5-21-other numbers, cn=foreignsecurityprinciple; dc=domainname, dc=local do have other solutions retrieving username against active directory using foreginsecurityprinciple ? is there recommendation using that? thanks lot in advance

javascript - Why we can't call methods of Date() class without new operator -

this question has answer here: difference between date(datestring) , new date(datestring) 9 answers suppose define variable this var today = date(); console.log(today.getmonth()); // throw error while other class error class call methods without new operator. function factorial(x) { if(x <= 1) throw error("x must not negative"); return x*factorial(x-1); } also wrapper objects (number, boolean, string) can call methods without new operator. so, class require new operator or object creation technique before calling methods. edit: date() string type, should call methods without creating objects. because string type behave if objects. why not? edit 2 : think core function cannot same new date() other functions ( array(), string(), error() etc). so, it's hidden feature of language or ecmascript mistake. ecmascript language sp

php - jQuery max value of fields and min in form -

i'm little bit new jquery have questions: i have form 2 links can add 1 field , remove 1 field. but problem want stop @ 10 fields, max can add 10 fields? the second problem how can stop @ minimum 1 field, right it's deleting every field 0 if click remove time? last question how can do, when press submit button, want remember how many fields on before pressed submit? i hope can me, it's need quick :-d jquery: var = $('input').size() + 1; max = 10; $('#add').click(function() { $('<div><input type="text" class="field" name="dynamic[]" value="some text..." /></div>').fadein('slow').appendto('.inputs'); i++; }); $('#remove').click(function() { if(i > 1) { $('.field:last').remove(); i--; } }); html: <a href="#" id="add">add +1</a> | <a href="#" id="remove">remove -1&l

codeigniter - PHP - concatenate string from database -

i have string send email registration. string stored in database. when load string model. //string db hi {$email} , bla bla bla my controllers example. function (){ $text = $this->some_model->get_string(); // var post $email = 'foo@mail.com' echo $text; } and there no change whatsoever in string. str_replace cant output this. hi foo@mail.com, bla bla bla what if case. have 2 or more string replace? example hi {$email}, {$username} php doesnt magically check each string if contains code can execute. if string in database contains hi {$email} , bla bla bla php leave that. so need manually override values in string match values. safest way simple str_replace <?php $string = 'hi {$email} , bla bla bla'; $email = 'foo@example.com'; $output = str_replace('{$email}', $email, $string); $output = str_replace('{$username}', $username, $output ); echo $output; //hi foo@example.com ,

google maps - Cannot read property 'Query' of undefined -

in code snippet ` 1) function gvizselect(tableid) { 2) var uri = "select geometry " + tableid + " name = 10095"; 3) var querytext = "http://www.google.com/fusiontables/gvizdata?tq=" + encodeuricomponent(uri); 4) var query = new google.visualization.query(querytext); 5) query.send(getdata); 6) } ` i have confirmed querytext url produce proper response set when browsed directly; line 4 generating following error; "uncaught typeerror: cannot read property 'query' of undefined." here complete html file demonstrates error receiving <!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>indianatrails.com</title> <script type="text/javascript" src="http://www.google.com/jsapi"></script> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sens

c# - Binary serialization, IFormatter: use a new one each time or store one in a field? -

using binary formatting 1st time in .net c# code msdn this: iformatter formatter = new binaryformatter(); stream stream = new filestream("myfile.lvl", filemode.create, fileaccess.write,fileshare.none); formatter.serialize(stream, globals.currentlevel); stream.close(); just wondering should store iformatter in field in class , use on , on again or should above , instantiate new 1 every time save/load something? i noticed not idisposable . there's little overhead in re-creating binaryformatter , of properties sets in constructor enum s, see here (thanks reflector): public binaryformatter() { this.m_typeformat = formattertypestyle.typesalways; this.m_securitylevel = typefilterlevel.full; this.m_surrogates = null; this.m_context = new streamingcontext(streamingcontextstates.all); } if going re-use though, you'd need synchronize access serialize , deserialize methods keep them thread-safe.

windows - Determine the caller process of a Win32 function -

is there way determine process has called win32 function. need hook few functions , in addition need determine process has called function. done hooking functions findnextfile() , winsock functions send() , receive() using ms detours problem later part i.e. determining caller process. kindly help. your hook run in context of calling process, may call getcurrentprocessid or similar function returns need know process.

javascript - Code only working in IE9 standards, Any way to downgrade? -

the code not work untill manually hit f12, hit document mode: ie9 standards , decides work.(and need fix target audience otherwise hitting f12 100 times day, thats annoying. ) know ie crap sadly have no choice in matter, , target audience doesnt take seconds time change ie9 standards. code (its bookmarklet) javascript:(function(){ a=document.createelement('script'); a.setattribute('src','//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js'); document.body.appendchild(a); data='[["#txtapplicantlname","agrawal","text"],["#txtapplicantfname","aayush","text"],["#txtfather","ranjan","text"],["#txtmother","neelam","text"],["#txtpincode","452010","text"],["#txtphone","2147483647","text"],["#txtemail","aayush@mail.com","text"],[&qu

python - Syntax error on server -

i've following line in python: out = {"response": {"status": 200, "message": status_codes["200"], "data": { article }}} in machine runs ok(python 2.7) syntax error on production server(python 2.6.6). do have ideas of be?, don't see problem is. don't use set syntax { item } , use set([item]) . code should read out = {"response": {"status": 200, "message": status_codes["200"], "data": set([article]) }} note set syntax curly brackets has been added in python 2.7. if want support lower versions, you're therefore bound use older version.

c# - How to stop a ListBoxItem from being selected if the data related to the previous one is incorrect? -

i have listbox when clicked displays data user. if user enters invalid data , click item in list want prevent listboxitem clicked being selected. however, listboxitem_selected event firing after listboxitem being selected, don't know how stop next list box item being selected. in listboxitem_selected event, i'm validating data point it's late. simply executing ((listboxitem)this.listbox.items[previousindex]).isselected = true; or this.listbox.selectedindex = previousindex; does not work, i.e. next list item still selected. how can prevent next item being selected if data entered invalid? so best way bind listbox enabled bool in code. something this public bool enabledornot { get; set; } <listbox isenabled={binding enabledornot}>... then when validation on first input can set bool , enable or disable needed. another way use validationrules. know use these in our code @ work arcane me understand. know somehow validate before els

xaml - Swipe-select on a GridView Item in MVVM -

i have gridview want able swipe-select items or click on them. as wanted work mvvm click handled command on button root of item in gridview. in following simplified example of this: <gridview itemssource="{binding source={staticresource groupeditemsviewsource}}" isswipeenabled="true" padding="116,0,40,46"> <gridview.itemspanel> <itemspaneltemplate> <virtualizingstackpanel orientation="horizontal"/> </itemspaneltemplate> </gridview.itemspanel> <gridview.itemtemplate> <datatemplate> <button command="{binding clickedcommand}" /> </datatemplate> </gridview.itemtemplate> </gridview> my problem swipe won't recognized long have button in itemtemplate. command on button seems receive gestures , doesn't allow swipe-select item. when i doesn have same problem or idea how

plsql - PL/SQL Case Statement - IS NULL -

i have sql, far add of statement in question, trying improve in order drive out system slowdowns. in part of pl/sql there and exists clause contains and not exists clause. both of these clauses contain case statements. after end part of case statement, there either is not null or is null statement. having used pl/sql years first time have seen syntax , freely admit not understanding it. whole of and exists clause displayed below, , appreciated. and exists ( select distinct projectid milestone_history mh, project_milestone pm mh.milestoneid = pm.id , mh.projectid = pr.id , ((upper(pm.description) = 'final build invoice instructions issued') or (upper(pm.description) = 'feasibility study required') or (upper(pm.description) = 'project complete')) , (case when upper(pm.description) = 'feasibility study required' actual end not null ,

simple form - Rails simple_form Nested Model Fields Won't Render -

i'm using rails 3.2 , simple_form build application. i'm trying have each nested model display it's fields in different tab using twitter bootstrap. reading stack overflow questions people seemed recommend cocoon gem i've installed too. i'm trying follow example on cocoon site ( https://github.com/nathanvda/cocoon ) reason it's not working. (could problem in translation of slim standard rails). here code, i'm doing best strip out pieces aren't relevant. here models: class superrequest < activerecord::base attr_accessible (all of fields) has_many :prisms accepts_nested_attributes_for :prisms class prism < activerecord::base attr_accessible :access, :business_client, :sla belongs_to :super_request my form follows: <%= simple_form_for @super_request, :html => {:class => 'form-horizontal'} |f| %> <div class="tabbable"> <!-- required left/right tabs --> <ul class="nav nav-tabs">

Continuous deployment to Azure from TFS 2012 Update 2 -

i not using tfs service (preview/online). running tfs 2012 update 2 on-site , trying deploy azure service contains web , worker role. i'm using azure sdk 2.0. i have tried endlessly deployment working "azurecontinuousdeployment.11" template. however, effort , read on web, seems template applies when using tfs service (online/preview) , not on-premise tfs. i have ventured down path suggested http://blogs.msdn.com/b/tomholl/archive/2011/12/06/automated-build-and-deployment-with-windows-azure-sdk-1-6.aspx , http://www.justaprogrammer.net/2012/10/18/continuous-integration-with-windows-azure-sdk-1-7-powershell-and-tfs-build-too/ article. started process, have nothing working yet. however, when looking @ steps required do, can't , pause moment , think "is there better way?". on tfs 2012 update 2, tfs preview has been out for, there must easier way this. what suggested steps/processes required continuous push of azure solution out cloud part of tfs?

java - Difference bewteen using TableRowSorter with getColumnClass and without getColumnClass -

i sorted data table in java. both sort getcolumnclass , without getcolumnclass done. what's difference between them? all the getcolumnclass() method required implementations of tablemodel ; table without getcolumnclass() not possible. "is used jtable set default renderer , editor column," may required refresh rows changed due sorting. number of times called unspecified. if suspect implementation problem, should profile application.

django - Argument of type 'NoneType' is not iterable when trying to update a model object -

getting error argument of type 'nonetype' not iterable , can't figure out why. it happens @ line if model_form.is_valid(): views.py def update_model(request, pricemodel_id): """ update part given id. """ pricemod = part.objects.get(id=pricemodel_id) if request.method == "post": print "post request" model_form = priceform(request.post, request.files, instance=pricemod) model_form.is_update = true if request.user == pricemod.adder: #from ipdb import set_trace; set_trace() if model_form.is_valid(): forms.py class priceform(modelform): # price form: form associated part model def __init__(self, *args, **kwargs): super(priceform, self).__init__(*args,**kwargs) self.is_update=false choices = unipart.objects.all().values('manufacturer').distinct() def clean(self): if self.cleaned_data , 'modelname&

excel - can I add a mime type to a javascript encodeURIcomponent response? -

i generate excel file visible data in table have. i generate so: $("#data_table tbody tr").filter(":visible").each(function(i,t){ //iterate through rows , collect data location.href='data:application/download,' + encodeuricomponent(data); }); is possible define mime-type response opened excel? solution requires browser "save as:" in order open excel. (note: rendering not great either in csv, might skip solution altogether , go through server side). now easy :) i had copied code somewhere else, , while editing bit create post, started looking better @ it. location.href containing mime type! solution is: location.href='data:application/vnd.ms-excel,' + encodeuricomponent(data)

How can I get a list of all files *I* have committed to Git (GitHub repo) after a certain date? -

the list should include creation, modifications, , deleted files. the closest can come question like git log --no-merges --stat --author="name" --pretty=format:"%c(yellow)%h%creset - %ad%n" which show file revision history specific user, grouped commits. if want see simple name-only list, suggest using h0tw1r3's answer related question: can git tell me files 1 user has modified? git log --no-merges --stat --author="pattern" --name-only --pretty=format:"" | sort -u

What does <- mean in Java? -

i ran across example , realized don't understand what's going on here if (a <- b) { return false; } what <- in java? see in way: if (a < -b) { return false; } there no <- operator in java. related, i've found question: what "-->" operator in c++?

hibernate - Object is not an indexed entity or a subclass of an indexed entity -

i doing web app hibernate, hibernate search, lucene , tapestry. now, ok, until have deployed part of code app. keep getting error render queue error in setuprender[index:layout.listarticles.grid]: failure reading parameter 'source' of component index:layout.listarticles.grid: java.lang.object not indexed entity or subclass of indexed entity even though have denoted article class @indexed annotation specified. may cause issue? may inherited classes cause issue, since article top of many other subclasses, , hs or lucene can't provide polymorhic search or what? stuck on half hour now. appreciated. in advance. public class listarticles { @property @suppresswarnings("unused") private article article; @inject private session hibernate; @sessionstate // changed applicationstate @property private user user; @property private boolean ifuserexists; private static logger logger = logger.getlogger(listarticles.class);

javascript internet explorer byte order mark -

i working on way save html table csv file. ideally, should cross-browser, , have gotten work on internet explorer. however, have gotten obvious parts working. remains unable working csv file javascript because byte order mark prepended data wish download. i have confirmed case downloading csv file in ie , else , used hex editor view raw file, can confirm file internet explorer downloaded prepends unicode character "fffe". please see code below this. savetable takes "<a>" node located inside table. if can me disgnose issue , offer solution i'd grateful. please forgive faux pas on part, don't think i've ever used site of nature before. if need me provide further information please let me know , shall best on here. function findtable(node) { // finds nodes parent table. return (node.nodename !== "table") ? findtable(node.parentnode) : node; } function savetable(node) { var csv = []; var table = findtable(node); var row

plsql - oracle dynamic sql using params with brackets as table name -

i have table in schema brackets in name (that's legacy, cannot modified): create table "addresses" ("id" number(*,0) , "fulladdress" nvarchar2(100), "homenum" nvarchar2(25), "streetname" nvarchar2(50) ) so want have ability update table via dynamic sql. that's how attempt that: declare sql_upd_statement varchar2(500) := ''; table_name varchar2(20) := '"addresses"'; column_name varchar2(20) := '"fulladdress"'; begin --no rows updated, sample sql_upd_statement := 'update stm.:1 set :2 = substr( :2, 2 ) :2 not null , :2 null'; dbms_output.put_line( sql_upd_statement ); execute immediate sql_upd_statement using in table_name, column_name; end; please, tell me, possible reach want via dynamic sql? tried set 'table_name', 'column_name' val

'Errno::ENOENT no such file/directory' intermittently with FactoryGirl & RSpec/Rails -

getting bizarre error on rspec tests, intermittently, on different examples. pass 99.999% of time (and did until hour or ago) leading me believe there's crazy going on spork setup. maybe? the recent relevant failure (but it's happening intermittently on lots of different examples, ever 1 @ time on file of ~60 examples) failure/error: @person = create(:person) errno::enoent: no such file or directory - /users/jon/code/help-me-write/tmp/cache/cached-slugs%2fpeople%7c081706ccee3f19f01752ba7b60dec0f901a746fe4e3f8c00b70ee6671669c80220130514-24434-1byq6eq # ./spec/controllers/ideas_controller_spec.rb:153:in `block (3 levels) in <top (required)>' here's gist whole file (which don't important in case), , spec_helper.rb (which think is) https://gist.github.com/jongd/854669388bec56f69910 annoying - rerunning tests or restarting guard/spork makes failing example pass fine. how can stop bug happening?

javascript - Get JSON object from server-side Python into client-side Django template -

server-side, in python, i'm returning json object looks this: contactaddr = {'name' : name, …} contactaddrjson = json.dumps(contactaddr) client side, i'm using django's template engine dump string javascript variable, , turning object this: var _myaddressobj = '{{ contactaddrjson|safe}}'; var adrobj = $.parsejson(_myaddressobj); this worked fine, until got name had single-quote in it. i've spent past couple of hours trying figure out these levels of string escapes damn object javascript, no avail. need robust single , double quotes. can enlighten me? brain smoking. you can skip parsing process. json data syntactically valid javascript, can put directly source: var adrobj = {{ contactaddrjson|safe}};

jquery - Saving array in PHP Sessions -

this question has answer here: using php $_session variable store large amonts of data 2 answers would saving large array in php session hard on server? "large" array, mean array has perhaps 500 elements each element having 100 fields. i have thousands of users doing process several times / minute. first, brief intro session handling in php: when open session, cookie created contains id of session, , sent client. php use path defined in session.save_path save file using id filename ( reference ). what mean in case? means you'll creating additional bottleneck (disk i/o 1 of slowest things in setups) because you'll writing/reading files time. database servers have tons of code handle kind of latency, might beneficial use table in database has serialized array string, keyed id in $_session .

javascript - Need help identifying this code -

what written in, , how can convert html? http://pastebin.com/eppxkhmp i need edit it, not sure how convert html. need style it, not sure how start. thought markdown not. maybe coffeescript, thought javascript. need convert coffeescript javascript javascript something? i'm bit lost. developer not available comment right now. cheers! it angularjs template can build coffeekup(as said, , linked, in answer), you'll need angularjs reuse it! angular script angular dynamic templates

c++ - arbitrarily sized enum values -

i'm compiling code written gcc, in visual c++ 2012. i'm getting warnings thrown enum value truncation following enum (due value being outside range of int): enum tile_flags { tile_flag_inner_flame= 0x10000000ull, tile_flag_constricted= 0x20000000ull, tile_flag_mimic_inept 0x2000000000ull tile_flag_mimic 0x4000000000ull tile_flag_mimic_raven 0x6000000000ull tile_flag_mimic_mask 0x6000000000ull } when compiling x86, appear msvc truncates enum values fit in 32bits. however, no truncation occurs in gcc. happening on gcc? , how can make work msvc? from n3485, § 7.2/6: for enumeration underlying type not fixed, underlying type integral type can represent enumerator values defined in enumeration. if no integral type can represent enumerator values, enumeration ill-formed. implementation-defined integral type used underlying type except underlying type shall not larger int unless value of enumerator cannot fit in int or unsigned int. if

c++ - compiling multiple files with -D option using gcc -

i have project multiple .cpp , .h files. have file called globals.h included in .cpp files. when compiling file use -d options. these options affect files not globals.h. in makefile had use same -d options when compiling every file. of course when removing options "undefined" errors arise. this means every time change 1 of these options have recompile whole project. there way let me compile globals.h these options? this part makefile: lines create globals.o : globals.o : $(globalslib) $(globalsinc) g++ -c -wall $(codedefined) $(userdefined) $(globalslib) -std=c++0x -o globals.o $(globalslib) , $(globalsinc) paths files globals.h , globals.cpp $(codedefined) , $(userdefined) -u , -d options code creating .o file: nt_fft_decomp.o : $(globalslib) $(globalsinc) $(nt_decomplib) $(nt_decompinc) g++ -c -wall $(codedefined) $(userdefined) $(nt_decomplib) -std=c++0x -o nt_fft_decomp.o (nt_decomplib) $(nt_decompinc) paths files. notice had add sa

java - How do I get a random word from a string? -

i want create hangman game in java, i'm unsure on how set whole thing up. working on system more letters have, have less chance of appearing on hangman puzzle. import java.ultil.scanner; public class hangman { public static void main(string[]args); // let's try main? scr = newscanner(system.in); // used keyboard input string words = "hi:bye:hello:cheese:puppies"; int length = words.length(); } } how can random word variable, "words", , calculate it's length? please keep in mind, i'm not best @ coding java. this answers part picking random word , finding length. string words = "hi:bye:hello:cheese:puppies"; string[] wordsasarray = words.split(":"); int index = new random().nextint(wordsasarray.length); string randomword = wordsasarray[index]; system.out.println("random word: '" + randomword + "'. of length: " + randomword.length());

html - How to fix image to bottom right in gallery -

Image
i have gallery working fine, want add image in bottom right of gallery have: i know css solve it: #container_logo { position:fixed; right:0; bottom:0; margin:0; width:75%; height:75%; background:url(http://blog.logobee.com/free-logo1.jpg) no-repeat bottom right; background-size:100%; } but how add current code? i tried adding line background:url(http://blog.logobee.com/free-logo1.jpg) : #containingdiv { width:100%; margin:0 auto; padding:0px 0 0 0; background:url(http://blog.logobee.com/free-logo1.jpg) no-repeat bottom right; } but not showing in right place... how change container code has fixed image @ bottom right? here result kindly take @ the complete fiddle take @ http://jsfiddle.net/kgk9f/5/ you need add <div id="container_logo"></div> to <div id="containingdiv"> and make few css changes... #containingdiv { width:680px; height:470px; posit

character encoding - Is it necessary to use &mdash; and &ndash; in XHTML or HTML5? -

it seems best use &amp; escape , instead of typing ampersand (&). however, should using x/html character entity references dashes , other common typographical characters when writing blog posts on cmss wordpress or hard-coding websites hand? for example: &ndash; en dash (–) &mdash; em dash (—) what risk if not? why hyphen (-) never written &#45; typed directly keyboard in html? (assuming hyphen, , not minus sign .) the w3c released official response when use , when not use character escapes can find here . group in charge of html specification, think it's best follow advice. from section "when use escapes" syntax characters. there 3 characters should appear in content escapes, not interact syntax of markup. these part of language documents based on xml , html. &lt; (<) &gt; (>) &amp; (&) they mention using characters might not supported in current encoding.

c++ - error C1189: #error : WINDOWS.H already included. MFC apps must not #include <windows.h>"** -

i have project use stdafx.h precompile header. means cpp file must contain #include "stdafx.h" first include. however, in a.h, need include "afxinet.h", compiler complain this "error c1189: #error : windows.h included. mfc apps must not #include "windows.h"" this because "afxinet.h" complains when windows.h included, "stdafx.h" have windows.h included , present first include in a.cpp. this implies need somehow have "afxinet.h" included in front of "stdafx.h", "stdafx.h" precompile header , needs present first include... how can resove dilemma? if project uses mfc, should include headers in stdafx.h , not use windows.h (as included mfc); , if include windows.h, cannot use mfc. afxinet.h part of mfc, so, guess, should either (1) replace windows.h afxwin.h , "use mfc" in settings (2) don't use mfc wrappers wininet, use functions wininet.h

r - How to get column name of the variable with the top 10 highest values? -

if have data.frame(sum_clus) 600 columns(variables) , 10 rows have no na's , numeric values, how can create 5 new variables give me column names of top 5 variables in row? for eg. max <- apply(sum_clus ,1, max) for(ii in 1:10) sum_clus$max[ii] <- colnames(sum_clus)[which(sum_clus[ii , ] == sum_clus[ii, sum_clus[ii,] == max[ii]])] this above code helped me create variable sum_clus$max gives me column name of max variable in each row. similarly, how can 5 such variables give me column names of top 5 variables? sum_clus$max, sum_clus$second_but_max, , on.. thanks in advance! here's similar solution, using (i) loop instead of apply ; , (ii) rank instead of order . set.seed(1) n_i = 10 n_ii = 600 n_top = 5 df <- data.frame(matrix(runif(n_ii*n_i), ncol = n_ii)) out <- matrix("",n_top,n_i) (i in 1:n_i){ colranks <- rank(df[i,]) out[,i] <- names(sort(colranks)[n_ii:(n_ii-(n_top-1))]) } # [,1] [,2] [,3] [,4]

grails 2.2.2 platform-core-plugin No signature of method event in domain model -

i try out platform-core-1.0 rc5 plugin services events. write service in grails-plugin "listadmin": package listadmin class seco_listenservice { @grails.events.listener(topic='getentriesoflist', namespace='listadmin') def getentriesoflist(string intnallistname) { println "seco_listenservice" def liste alist = liste.findbyinternal_name(intnallistname) return alist.eintrage.tolist() } } this service should return list dropdown in other grails-plugin called "institutionadmin". want use list of service dropdown of domain-model. should mention use dynamic scaffolding. try call event in domain-model: package institutionadmin import org.springframework.dao.dataintegrityviolationexception class einrichtung { long einrichtungs_type long type_of_conzept int anzahl_gruppen int anzahl_kinder_pro_gruppe string offnungszeiten static hasmany = [rooms : raum] static constraints =

javascript - Get GMT time difference between now GMT and 1 January 2013 gmt -

i trying store time difference between 1 jan 2013 , moment save on database. smaller standard of making relative 1970 ;) both in storage , because sending clientside. as going getrelativetime() quite lot, looking simplicity. might change 1 jan 2013 date of server launch 1st of month in 2013 :d i keeping client , serverside track in gmt , on nodejs server, server unknown. researched, there solutions, many call them incorrect due , :| to offer valid answer question: var ms = new date() - date.utc(2013,0,1); but please not this. you end confusing uses system (developers, api clients, database folks, etc.) you not saving in terms of bytes think. javascript number types 64 bits (8 bytes) in memory, see here . how might save in database dependent on database platform, example, mysql datetime type takes 8 bytes, while timestamp type takes 4. range of timestamp smaller, reference here , here . you encounter negative numbers frequently, if app works dates befo

OpenCV for Android: Simple example to convert Image to Greyscale -

as starter want convert bitmap greyscale via opencv. have running, crashes hard want convert image greyscale. can out? hope snippets enough, if not can attach rest. part of java file: // convert opencv structure mat image = new mat(); mat grayimage = new mat(); utils.bitmaptomat(b2, image); // call opencv processing grayimage = converttogray (image); // convert utils.mattobitmap(grayimage, b2); jni cpp file: jniexport jlong jnicall java_com_my_sample_mainmenuactivity_converttogray (jnienv*, jobject, jlong addrrgba) { logi("converting gray."); mat *mrgba = (mat*)addrrgba; mat *_retval_; cvtcolor(*mrgba, *_retval_, cv_rgb2gray); logi("successfully finished converting gray."); return (jlong) _retval_; } it never gets logging successful having converted image. seems if bitmap not converted mat. bitmap