Posts

Showing posts from May, 2012

LWJGL 3 change OpenGL context / ContextAttribs alternative -

in lwjgl 2 use older profile of opengl that: pixelformat pixelformat = new pixelformat(); contextattribs contextatrributes = new contextattribs(3, 2) //<-- .withprofilecore(true) .withforwardcompatible(true); display.setdisplaymode(new displaymode(width, height)); display.settitle(window_title); display.create(pixelformat, contextatrributes); in lwjgl 3 there no display class anymore, how can there? use glfwwindowhint contextattribs : glfwwindowhint(glfw_context_version_major, 3); glfwwindowhint(glfw_context_version_minor, 2); glfwwindowhint(glfw_opengl_profile, glfw_opengl_core_profile); glfwwindowhint(glfw_opengl_forward_compat, glfw_true); then glfwcreatewindow(width, height, title, 0, 0) glfwwindowhint can change options found in pixelformat , , defaults different may want to. you need call glfwinit() before of this. more complete guide can found here: http://www.lwjgl.org/guide

How to proxy secure web services (HTTPS SSL/TLS) using Mule's <pattern:web-service-proxy> -

we have cxf web services running locally accessed across https tls/ssl. we'd expose these services externally using mule's <pattern:web-service-proxy>. our question is, can <pattern:web-service-proxy> configured use https? we have proxied these services across http using <pattern:web-service-proxy>. however, when change web-service-proxy's inboundaddress , outboundaddress attributes (below) http urls https urls error: "the required object/property "tls-key-store" null". this works: <pattern:web-service-proxy name="unsecure_ws_proxy" inboundaddress="http://localhost:80/services/service_common_name" outboundaddress="http://localhost:8080/app_name/proxied_service_name" /> this not work (produces "the required object/property "tls-key-store" null "): <pattern:web-service-proxy name="secure_ws_proxy" inboundaddress="https://localhost:443/ser

C# - How to specify generic type constraints for multiple level of inheritance hierarchy? -

