Posts

Showing posts from August, 2014

javascript - Width of page in iframe -

i have parent page , inside parent page, there iframe around half size of parent page. the javascript in iframed page supposed size of iframed page , set size of text input, both javascript's document.body.clientwidth , jquery's $(document).width() returning parent page's width. how width of iframed page scripts inside iframe (that is, without having send iframe width parent page iframe page querystrings)? cross-domain too. simply use - <iframe src="demo_iframe.htm" width="200" height="200"></iframe>

node.js - How to produce errors\exceptions in callback functions in mongoose for testing purpose -

i working mongodb using mongoose. of opeartion works callback. error may occur while saving/updating/finding document. though can check if there error in callback function (as shown in below code) want know while developing how can generate error , test these blocks? tank.findbyid(id, function (err, tank) { if (err) return handleerror(err); tank.size = 'large'; tank.save(function (err) { if (err) return handleerror(err); res.send(tank); }); }); are familiar error class? emiting errors eventemitter ? throwing errors throw ? this link extensive overview on how deal errors in node. assuming using express, in case of example provided, create instance of error class doing like: exports.findtankbyid = function(req, res, next) { var id = req.params.id; tank.findbyid(id, function (err, tank) { if (err) { var e = new error("failed find tank"); e.data = err; // attach other usefu...

ios - How can I access the array saved in the for loop? (objective c) -

-(void) queryrestuarantsname { nsmutablearray* restaurantnamearray = [[nsmutablearray alloc] init]; pfquery *query = [pfquery querywithclassname:@"menus"]; [query selectkeys: @[@"resturant", @"description", @"name"]]; query.limit = 1000000; [query findobjectsinbackgroundwithblock:^(nsarray *objects, nserror *error) { (pfobject *object in objects) { nsstring* restaurant = [object objectforkey: @"resturant"]; [restaurantnamearray addobject:restaurant]; } }]; } currently, outside of loop, restaurantnamearray said empty. however, in loop, has objects. how can access objects outside of loop? it asynchronous code. access restaurantnamearray before receiving results findobjectsinbackgroundwithblock return empty results. so processing of data in array should happen after findobjectsinbackgroundwithblock got results. expected following code work: [self queryrestuarantsname];...

android - Selendroid wating for an element in native app -

i using selendroid test android application . working fine having couple of problems. 1 when app opened element loaded after sometime, using thread.sleep(); work around want use built in waiting conditions not @ working me. please if can answer helpful. implementing following code webelement referimage = waitforelement(by.id("imageview_close"),30,driver); referimage.click(); i got answer question after more research changed above code webdriverwait wait = new webdriverwait(driver, 30); webelement element =wait.until(expectedconditions.presenceofelementlocated(by .id("imageview_close"))); element.click();

ios - Memory leak in UIWebview when loading data content with url (WebCore::CachedResource::unregisterHandle) -

i have problem uiwebview . when loading data content url, application has crashed. occurs time in month. tired it, couldn't reappear it. occurs on client's device. please me. application run on ios7.1 exception type: exc_bad_access (sigsegv) exception subtype: kern_invalid_address" thread 2 name: webthread thread 2 crashed: 0 webcore 0x38322b02 webcore::cachedresource::unregisterhandle(webcore::cachedresourcehandlebase*) + 110 1 webcore 0x38322a8a webcore::cachedresourcehandlebase::~cachedresourcehandlebase() + 14 2 webcore 0x384b77fe webcore::memorycache::prunedeadresourcestosize(unsigned int) + 278 3 webcore 0x38396aee webcore::memorycache::prune() + 94" the following our source code. if ([defaults boolforkey:@"cacheenabled"]) { [[nsurlcache sharedurlcache] setmemorycapacity:[defaults integerforkey:@"cachesize"]]; } else { [[nsurlcache sharedurlcache] removeallcachedresponse...

XML Parsing with Javascript Display .childNodes -

xml parsing javascript display .childnodes i studying xml & javascript have problems display .childnodes , .nodevalue of , in file xml. search in w3schools.com , google unsuccessfully :( i not understand why not display data... any welcome ! thanks in advance support ! the code xml: <team id="burnley"> <team_name>burnley</team_name> <description>fundado en 1882. premierleague 2013/14</description> <city>londres </city> <stadium>burnley </stadium> <players> <person> <first_name>daniel johnson</first_name> <country_birth>inglaterra</country_birth> <position>md</position> </person> <person> <first_name>charles n'zogbia</first_name> <country_birth>francia</country_birth> <position>md</position> </person> </pl...

java - error: package com.google.gdata.client.appsforyourdomain.audit does not exist -

i find answers questions in net , more not in stackoverflow on 1 i've failed far , it's triggering first question in forum... bear me: i'm trying use google's email audit api first time. imports referred in code snippets import com.google.gdata.client.appsforyourdomain.audit.auditservice; import com.google.gdata.data.appsforyourdomain.generic.genericentry; import com.google.gdata.client.appsforyourdomain.audit.mailmonitor; i cannot find library (jar) add code fails compile cannot find these classes. i found link download audit java library when press on actual download goes page saying "no library available". i found gdata-appsforyourdomain-1.0.jar doesn't include above classes either. there couple of other questions* in stackoverflow related issue answers there didn't me how resolve it. i'd appreciate direction on missing. thanks!! *sorry cannot add links questions because stacoverflow reputation low - newbie - can post 2 l...

c# - Autofac.Extras.DynamicProxy2 v3.0.6 got a exception -

i use autofac.extras.dynamicproxy2 implement aop policy. updated autofac.extras.dynamicproxy2 v3.0.6, got exception: the component activator = lookupservice (reflectionactivator), services = [wordbook.protocols.logic.ilookupservice], lifetime = autofac.core.lifetime.currentscopelifetime, sharing = none, ownership = ownedbylifetimescope cannot use interface interception provides services not publicly visible interfaces. check registration of component ensure you're not enabling interception , registering internal/private interface type. this sourcecode: containerbuilder builder = new containerbuilder(); builder.registertype<exceptioninterceptor>(); builder.registerassemblytypes(assembly.load("wordbooklogics")).asimplementedinterfaces().enableinterfaceinterceptors(); var container = builder.build(); dependencyresolver.setresolver(new autofacdependencyresolver(container)); it works @ autofac.extras.dynamicproxy2 v3.0.5. do need adjust w...

sql - Query performing poorly (nested joins, lateral join) (PostgreSQL) -

i'm working on query touching 4 tables. schema drew in following er model: http://i.stack.imgur.com/ftscj.jpg i'm trying write query return sites sum of file sizes not exceed storage limit of associated plan. in other words, i'd know sites able create new files, once there storage available yet. the trick contracted plan can have many sites can have many files, once 1 site exceed limit, sites share same contracted plan must disabled well. after many tries, got following sql: select sites plans p inner join ( select cp.plan_id plan_id, cp.id contracted_plan_id, array_agg(s.id) sites, sum(total_size) total contracted_plans cp inner join sites s on cp.id = s.contracted_plan_id left join lateral( select sum(size) total_size files f f.site_id = s.id ) agg on true group cp.id, cp.plan_id ) total_per_contracted_plan on p.id = total_per_contracted_plan.plan_id total < p.storage_limit; currently sql seems working, notice it's not performi...

ios - Exception while registering subclass with Parse -

i have class called attendee inherits pfobject . in applicationdidfinishlaunching() method, register subclass so: func application(application: uiapplication, didfinishlaunchingwithoptions launchoptions: [nsobject: anyobject]?) -> bool { attendee.initialize() parse.enablelocaldatastore() parse.setapplicationid(objectmanager.appid, clientkey: objectmanager.clientkey) getdata() return true } func getdata() { //create query var attendeequery = attendee.query() attendeequery?.fromlocaldatastore() .frompinwithname(cachekeys.attendeeskey) .wherekey("conference", equalto: objectmanager.currentconf) //register background task var bgtask = uibackgroundtaskinvalid bgtask = uiapplication.sharedapplication().beginbackgroundtaskwithexpirationhandler({ () -> void in uiapplication.sharedapplication().endbackgroundtask(bgtask) bgtask = uibackgroundtaskinvalid println("attendees loader ...

c# - Upload CSV with UTF-8 Characters to Server -

i'm able upload csv content browser server, non-ascii characters "š" in string "pštrossova" come out "p�trossova" when parse contents on server. i'm processing file follows hoping preserve utf8 encoding, it's not working (result contains "p�trossova" want "pštrossova") // read bytes http input stream binaryreader b = new binaryreader(request.files["file"].inputstream); byte[] bindata = b.readbytes( convert.toint32(request.files["file"].inputstream.length) ); string result = system.text.encoding.utf8.getstring(bindata);

Issue with showing content from Firebase using Google Polymer Firebase element -

i have faq page reads firebase node , lists q & contents using below lines of code: <firebase-auth id="fblogin" provider="anonymous" location="https://xxx.firebaseio.com"></firebase-auth> <firebase-collection orderbypriority log id="fbfaq" location="https://xxx.firebaseio.com/faq" data="{{faqs}}"></firebase-collection> <template is="dom-repeat" items="[[faqs]]" as="faq"> <div class="forborder"> <akyral-details id="[[faq.__firebasekey__]]"> <akyral-summary>[[faq.q]]</akyral-summary> <p class="answer">[[faq.a]]</p> </akyral-details> </div> </template> i have link mainpage faq page , upon click works perfect! when go main page , click again faq link page renders nothing. if refresh page fine. to recreat...

loopbackjs - How to configure two different datasource for a model in Strongloop Loopback framework? -

our mysql database set write clusters , read clusters, there way set strongloop loopback model (e.g. user) write mysql host , read mysql host b? try use attachto() if want change datasource single model. example app.models.yourmodel.attachto(app.datasources.readds); readdata(); ... app.models.yourmodel.attachto(app.datasources.writeds); writedata(); you have define readds , writeds datasources in datasources.json file: { "readds": { "host": "hosta", "database": "dbonhosta", "username": "user", "password": "password", "name": "readds", "connector": "mysql" }, "writeds": { "host": "hostb", "database": "dbonhostb", "username": "user", "password": "password", "name": "writeds", ...

user interface - Libgdx, stage is creating duplicate widgets when run on android -

i trying display textfield on screen. works when desktop version run when run android version textfield duplicated , background messed up. screenshots code of screen class: public class setupscreen implements screen { private stage stage; private table table; private textfield paymentfield; @override public void show() { stage = new stage(); gdx.input.setinputprocessor(stage); table = new table(); table.setfillparent(true); stage.addactor(table); pixmap bgpixmap = new pixmap(1, 1, format.rgba8888); bgpixmap.setcolor(color.gray); bgpixmap.fill(); texture bgtexture = new texture(bgpixmap); pixmap cursorpixmap = new pixmap(1, 1, format.rgba8888); cursorpixmap.setcolor(color.white); cursorpixmap.fill(); texture cursortexture = new texture(cursorpixmap); pixmap selpixmap = new pixmap(1, 1, format.rgba8888); selpixmap.setcolor(color.bl...

android - Access SQLite from BaseAdapter -

i have base adapter class , want acces sqlite table cursor, have trouble context. getting context right way? public class getallentryslistviewadapter extends baseadapter { private jsonarray dataarray; private activity activity; private static layoutinflater inflater = null; public cursor cursor; private sqlitedatabase dbase; dbhelper dbh; private context context; string pos; public getallentryslistviewadapter(jsonarray jsonarray, activity a) { this.dataarray = jsonarray; this.activity = a; inflater = (layoutinflater)this.activity.getsystemservice(context.layout_inflater_service); } public getallentryslistviewadapter(context context) { this.context = context; } //... dbh = new dbhelper(context); cursor = getlikes(dbh); cursor.movetofirst(); if (cursor.movetofirst()) { { if (integer.parseint(cursor.getstring(2)) == 1) { cell.likeimage.setimageresource(r.drawable.heart_filled); ...

php - Bash seems to be executing command 2nd time when variable of captured output is used -

output=$(php -f somecommand arg1 arg2 arg3 2>&1) echo "$output" >> error.log the script runs cron. in emailed output received looks php -f ... command run twice. is run once when variable set, , again when variable echoed? don't remember behavior happening before. if happening... how program output variable without re-executing program?

django - Send emails with a new domain? -

i new emailing systems in web applications. i've built django app , i'd add send email functionality. bought domain 'mydomain.com' , want send emails 'services@mydomain.com'. possible using mandrill? edit i have domain, there's no yet email address created domain, first time in charge of , i'd know how create emails addresses , use send messages via django app , mandrill. i have working 'gmail' account, in settings have: # email default_from_email = 'myaccount@gmail.com' server_email = 'myaccount@gmail.com' email_host_user = 'myaccount@gmail.com' email_host_password = 'mypassword' email_host = 'smtp.gmail.com' email_port = '587' email_use_tls = true djrill mandrill email backend django. uses mandrill http api rather smtp, can helpful if running in environment blocks outgoing smtp ports or need extended status mandrill after sending message. otherwise, using mandrill's ...

asp.net mvc - Rendering partial view with model and property set at instantiation -

par i'm trying call partial view, passing in new model, setting property value on instantiate. the below code errors follows: 'cs1525: invalid expression term '{'' @html.partial("~/views/partials/_contactus.cshtml", new contactusmodel({thankyoupage = 555})) however if replace below, view renders without error: @html.partial("~/views/partials/_contactus.cshtml", new contactusmodel()) can spot issue? cheers your syntax wrong if want set property during instantiate activity have way: new contactusmodel() { thankyoupage = 555 } or new contactusmodel { thankyoupage = 555 }

scala - Spark Streaming MQTT -

i've been using spark stream data kafka , it's pretty easy. i thought using mqtt utils easy, not reason. i'm trying execute following piece of code. val sparkconf = new sparkconf(true).setappname("amqstream").setmaster("local") val ssc = new streamingcontext(sparkconf, seconds(10)) val actorsystem = actorsystem() implicit val kafkaproduceractor = actorsystem.actorof(props[kafkaproduceractor]) mqttutils.createstream(ssc, "tcp://localhost:1883", "akkatest") .foreachrdd { rdd => println("got rdd: " + rdd.tostring()) rdd.foreach { msg => println("got msg: " + msg) } } ssc.start() ssc.awaittermination() the weird thing spark logs msg sent in console, not println. it logs this: 19:38:18.803 [recurringtimer - blockgenerator] debug o.a.s.s.receiver.blockgenerator - last element in input-0-1435790298600 message foreach distributed act...

java - BST equality check -

i have method checks see if node of bst equal node of tree (given inside input) - regardless of structure. this have far seems missing something. public boolean samevalues(bstinterface<t> other) { if(other == null && != null) return false; else if(other.size() == 0 && this.size() == 0) return true; object temp = null; object temp2 = null; while(other.preorderiterator().hasnext() && this.preorderiterator().hasnext()) { temp = other.preorderiterator().next(); temp2 = this.preorderiterator().next(); if(temp.equals(temp2)) return true; else return false; } return false; } does know better approach this? thanks. your while() loop terminates in first iteration due superfluous return false . should rather like: while(other.preorderiterator().hasnext() && this.preorderiterator().hasnext()) { temp = other.pre...

c# - Redirect from controller during an Ajax.Actionlink call -

i'm trying redirect controller during middle of ajax.actionlink call. have ajax.actionlink so: @ajax.actionlink("send project", "registerajax", "projects", new {id = model.incidentid}, new ajaxoptions {httpmethod = "post", updatetargetid = "projectmsg_" + model.incidentid}) then in controller, have following: public actionresult registerajax(int id = 0) { string result = registerproject(id); if (result != null) { return redirectresult(result); } return content("sent..."); } private actionresult redirectresult(string result) { throw new notimplementedexception(); } if result != null , i've tried above, return redirect(result) , return view(result) , etc. , nothing gets me redirected result page (e.g. ~/views/manage/location.cshtml). i'...

JAVA invalid maximum heap size. The specified size exceeds the maximum representable size -

i have run command fix code xml file: java -xmx5g -cp .:jsoup-1.8.2.jar checksyntax test.xml > test2.xml but gives me error: invalid maximum heap size: -xmx5g specified size exceeds maximum representable size. how can make work? if jvm 32-bit cannot use switch -d64

javascript - Show Hide Functionality -

i have following button: <a href="#" class="see-more">see more <i class="fa fa-chevron-right"></i></a> when clicked toggle div show/hide effect. got part working okay. however, realized i'm going need on multiple buttons. believe need refactor current code function, i'm not sure go here. this started with: // slide toggle content $(".see-more").click(function(e){ e.preventdefault(); $(".show-more").slidetoggle('slow'); if($(this).html() == 'see less <i class="fa fa-chevron-right"></i>') { $(this).html('see more <i class="fa fa-chevron-right"></i>'); } else { $(this).html('see less <i class="fa fa-chevron-right"></i>'); } }); my first attempt didn't yield luck var seemore = $('.see-more'); function showhide() { this.preventdefault(); $(".show-mor...

Scroll JScrollPane by dragging mouse (Java swing) -

Image
i making map editor game working on. there jpanel in jscrollpane displays map edited. make when user holding down spacebar , dragging mouse in jpanel, jscrollpanel scroll along dragging. here have far: panelmappanel.addmousemotionlistener(new mousemotionlistener(){ @override public void mousedragged(mouseevent e) { //gets difference in distance x , y last time listener called int deltax = mousex - e.getx(); int deltay = mousey - e.gety(); mousex = e.getx(); mousey = e.gety(); if(spacepressed){ //scroll scrollpane according distance travelled scrollpane.getverticalscrollbar().setvalue(scrollpane.getverticalscrollbar().getvalue() + deltay); scrollpane.gethorizontalscrollbar().setvalue(scrollpane.gethorizontalscrollbar().getvalue() + deltax); } } }); currently works scrolling not smooth @ all. moving mouse lot @ time fine doi...

debugging - How does test and je/jne work -

okay started working little assembly. began following instructions: test al, al jne 0x1000bffcc using debugger, wanted code not jump address 0x1000bffcc set breakpoint on jne instruction , inverted al register using following lldb command: expr $al = 1 this worked continued until stumbled across following, similar instruction pair: test al, al je 0x1000bffcc while looks similar, inverting al register doesn't seem have affect. keeps on jumping address 0x1000bffcc . did research , figured out test runs logical and al , sets 0 flag or zf accordingly. leads 2 questions: why did invert al register in first example? why not work in second example? how can use debugger make code not jump in second example? thanks lot help! test al, al jne 0x1000bffcc the test instruction performs logical and of 2 operands , sets the cpu flags register according result (which not stored anywhere). if al zero, anded result 0 , ...

R Markdown kniter and LateX issue -

ok, running frustrating situation try display latex table via rmd(kniter) , output commented out. result shows latex code, not table. what missing? --- title: '2' author: "aaron soderstrom" date: "july 1, 2015" output: html_document --- ```{r } library('xtable') df <- data.frame(a = c(1.00123, 33.1, 6),b = c(111111, 3333333, 3123.233)) print(xtable(df, display = c("s","f","f"), digits = 4), format.args = list(big.mark = " ", decimal.mark = ",")) ``` output: print(xtable(df, display = c("s","f","f"), digits = 4), format.args = list(big.mark = " ", decimal.mark = ",")) ## % latex table generated in r 3.1.0 xtable 1.7-4 package ## % wed jul 01 15:29:02 2015 ## \begin{table}[ht] ## \centering ## \begin{tabular}{rrr} ## \hline ## & & b \\ ## \hline ## 1 & 1,0012 & 111 111,0000 \\ ## 2 &...

c++ - Afx Unsupported in Windows 10/ Visual Studio 2015 -

i retargeted mfc solution visual studio 2013 visual studio 2015, when built received error telling me compiler not find afxdisp.h found under vc->atlmfc->include . -- of course copied file vs 2013 location, wondering why missing? know? my mistake, mfc addon in vs, , did not have of (only had atl). relaunched installer went custom install , clicked mfc classes. installed multibyte mfc library visual studio website. not available in custom options.

multithreading - How can I detect when my standalone Java application was shut down? -

i have standalone java application acts consumer connects activemq queue. in application's main() method, create instance of consumer thread , start it. seeing i'm using jms this, want add shutdown hook application when application stops working (either terminated or killed), application run method wherein resources closed. i tried runtime.addshutdownhook() doesn't seem invoked whenever shut down application. i act if contextdestroyed() method of servletcontextlistener invoked. runtime.addshutdownhook() correct api use, unfortunately "stop" button in eclipse terminates process without allowing hooks run. see shutdown hook doesn't work in eclipse more information.

talend - Find jobs which use a database connection -

anyone know quick way find out jobs use database connection in talend? for example, if have database connection "db_run_prod01" defined in talend. want identify jobs access connection can recompile them if make change db_run_prod01. ideas? i'm using talend open studio on windows 7. thanks in advance, bee every talend job saved .item+other files in workspace folder under process directory. either can search using file editor in direcotry string or can user talend job read these .item files - these xml structures , can parse in talend job search required string. if open .item file able understand contains , search.

javascript - Find correct streetview from Google maps URL without using computeheading -

i using computeheading code previous answer geocodezip works fine hiccups not geocodezips fault. variable "heading" recieves computeheading result , data positions heading view google maps streetview this: var heading = google.maps.geometry.spherical.computeheading(panorama.getposition(), marker.getposition()); panorama.setpov({ heading: heading, zoom: 1, pitch: 0 }); }); however not accurate. achieve pass heading value google maps url's variable "heading". can strip out heading value, parse xml file, , echo result in infowindow on working map. if copy , paste code below can see process working @ 100%, pov (point of view) off (you need rotate street view) due computeheading, yet when try pass value of variable "newheading" "heading" not being read , pov defects default north... in other words "0". have tried "rearranging" code flow without success. i have validated code in jshint , jslint , console ther...

Derby version mismatch between Spark and Hive : Unable to instantiate org.apache.hadoop.hive.metastore.HiveMetaStoreClient -

while connecting spark(1.4.0 built hadoop 2.6.0) hive(version 1.1.0) tables exception coming due derby version mismatch. there way both(spark & hive) can use same derby version ? ...any other way fix ? caused by: java.sql.sqlexception: failed start database 'metastore_db' class loader org.apache.spark.sql.hive.client.isolatedclientloader$$anon$1@e0d0b81, see next exception details. @ org.apache.derby.impl.jdbc.sqlexceptionfactory.getsqlexception(unknown source) @ org.apache.derby.impl.jdbc.sqlexceptionfactory40.wrapargsfortransportacrossdrda(unknown source) ... 88 more caused by: java.sql.sqlexception: database @ /home/saurabh/softwares/hive1.1/bin/metastore_db has incompatible format current version of software. database created or upgraded version 10.11. @ org.apache.derby.impl.jdbc.sqlexceptionfactory.getsqlexception(unknown source) @ org.apache.derby.impl.jdbc.sqlexceptionfactory40.wrapargsfortransportacrossdrda(unknown source) @ org.apac...

startup - Problems starting Sonatype Nexus 2.11.3 -

when attempting start nexus 2.11.3 i.e. ./bin/nexus console attempts 5 times , fails. error log set @ debug level output not intuitive start trouble-shooting. perhaps others familiar of output. btw. run java jdk 1.7u1. command(0) : java command(1) : -xx:maxpersize=192m command(2) : -djava.io.tmpdir=./tmp command(3) : -djava.net.preferipv4stack=true command(4) : -dcom.sun.jndi.ldap.connect.pool.protocol=plain ssl command(5) : -xms256m command(6) : -xmx768m command(7) : -djava.library.path=bin/jsw/lib command(8) : classpath command(9) : <large list of jar files> command(10) : -dwrapper.key=<key> command(11) : -dwrapper.port=32000 command(12) : -dwrapper.jvm.port.min=31000 command(13) : -dwrapper.port.max=5939 command(14) : -dwrapper.debug=true command(15) : -dwrapper.pid=5939 command(16) : -dwrapper.version=3.2.3 command(17) : -dwrapper.native_library=wrapper command(18) : -dwrapper.timeout=10 command(19) : -dwrapper.jvmid=5 command(20) : org.sonatype.nexus.bootstrap...

I need to fit a best circle to the 3D data in matlab -

basically, have many irregular circle on ground in form of x,y,z coordinates (of 200*3 matrix). want fix best circle in data of x,y,z coordinates (of 200*3 matrix). any appreciated. i try using ransac algorithm finds parameters of model (in case circle) given noisy data. algorithm quite easy understand , robust against outliers. the wikipedia article has matlab example fitting line shouldn't hard adapt fit circle. these slides give introduction ransac algorithm (starting page 42). show examples fitting circle.

ruby on rails - Validate paramaters in Restful endpoints -

i rookie in rails restful web service , trying build service returns json dump of deals.so far app returns these deals in json format when hit http://localhost:3000/api/deals . want add 2 mandatory parameters(deal_id , title) , 2 optional parameters in uri http://localhost:3000/api/deals?deal_id=2&title=book . best way validate these 2 mandatory parameters?in other words want query if deal_id , title parameters present. assuming deal model has fields deal_id, title, description , vendor. here code controller module api class dealscontroller < applicationcontroller respond_to :json def index @deals = deal.all respond_with (@deals) end end end routes namespace :api,:defaults => {format:'json'} resources :deals end to validate presence of query parameters in rails route, can use :constraints option. so, in case, if want require presence of parameters deal_id , title , can changing: resources :deals to: resources :deals, ...

xcode c/c++ linker error: undefined symbol -

i did search problem seems trivial no 1 asked. have mixed c , c++ code. in model.h , have following declaration: void free_and_null (char **ptr); in model.cpp , have function body: void free_and_null (char **ptr) { if ( *ptr != null ) { free (*ptr); *ptr = null; } } /* end free_and_null */ in solve.c file, have following : #include "sort.h" ..... free_and_null ((char **) &x); when compile project, has following linker error: wrap) undefined symbols architecture x86_64: "_free_and_null", referenced from: why such simple program can have error? use apple llvm 6.0 compiler. input highly appreciated. you need tell c++ compiler function should have "c" linkage declaring such (in c++ source file). extern "c" { void free_and_null (char **ptr); } c++ compilers construct "mangled" names functions 2 functions same name different argument types end having different ma...

c# - WCF .NET 4.0 doesn't work without TLS 1.0 -

Image
in company work have product uses wcf on net.tcp using ssl in .net framework 4.0. in specific client, security reasons, exists requirement disable ssl 2, ssl 3 , tls 1. problem communication doesn’t work without tls 1.0. can tell me why? used iiscrypto disable above protocols. it's attached in discussion example code. steps reproduce scenario. disable protocols show in image below restart computer build solution attached execute server.exe execute client.exe it’ll show error below : caller not authenticated service guys. after many attempts, way make wcf run without tls 1.0, enabling fips. follow link https://stackoverflow.com/a/13635742/1234031 enable fips.

c# - How to serialize TreeView and DataGridView along with strings -

i have windows form application in c#. need save form data xml file. can save text in textboxes given in tutorial using strings c# tutorial - xml serialization i unable figure out how serialize treeview , datagridview same xml file. tried solution given here how serialize treeview in xml , deserialize xml treeview? unable save data single xml file. while deserializing, strings populated in treeview instead of nodes.

Random numbers that follow a linear drop distribution in Python -

Image
i'd generate random numbers follow dropping linear frequency distribution, take n=1-x example. the numpy library seems offer more complex distributions. so, turns out can totally use random.triangular(0,1,0) this. see documentation here: https://docs.python.org/2/library/random.html random.triangular(low, high, mode) return random floating point number n such low <= n <= high , specified mode between bounds. histogram made matplotlib : bins = [0.1 * in range(12)] plt.hist([random.triangular(0,1,0) in xrange(2500)], bins)

javascript - Google Sheets & Charts on HTML -

i couldn't find answer this, i'd know started in making web applications title. more have script running on google sheets dynamically updating every (5 minutes?) of various information in cells. want export data table in google chart , have dynamically update on html page. looks has been addressed google directly .

android - Elevate application rights to execute binary -

i trying package , execute native arm binaries within java android app version 4.0 (api level 15). the packaging works fine, adding shell scripts , binaries assets folder of project (using android studio), deployed apk. i follow these solutions copy assets filesystem. here first problem, seem able write getfilesdir() not e.g. /data/local/tmp/ . well, copy files application data dir (resolves /data/data/com.myapp/files/ . along process, set mode of files executable. then try execute binaries via runtime.getruntime().exec() seems work shellscripts not binaries. can use copy binaries prefered destination via cat /data/data/com.myapp/files/binary > /data/local/tmp/binary note: cp wont work, permission denied. chmod 777 works again. execution not work, permission denied. assume related how paths mounted. the whole process works when performing via adb. can see app has different user id adb, might related kernel limitations ? requesting write_external_storage . re...

c# - Change the .net framework with visual studios 2013 and the xamarin plug in -

i trying change .net framework android c# app in visual studios 2013. tried create new project .net framework 4.0 still error saying application targeting 4.5 framework. know how force this? reason doing have nuget package uses 4.0 framework, if there way nuget package use 4.5 framework equally valid solution. you cannot change .net framework android app. targeting monoandroid. you cannot use nuget package assemblies .net framework since may use parts of xamarin android api not supported. so left finding nuget package supports android projects or re-compiling source code in android library project targets monoandroid, may or may not work depending on source code does.

android - Is it possible to sort data in a textview? -

i using 'codeofaninja' . android table scroll code he generates data. replaced sqlite database. works but... need sort , displays textviews tablerows. should use listviews instead of textviews/tablerows? have seen examples of data being sorted in collection. have data in lists have read textviews have performance problems. if answer listviews have redesign views trying not do. if technology says must it. have come 2 options: 1:textview gets repopulated list after data actions. 2:listview data manipulated stored db. need put listview in relativelayout view? i have tried deleting tablerows textview , reading data in proves slow. i searched on textviews , listviews , have seen many examples still not clear method preferred. thank input. the idea sorting independent of view. sort data in collection (list, array, etc.) first, use listadapter (or arrayadapter, .etc) populate view. from described, seems textviews re-created every time, i.e, if have 10 rows, each ...

php - Sending value, get nothing -

i created ajax function sends data php file wrong because when die it, holds nothing, , know ajax function written good. here how sending it: xmlhttp.send(dop); and here how recieve in php file: $selectedlang = isset($_post['dop']) ? $_post['dop'] : ''; what doing wrong? i'am recieving info badly. coz can see parameteres in ajax function. please help, need fast. <script type="text/javascript"> function run() { var dop = document.getelementbyid("kalba").value; return dop; } function insertdata() { var dop = run(); if (window.xmlhttprequest) {// code ie7+, firefox, chrome, opera, safari xmlhttp=new xmlhttprequest(); } else {// code ie6, ie5 xmlhttp=new activexobject("microsoft.xmlhttp"); } xmlhttp.open("post","style/wps-light/datafile.php",true); xmlhttp.setrequ...

javascript - Facebook Flow Function Union Type -

i'm playing around facebook flow , wonder, why following function not type check? uses union type denoted '|'. declare var f: ((x: any) => number) | ((x: any) => string); function f(x) { if(true) { return 5; } else return 'hello'; } the checker complains: function type incompatible union type i know works when annotate like: declare var f: (x: any) => number|string; but why former annotation fail? frankly, haven't seen union types function types anywhere far, however, don't see theoretic reason why shouldn't allowed. ((x: any) => number) | ((x: any) => string) valid expression. means f can 1 of these 2 function signatures . eg. f = function(x: any): number {return 0} work f = function(x: any): string {return 'hello'} work (x: any) => number|string means return value of same function can 1 of these types dynamically, case here.

ios - POST request not receiving all json -

little issue that's been bothering me. i've been making post request aws rdb. request should return json output. issue i'm having i'll receive bytes back, contains incomplete json, converting dictionary won't work. receive null value nsdata received, can print out length of data. ideas? here's ios code requests: #import "serviceconnector.h" @implementation serviceconnector{ nsmutabledata *receiveddata; } -(void)gettest{ //send server nsmutableurlrequest *request = [[nsmutableurlrequest alloc] initwithurl:[nsurl urlwithstring:@"my_website"]]; [request sethttpmethod:@"get"]; //initialize nsurlconnection request nsurlconnection *connection = [[nsurlconnection alloc] initwithrequest:request delegate:self]; if(!connection){ nslog(@"connection failed"); } } -(void)posttest:(nsmutablearray *)carsearches{ //build request sent server nsmutableurlrequest *request = [[nsm...

java - Making a 2D grid of Sprites -

i finished first coding class (ib computer science, if helps), , decided wanted make first game. the game world have top-down view of terrain. each part of terrain made of squares (it similar way dwarf fortress looks). have been able output console, using characters stand-in graphics, course covered little on graphics work. what best way create grid of sprites or colored squares inside jpanel? have been able display bufferedimages before, have not been able align multiple bufferedimages grid. as of now, have '2d' arraylist, arraylist of arraylist, making game world. works great when use double loop , system.out.print(""); check oracle documentaion layout managers . 1 looking grid layout. if feel fancy, can upgrade javafx, , use grid pane instead.

Android ListView card behaviour -

i noticed something. when use layout inside listview use linearlayout cardview inside it. cardview has margin of 10dp , looks fine. however, when use cardview has same attributes, not give me margin @ all. there i'm doing wrong? layout 1 (gives me layout want): <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:card_view="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v7.widget.cardview android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margintop="10dp" android:layout_marginleft="10dp" android:layout_marginright="10dp" card_view:cardbackgroundcolor="@color/white" card_view:cardelevation="2sp" card_view:cardusecompatpadding=...