i have following class hierarchy public class entitybase<t> t : entitybase<t> { //nothing interesting here } public class benefit : entitybase<benefit> { //again, nothing interesting here } public class seasonticketloan : benefit { //nothing interesting here } now have got following interface public interface iquery<t> t : entitybase<t> { } when try build following class compilation error public class employeesquery : iquery<seasonticketloan> { } i error saying seasonticketloan class not satisfy constraint. the benefit class should have generic type - parent classes have "ultimate" /sealed type generic type. "ultimate"/sealed types have no generic arguments. the result in parent classes way through root parent class generic argument contains type of "ultimate"/sealed class , no errors arise. public class entitybase<t> t : entitybase<t> { //nothing interesting he

SML: syntax error: replacing FUN with VAL -

i trying write function in ml works loop (yes know not how language supposed work). here code far: fun (f:int->unit) start_i:int end_i:int = let fun for2 (f:int->unit) start_i:int end_i:int i:int = if i=end_i - 1 f else (f i; for2 f start_i end_i (i + 1)) in for2 f start_i end_i start_i end but sml (and ocaml too) giving me error: test.ml:1.2-1.5 error: syntax error: replacing fun val test.ml:2.6-2.9 error: syntax error: replacing fun val so, there wrong function's signature. can't find is. can me? thanks not sure if compiles in ocaml (is f#) version of interactive not complaining is: let rec for2 (body: int->unit) istart iend = if istart = iend () else body istart; for2 body (istart+1) iend

java - Jena; How to check A subClassOf B without iterating A super classes nor B sub classes -

let's have ontology manipulated jena , 2 ontology classes ( ontclass ), , b. there method check a subclassof b without iterating through super classes , checking if b among them. without iterating b sub classes , checking if among them. mean a.issubclassof(b) the best place check documentation. (actually, using ide has support autocompletion make easy find, too.) in case, documentation ontclass has 2 methods you're asking for. it's not issubclass , rather hassubclass(resource) . there's hassuperclass(resource) . instance, check whether subclass of b, do: ontclass = ...; ontclass b = ...; a.hassuperclass(b); // have b superclass? b.hassubclass(a); // b have subclass?

loopbackjs - Node.js periodic tasks with clustering -

i'm running strongloop's loopback api server in production mode. means master process creates many workers, how many cores cpu has. master process controls workers , never execute code. my purpose execute periodic task once @ time, because runs on 4 workers. is there suggestions, except cron or 'key lock' in redis-like storage? in iojs , node v0.12 possible exclusive socket binding . used form of locking similar filesystem based approach. method same both: attempt exclusive access resource if success: perform task else: not perform task with sockets this: net.createserver().on('error', function(err) { console.log('did not lock', err); }).listen({ port: 4321, exclusive: true }, function() { singleprocesstask(); this.close(); }); note exclusive: true required cluster mode because defaults sharing sockets. similarly fs.open : fs.open('lock.file', 'wx', function(err, fd) { if (err) { console.log

image processing - Detect corner coordinates of a non-convex polygon in clockwise order MATLAB -

Image
i have images includes both convex non-convex polygons. each image contains 1 polygon. need detect corner coordinates , need sort them in clock-wise or counter-clockwise order. convex polygons, use harris corner detection detecting corners , convexhull sorting points. dont have idea on how sort non-convex polygon. inputs images, think image processing technique might sort them out moving alongside edge of polygon. there way least complexity? example image: i have named corners randomly. expected output: i expect corner coordinates in order 1 3 5 9 4 2 8 7 6 10 or 1 10 6 7 8 2 4 9 5 3 . can start @ point, not 1 edit 1: after rayryeng's solution, works convex polygons non-convex polygon, there non-convex polygons doesn't go algorithm. here example another approach use bwdistgeodesic find order corners distance along edge. should work polygon can detect continuous edge. we start loading in image stack overflow , converting black , white imag

sql server - How to restore a differential backup made under a different database name? -

i did full backup of database. restored database on server, different name. did differential backup. now want restore database using management studio. both backups checked default, accept default options. message appears: you cannot select backup sets different databases this same database, name different. if had made full backup, right after restoring database, have no problem. didn't. how restore differential backup? you can restore differential backup using transact-sql. first analyze contents of backups: restore headeronly disk = 'l:\temp\1\pusta.bak' then restore backups in 2 steps: restore database pusta disk = 'l:\temp\1\spplus_pusta.bak' file = 1, norecovery go restore database pusta disk = 'l:\temp\1\spplus_pusta.bak' file = 2, recovery go i found answer on russian forum sql.ru , thank you, pr0ger .

Android images gridview -

the code display images sd card , whatsapp in app when run code pictures displayed there random whitespaces between photos , photos not of same size. how resize image ? heres code main activity: import java.io.file; import java.util.arraylist; import android.app.actionbar; import android.app.activity; import android.content.context; import android.graphics.bitmapfactory; import android.os.bundle; import android.os.environment; import android.provider.mediastore; import android.view.window; import android.widget.baseadapter; import android.widget.gridview; import android.widget.toast; public class mainactivity extends activity { private imageadapter imageadapter; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); gridview gridview = (gridview) findviewbyid(r.id.gridview); imageadapter = new imageadapter(this); gridview.setadapter(imageadapter); string externa

java - Android How to find original apk on the system partition -

using packagemanager i've got applicationinfo apps filtered applicationinfo.flag_updated_system_app. know sourcedir points me current apk location, need original system apk location. there non hack way this... or have list apks on system , find right one? to clarify, let have /data/app/com.google.apps.maps-1/maps.apk want know update /system/app/maps/base.apk all apk files can found in data/app folder on device, need root permission in order access system files.

c# - Is there a way to make the Splitter resize immediately on drag, instead of waiting for mouse up? -

i need way make splitter resize instantly when mouse drags. default shows ugly dot pattern preview , doesn't show resize until let go. i've seen immediate resize behaviour in outlook, instance. .net framework provide way implement this? i have apparently customized behaviour of splitter container in project. welcome code : class ribbonsplitcontainer : splitcontainer { private color topgradientcolor = color.fromargb(89, 135, 214); private color bottomgradientcolor = color.fromargb(0, 45, 150); private color notchcolor = color.fromargb(40, 50, 71); private color notchshadowcolor = color.fromargb(249, 249, 251); private color notchtouchcolor = color.fromargb(97, 116, 152); private ushort nbrnotches = 9; private int diff = 0; private bool drawborderbottom = false; private bool drawbordertop = false; private bool drawborderleft = false; private bool drawborderright = false; [defaultvalue(typeof(color), "89,135,21

android - Are ActiveAndroid .save() operations executed on the main thread or asynchronously? -

im using activeandroid library , have read entire information (very minimalist , insufficient unfortunately) there no mention whether .save() operation executed syncrhonously. if asynchronous, how "listen" end before proceeding? http://www.activeandroid.com/ - documentation read if have @ source code of model class, you'll see save method not thread handling: public final long save() { final sqlitedatabase db = cache.opendatabase(); final contentvalues values = new contentvalues(); (field field : mtableinfo.getfields()) { /* ... */ } if (mid == null) { mid = db.insert(mtableinfo.gettablename(), null, values); } else { db.update(mtableinfo.gettablename(), values, idname+"=" + mid, null); } cache.getcontext().getcontentresolver() .notifychange(contentprovider.createuri(mtableinfo.gettype(), mid), null); return mid; } saving occurs synchronously.

Facebook for Android error on getting gender of user -

some users getting force close when signing facebook in our app. received stacktrace on lines below: java.lang.stringindexoutofboundsexception: length=0; regionstart=0; regionlength=1 @ java.lang.string.startendandlength(string.java:588) @ java.lang.string.substring(string.java:1475) @ com.yolify.android.activity_splash$7.oncompleted(activity_splash.java:483) @ com.facebook.request$1.oncompleted(request.java:281) @ com.facebook.request$4.run(request.java:1666) @ android.os.handler.handlecallback(handler.java:733) @ android.os.handler.dispatchmessage(handler.java:95) @ android.os.looper.loop(looper.java:136) @ android.app.activitythread.main(activitythread.java:5146) @ java.lang.reflect.method.invokenative(native method) @ java.lang.reflect.method.invoke(method.java:515) @ com.android.internal.os.zygoteinit$methodandargscaller.run(zygoteinit.java:732) @ com.android.internal.os.zygoteinit.main(zygoteinit.java:566) @ dalvik.system.nativestart.main(native method) code: string gen

How do I build React Native iOS app to device through Xcode? -

i tried building awesomeproject app device. build succeeds , splash screen shows, see red "could not connect development server" screen. says "ensure node server running - run 'npm start' react root." it looks node server running because when npm start eaddrinuse message, saying port in use. accessing development server device can iterate on device using development server. that, laptop , phone have on same wifi network. open ios/appdelegate.m change ip in url localhost laptop's ip in xcode select phone build target , press "build , run" ps: http://facebook.github.io/react-native/docs/runningondevice.html#content

android - Getting error while creating an instance of JSONObject -

i want make app contains basic login facility, using volley in eclipse.i have login screen, registration screen , home screen (for logout purpose). i following steps stated androidhive. in registration process runs fine.i can see details enterd user in database. the problem when i,m pressing registration button should move login activity after completing user registering ,but after registering user nothing . what have tried: as of logcat,i figure out there wrong when trying create instance of jsonobject . link logcat screenshot: http://www.imageupload.co.uk/image/z5p9 link registration codes http://www.imageupload.co.uk/image/z5pf just changes in code .remove line "enter code here" (you using 000webhost.com hosting website) ,which default line each page in 000webhost.com .

Linux: Compiling a kernel device driver in standalone fashion -

i'm compiling linux arm board. need make customized changes existing driver code present in kernel repository , reload driver. i expecting find ".ko" file in driver directory after doing make, no such file exists. apparently uimage/device tree image compilation doesn't work way. do need write own makefile standalone device driver compilation? it may silly question, sorry i'm pretty new kernel/device drivers. edit: followed process outlined here: http://odroid.com/dokuwiki/doku.php?id=en:c1_building_kernel after git checkout , installing cross-compiler(arm-linux-gnueabihf-gcc 4.9.2), issue basic make comands $ make odroidc_defconfig $ make -j4 $ make -j4 modules $ make uimage all steps successful. last few lines of log like ksym .tmp_kallsyms1.o ksym .tmp_kallsyms2.o ld vmlinux sortex vmlinux sysmap system.map objcopy arch/arm/boot/ccimage kernel: arch/arm/boot/ccimage ready image arch/arm/boot/ccimage.lzo ready uimage arch/arm/boot

c++ - Including header from the same file on every platform -

i have file cpp-options.txt in have written every compiler option use compile c++ programs. i have made alias g+ g++ @/path/to/cpp-options.txt $* , whenever invoked g+ prog.cpp , anywhere on computer, program compiled compiler options file. now want add option includes header file header.h in options file. file kept on same directory cpp-options.txt file. so, cpp-options.txt file looks -: -wall -wextra..... -include /path/to/header.h now, setup works on windows perfectly, wont work on linux, absolute path options file on linux -: /mnt/media......../absolute/path/to/header.h so, compiler complain absence of such file on linux. aware of 1 solution of problem, include folder in these 2 files kept in path environment variable on both operating systems , writing -: -wall -wextra..... -include header.h however, dont want pollute path variables. there other way of accomplishing ? the best create common file cpp-options-common.txt contain

mysql - error in database connection in cloud9.io -

this type of questions have been asked many times before.i have tried every answer can't figure out problem. i having problem in mysql database connectivity in cloud9.io environment in sails js project. steps 1)mysql-ctl start 2)phpmyadmin-ctl install it worked , opened phpmyadmin page me.i created db there. 3)mysql-ctl cli 4)mysql> \r here's problem giving connection id:1 current database: *** none there no error in console while running sails lift.it gives error on executing queries.i have tried following links related problem no use. access denied user 'root'@'localhost' while attempting grant privileges. how grant privileges? error 1045 (28000): access denied user 'root'@'localhost' (using password: no) error 1045 (28000): access denied user 'root'@'localhost' (using password: yes) and few more.

ibm mq - WMQ self-signed SSL mutual authentication fails when QM has special character -

i have 2 queue manager servers running on 2 boxes. qm1 has sender channel defined , , qm2 has receiver channel same name. have created self signed certificate each qm , extracted , added public part of each certificate other qm's key db. altered each channel use cipherspec triple_des_sha_us. this setup works fine, if qm names don't contain special character. if name of sender qm a_qm , other 1 b_qm , sender channel never comes , in retrying state. while creating self-signed certificate using label ibmwebspheremq a_qm in case of a_qm , ibmwebspheremq qm1 when queue manager qm1. when adding public part of certificate preserving other qm's label. difference in whole setup. is there restriction in defining qm names if want configure ssl or tls ? i had no trouble creating pair of qmgrs , channels described , getting them run: [mqm@rhel6base scripts]$ runmqsc a_qm 5724-h72 (c) copyright ibm corp. 1994, 2014. starting mqsc queue manager a_qm. dis chs(*)

ios - Cannot access property in tableviewcell -

i have custom tableviewcells, each thumbnail having gesture recognizer on it, open modal box. in each tableviewcell there's property containing string. in method called gesture recognizer, i'm trying access property, looping superviews of gesture recognizer. - (void)handlelongpress:(uilongpressgesturerecognizer *)longpressgesturerecognizer { //handle press zoomimageviewcontroller *zoomimage = [self.storyboard instantiateviewcontrollerwithidentifier:@"zoomimage"]; uiview *subview = longpressgesturerecognizer.view; while (![subview iskindofclass:[uitableviewcell self]] && subview) { subview = subview.superview; } uitableviewcell *cell = (uitableviewcell *)subview; zoomimage.filename = cell.machinepicture; zoomimage.modaltransitionstyle = uimodaltransitionstylecrossdissolve; [self presentviewcontroller:zoomimage animated:yes completion:nil]; } in debugger cell object tableviewcellcontroller containing

Algorithms - Semi definite programming -

let g=({1,...,n},e) graph 2 edge weight functions ֿ αe ≤ βe , e ∈ e . i want know whether there exist points p1 ,..., pn ∈ rn , such α{i,j} ≤ ||pi−pj||^2 ≤ β{i,j} , {i,j} ∈ e . how can show decision problem can formulated semidefinite program?

java - Saving previous value for later usage -

i want save value , use later calculate difference between prog , progalt. int prog = (s3.getprogress()-90); int progold = 0; int = prog-progold; then stuff happening. , after want save value of actual prog in progalt use in next round. progold= prog; logically "progalt = prog" useless, because progalt set 0. so, how initialize progalt once , use saved value? int prevvalue = 0; while (somecondition) { int curvalue = ...; int deltavalue = curvalue - prevvalue; ... prevvalue = curvalue; }

php - How to append a new item into the array-type column in PostgreSQL -

im using postgresql application, the task this there users use app, , need maintain notification each of them based on activity lots , lots of notifications each user. so in general put notifications in seperate table , map user id, can fetch them, im thinking use either json/array datatype, can put entire notification set array/json cell of each user row. which 1 better, storing json or array?( im using php @ server side) and if pick 1 among two, lets have 10 notifications, , got 11th one, how append new item array/json object in single execution(may update statement)? dont want go in basic way select row, existing array/json add new item in end(process php) , update back- here takes 2 executions change may occur , brings dataloss so there way update query adds new element or alters existing element/node in array/json obejct types in postgresql? to append item array in postgresql can use || operator or array_append function. with || operator update table s

string - Writing a Java program to encrypt and decrypt a ADFGVX cipher -

i need able encrypt , decrypt message using polybius square. know how works on paper don't know start when turning program. planning use hash map told thats bad way go , there better approaches this...but don't know approaches be. i've been given code me lecture workshop on project don't understand it. i'll paste below , if explain appreciate it! i've been focusing on c lot past while bit rusty when comes java. char [][] poly = { {",'a','b','d'..... {'a','p','h','q'} } thats double array i'll using sort polybius square right? for(int row = 0; row < poly.length; row++) { } for(int col = 0; col < poly[row].length; col++) { } // c char i'm looking if(poly[row][col] == c){ } this used navigating array , finding chars want? // how break line down character string[] words = line.split(" "); for(int i=0; < words.length; i++){ string word = words[i];

php - Why the image disappear when participating in the Facebook note builder you select the link to the image through Meta Code -

Image
when share link website on facebook , don't find image selected desperate other users <meta property="og:image:height" content="240"> <meta property="og:image:width" content="440"> i got permission error (403) when try access image directly. that´s reason why doesn´t show. after fixing that, refresh open graph tags in debugger: https://developers.facebook.com/tools/debug/ edit: og:image not image @ all. must absolute url picture.

php - Preg match a string to find all encounters of -> using regular expressions -

i'm having small technical difficulty regular expression, i'm trying @ string, let's have string: $string = "error->400"; and string: $string = "error->debug->warning"; as example, i'm trying preg_match() returns true on instances of -> within it. this attempt don't understand why doesn't work: preg_match("/^[->]*$/", $string); is there general rule custom characters i'm missing? thanks. right now, ^[->]*$ matches number of "-" or ">" characters, beginning end. must use group, not character class, , anchors not necessary. use check if "->" present in $string : preg_match("/(->)/", $string); have @ example .

javascript - Format number in jsx React component -

this question has answer here: javascript number/currency formatting [duplicate] i writing jsx file , want format display of numbers in table. here code table: <tr> <td> {stringvar} </td> <td> {numbervar} </td> </tr> the numbervar being printed directly; how can display number c-style string formatting (i need set precision value, add commas, , $ character)? you can use js expression format value. popular number formatting library http://numeraljs.com/ there many others of course. as prefixing $, that's string concatenation: {"$" + numbervar} or, using string interpolation es6 syntax : {`$ ${numbervar}`}

email - Mail rejected with "Client host rejected: MX-CIDR" -

i trying send mails mailgun. dns config (spf,dkim) seems ok , being validated in mailgun service. can send mail several users gmail, live , others mail providers. however, have problem when sent email email accounts of university. the message rejected following alert: "554 5.7.1 : client host rejected: mx-cidr" my current dns settings are: txt @ "v=spf1 include:mailgun.org ~all" mx 10 mxa.mailgun.org. mx 10 mxb.mailgun.org. dkim validated well. checked domain @ mxtoolbox , dns config pass in tests. did not find errors related alert in others questions. may me fix it? update 1: more informations: 1) dont send, , have absolutely no intention send spam. created educational website, used students , instructors, , send messages between each others. send mail confirm registers, recovery password, lot of others websites do. send messages people agreed terms of service, includes information mail policy. small service, never sent more 2,000 messages in

nunit - .NET unit testing framework without the use of attributes -

does of more common unit testing frameworks (msunit, nunit, xunit) support mechanism can write code returns list of test methods instead of them being collected automatically based on attributes? i write single method either reads tests external data source or use reflection own logic find test methods. you can build own test runner matter. takes filter methods assembly or other source plan write anyway. run these methods in try catch block. you can consider following filtering solutions nunit (i'm not sure other frameworks.) a) split tests categories , write own custom category attributes explained in following discussion: are custom filters in nunit possible? b) use filtering mechanism thought it's xml , not code: https://github.com/nunit/dev/wiki/test-filters .

To parse an Android application? -

is there external (or internal) script library start android app, parse, text displayed app , perform clicks in order build kind of bot user? yes, can simulate touches, using adb. see this question . link: you can use adb shell run command remotely: adb shell input tap x y if want text screen, screenshot device, (again using adb). screenshot adb: adb shell screencap -p /sdcard/screen.png adb pull /sdcard/screen.png adb shell rm /sdcard/screen.png see here source, , if doesn't work right. then need send screenshot through ocr program extract text. there easier way this, example if there website app, scrape information that.

c# - Linq or Tsql 'Pivot' -

i'm sure covered elsewhere i'm having problems figuring out elegant solution this. id c d 1 apple red 1 pear orange 2 apple red 2 pear orange what trying end this: id | benefit | value 1 | c | apple 1 | c | pear 2 | c | apple 2 | c | pear 1 | d | red 1 | d | orange 2 | d | red 2 | d | orange i can in linq scanning each column , adding list. public class samplerow { public int32 id { get; set; } public string { get; set; } public string b { get; set; } } public class sampleoutput { public int32 id { get; set; } public string description { get; set; } public string value { get; set; } } list<samplerow> rows = new list<samplerow>(); rows.add(new samplerow { id = 1, = "apple", b = "red" }); rows.add(new samplerow { id = 1,

Python simple bouncing physics -

Image
i wondering if there's straightforward way implement bouncing physics in python, without modules physics. bouncing physics, don't mean gravity, mean more released ios game "okay?" philipp stollenmayer ( https://appsto.re/us/1n7v5.i ). know if ball hits straight edges, velocities inverted. so, given diagram: when ball hits , c, x velocities inverted, , when hits b , d, y velocities inverted. if our diagram looks this: given angle of platform, how can find new x , y velocities? also, how can convert these x , y velocities degrees? what found out wikipedia bounce's line of symmetry perpendicular surface hits. my final question how, in pygame, find angle of line, , create line angle. p. s.: when answering question, please keel in mind math knowledge limited what's on nys algebra 1 regents in june :) don't go cauculus , trigonometry on me :) reflectedvector = velocityvector - scale(surfacenormal, 2.0*dot(surfacenormal, velocityvector)) ve

authentication - Allow username instead of e-mail in default Laravel 5.0 AuthController -

laravel 5.0 comes "out of box" authcontroller configured handle user registrations , logins. is possible , configure/modify default configuration use more general "username" instead of e-mail address? ideally, i'd users table have unique username instead of e-mail address; but, i'd settle turning off part of validator insists "e-mail address" field on login page formatted e-mail address. (i figured out how turn off client-side validation; but, can't figure out how turn off server-side validation --- part generates "whoops: ... email must valid email address." message.) the default validation rules defined in app\services\registrar . remove email rule validator method: public function validator(array $data) { return validator::make($data, [ 'name' => 'required|max:255', 'email' => 'required|email|max:255|unique:users', // ^^^^^

javascript - Angularjs Select to Select data passing -

so having inexperienced issues angularjs select function. lol have vehicle program info of car. have 3 select options. make, model, , year. grabbing info json server. 'make' input shows car makes (every make object has model object). 'model' input shows models make user has chosen. dont know how grab data of make , show models make. (and year). html <label class="item item-input item-select"> <div class="input-label"> make </div> <select ng-model="make" ng-options="item.name item in items.makes"> </select> </label> js .controller('milesctrl', function($scope, vehicle, x2js, $http) { /////////my vehicle/////////// $scope.formdata = {}; vehicle.getcar().then(function(data){ console.log(data.data); $scope.items = data.data; }); }); please have @ example: http://jsfiddle.net/s7p0zavy/ suppose have $scope.items following: $scope.item

ruby on rails how to get latest records from has many relationship -

i new ruby on rails. have problem- how latest records has many relationship in model. code this: class user < activerecord::base has_many :books end class book < activerecord::base belongs_to :user scope :rating, -> { where(rating: 5) } end what achieve is: i'd latest (last) book each user , filter books using scope rating. can using each loop (looping through user.books , book.last)- inefficient because have lot of data. have ideas how can this? maybe kind of scope chaining each other? you can if want avoid writing sql: class book < activerecord::base scope :latest, -> book_ids_hash = book.group(:user_id).maximum(:id) book_ids = book_ids_hash.values where(id: book_ids) end end then have is: book.rating.latest

Receiving an error Python 2.7.8 when using code %matplotlib inline -

when use code: %matplotlib inline i receive error message saying usageerror: invalid gui request u'inline', valid ones are:['osx','qt4', 'glut', 'gtk3', 'pyglet', 'wx','none', 'qt', none,'gtk','tk'] i'm running python 2.7.8 in anaconda 2.1.0 on windows 8 64 bit.

javafx - How to wait cancellation of task after Service#cancel? -

look @ example: package sample; import javafx.application.application; import javafx.application.platform; import javafx.concurrent.service; import javafx.concurrent.task; import javafx.stage.stage; public class main extends application { //notice: class in **other file** (here example) private static class myservice extends service { @override protected task createtask() { return new task() { @override protected object call() throws exception { system.out.println("service: start"); while(true) { system.out.println("service: iteration"); // thread.sleep(3000); // raise interruptedexception after cancel, how such code (it won't raise exception): for(long = 0; < 1_000_000_000; i++) { } if (iscancelled())

How to retrieve nested family instances in Revit API -

i'm using filteredelementcollector retrieve family instances: var collector = new filteredelementcollector(doc, doc.activeview.id); var familyinstances = collector.ofclass(typeof(familyinstance)); this works fine families don't have nested family instances. if have in project instances of family a, , family includes instances of family b, code doesn't instances of family b. how family b instances? i'm new revit api , seems there must simple solution couldn't find 1 online. i'm using revit 2015 if makes difference. the familyinstances have list of families in active view (including nested , non-nested ones). what need iterate through each familyinstance , see if root family (ie contains nested families) or nested family or none. like: var collector = new filteredelementcollector(doc, doc.activeview.id); var familyinstances = collector.ofclass(typeof(familyinstance)); foreach (var anelem in fami

ios - Swift Stable Sort? -

at time (march 28, 2015): if want use stable sort in swift, have use nsarray , sortwithoptions or write own stable sort in swift such insertion sort ? see in apple swift docs sorted not stable. example of stable sort in nsmutablearray : [array sortwithoptions:nssortstable usingcomparator:^nscomparisonresult(id obj1, id obj2) { return [obj1 compare:obj2]; }]; am missing option that's available me in swift other using objective-c or writing own sort? as @michael put it, 1 can "write swift-wrapper calls objective-c function"

python - count items using nested loops -

def count_vowel_phonemes(phonemes): """ (list of list of str) -> int return number of vowel phonemes in phonemes. >>> phonemes = [['n', 'ow1'], ['y', 'eh1', 's']] >>> count_vowel_phonemes(phonemes) 2 """ number_of_vowel_phonemes = 0 phoneme in phonemes: item in phoneme: if 0 or 1 or 2 in item: number_of_vowel_phonemes = number_of_vowel_phonemes + 1 return number_of_vowel_phonemes description : vowel phoneme phoneme last character 0, 1, or 2. examples, word before (b ih0 f ao1 r) contains 2 vowel phonemes , word gap (g ae1 p) has one. the parameter represents list of list of phonemes. function return number of vowel phonemes found in list of list of phonemes. question asks me count number of digits in list, codes keep returning 0 strange. there wrong code? in advance!! if any(i in item in ("0", &

arrays - C++ Accessing a class' private member from another friend class' function -

i trying create basic airport system. have classes named in info, , of classes similar airport class. class airport{ private: friend class systemmanager; friend class info; string apname; }; class info{ private: friend class systemmanager; static airport airports[100]; static airline airlines[100]; static flight flights[100]; static flightsection sections[100]; static seat seats[100]; }; now, when try reach "airports" array function systemmanager class, gives error "info::airline airlines[100] private", think missing operators. if(info::airlines[counter].alname==aname that compiler points error, there counter loop in function, , in loop when comes line, gives error. how should reach classes? by way, made arrays static because don't want them created every airport has been created, want keep airport informations in arrays. thank much.

html - PHP code with check box arrays does not work in real site but works in local host -

english not native language; please excuse typing errors. i have strange problem php code, using checkbox arrays. simple checkbox code in real site in russian language, frend fix: http://astrabis.ru/teoria/test2.php the host has php version 5.3.13. but code, yes, works in local pc (windows 7, installed xamp appache) php version 5.6.3. has been installed php server debug problem describe here. problem description. check boxes in file test2.php shown on browser, when check of them , press submit, server not move data testrez2.php file processes data. details. in file test2.php there 3 arrays of check boxes: vata[] pita[] kapha[] test2.php code fragments: <!doctype html> <html> <head> ... <meta http-equiv=content-type content="text/html; charset=windows-1251" /><meta name=viewport content="width=device-width, initial-scale=1" /> ... </head> ... <form action="http://www.astrabis.ru/teoria/testrez2.php" me

sqlite - Distribute NOT across parenthesis in SQL query, is it possible? -

i'm building parser turn search string boolean operators , nested parenthesis in sql queries. search string "(foo bar) or (foo baz)" generates ( "cards"."name" '%foo%' , "cards"."name" '%bar%' ) or ( "cards"."name" '%foo%' , "cards"."name" '%baz%' ) or , and work fine this, not doesn't work expected. i've done reading , looks modifies selectors? i'm pretty unfamiliar. is there way prefix group of selectors, "not (foo bar)" might expand functional equivalent of: ( "cards"."name" not '%foo%' , "cards"."name" not '%bar%' )

amazon web services - How to create a custom AMI using Packer? -

i want launch packer image using master puppet server documentation on packer.io isint greatest. if has experience - pelase let me know how did it. ideally want have packer file build out aws ec2 later can extend vmware well. need me started - dont know search anymore. googled many times no success.

c++ - pipe and stringstream - memory leak when writing in the stringstream -

i have memory issue code when try write binary data in stringstream object. valgrind log (first spotted system monitor): ==23562== 16,368 bytes in 1 blocks possibly lost in loss record 1,612 of 1,612 ==23562== @ 0x402a6dc: operator new(unsigned int) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so) ==23562== 0x4c72213: std::string::_rep::_s_create(unsigned int, unsigned int, std::allocator<char> const&) (in /usr/lib/i386-linux-gnu/libstdc++.so.6.0.19) ==23562== 0x4c73332: std::string::_rep::_m_clone(std::allocator<char> const&, unsigned int) (in /usr/lib/i386-linux-gnu/libstdc++.so.6.0.19) ==23562== 0x4c733d1: std::string::reserve(unsigned int) (in /usr/lib/i386-linux-gnu/libstdc++.so.6.0.19) ==23562== 0x4c4e1ff: std::basic_stringbuf<char, std::char_traits<char>, std::allocator<char> >::overflow(int) (in /usr/lib/i386-linux-gnu/libstdc++.so.6.0.19) ==23562== 0x4c52aec: std::basic_streambuf<char, std::char_traits<

mysql - How to sort a list of people by birth and death dates when data are incomplete -

i have list of people may or may not have birth date and/or death date. want able sort them meaningfully - subjective term - birth date. but - if don't have birth date have death date, want have them collated list proximal other people died then. i recognize not discrete operation - there ambiguity should go when birth date missing. i'm looking approximation, of time. here's example list of i'd like: alice 1800 1830 bob 1805 1845 carol 1847 don 1820 1846 esther 1825 1860 in example, i'd happy carol appearing either before or after don - that's ambiguity i'm prepared accept. important outcome carol sorted in list relative death date death date, not sorting death dates in birth dates. what doesn't work if coalesce or otherwise map birth , death dates together. example, order birth_date, death_date put carol after esther, way out of place thinking. i think you're going have calcul