Posts

Showing posts from March, 2011

java - Use JNI to call C functions in host binary -

i'm trying call jni c function in executable hosting jvm. i've compiled -rdynamic, , confirmed nm -d symbol exported in dynamic symbols table. however, when call jvm complains symbol can't found. i've done in past luajit , rather trivial, i'd pretty surprised if can't done java. i created test method in class jnitest public static native int strlen(); and implementation: #include <jni.h> #include <java/com_jnitest_jnitest.h> #include <string> #include <iostream> jniexport jint jnicall java_com_jnitest_jnitest_strlen(jnienv* env, jclass clazz) { return 1111; } int main() { jnienv* env; javavm* jvm; javavminitargs args; javavmoption options[1]; args.version = jni_version_1_8; args.noptions = 1; args.options = options; args.ignoreunrecognized = false; std::string classpath = "-djava.class.path="; classpath += "/var/projects/jnitest/src/java"; options[0].op

c# - Create a dictionary from the common property values of a List<Object> -

let's have list of _2dline objects. public class _2dline { public double x1 { get; set; } public double y1 { get; set; } public double x2 { get; set; } public double y2 { get; set; } } var l1 = new _2dline { x1 = 0, y1 = 0, x2 = 100, y2 = 100 }; var l2 = new _2dline { x1 = 50, y1 = 50, x2 = 200, y2 = 200 }; var l3 = new _2dline { x1 = 0, y1 = 0, x2 = 200, y2 = 200}; var l4 = new _2dline { x1 = 100, y1 = 100, x2 = 50, y2 = 50}; var mylines = new list<_2dline> { l1, l2, l3, l4 } as can see, of lines have points in common. how can extract points list dictionary specific _2dpoint(x,y) have list of lines entering or exiting point. var mypoints = new dictionary<_2dpoint, list<_2dline>>(); public class _2dpoint { public double x { get; set; } public double y { get; set; } } the final result this: key | value ----------------------------------- _2dpoint(0,0) | { l1, l3 } _2dpoint(100,100)

Regex to replace tags in a string in PHP -

i using php , regex below search through huge string [link]www.anyurl.com[/link] and replace with: <a href="http://www.anyurl.com">http://www.anyurl.com</a> the http:// prepended if http or ftp not exist in front of url already. $re = '/\[link]((?:(?!(http|ftp)|\[\/link]).)*)\[\/link]/i'; $subst = '[link]http://$1[/link]'; $xtext = preg_replace($re, $subst, $xtext, 1); $xtext = preg_replace("/(\[link\])(\s*)(\[\/link])/", "<a href=\"$2\" target='_blank'>$2</a>", $xtext); my problem appears working first match comes , not other [link]www.urls.com[/link] in document. document being $xtext whoops, have found error , simple. in third line: $xtext = preg_replace($re, $subst, $xtext, 1); i have 1 @ end of preg_replace i.e. replace once. should set -1 or left blank replace all.

jquery - CSS Transitions On/Off on Click -

http://codepen.io/dylanespey/pen/cvwzo the goal animation play on click, , reverse on second click. i'm not sure how use javascript set (just learning it, see.). had idea add class using jquery, below, wasn't working. tried "cheat" using :target selector, that's not functional. ideas? $(document).ready(function (){ $(function () { $("#button").click(function () { $("#button").toggleclass(".active"); }); }); }); http://codepen.io/anon/pen/qbgae markup: <body> <ul> <li> <a href="#button"> <div id="button"> <div class="plus">+</div> </div> </a> </li> <li> <div id="banner"> <p>some text viewing pleasure!</p>

python - Excel File and Sheet Location -

i have list of excel files , corresponding sheet number. need python go sheets , find out cell location particular content. "alecxe", used following code , worked well. import xlrd value = 'avg.' fn = ('c:/ab1.xls', 'c:/ab2.xls','c:/ab3.xls','c:/ab4.xls','c:/ab5.xls',) sn = ('505840', '505608', '430645', '505464', '505084') name, sheet_name in zip(fn, sn): book = xlrd.open_workbook(name) sheet = book.sheet_by_name(sheet_name) row in range(sheet.nrows): column in range(sheet.ncols): if sheet.cell(row,column).value == value: print row, column later wanted make changes , instead of writing down filename , sheetnumber, wanted python grab them excel sheet. program not printing anything. can show me made mistake? highly appreciate comment! import xlrd import glob import os value = 'avg.' sheetnumber = [] filename = [] xlfile = &qu

Get coordinates of imageview during animation android -

i trying make animation of imageview left right , right left want position of imageview while animation following code. want use coordinates origin display in app. please tell me how this. following code using animate , move position of imageview. animation anx = new translateanimation(0,100,0, 0); anx.setduration(2000); anx.setfillafter(true); myimage.startanimation(anx); is there function getx() , gety() position. have u tried set animation listener , starting runnable when animation starts check image getx , gety every milliseconds u want , stop after animation ends

database - Django. South. Heroku. KeyError: 'default' -

i'm new heroku, tried following instructions literally , i'm lost error. so, when included settings.py configurations written in "getting started django on heroku" can't run local server anymore unless comment out south installed apps. this error: south.db import default_db_alias file "/home/alejandro/proyectos/olenv/local/lib/python2.7/site-packages/south/db/__init__.py", line 83, in <module> db = dbs[default_db_alias] keyerror: 'default' this relevant settings in settings.py: databases = { 'default': { 'engine': 'django.db.backends.postgresql_psycopg2', 'name': 'dbolib', 'user': 'alejandro', 'password': 'zzzzz' } } # --- heroku --- # # parse database configuration $database_url import dj_database_url databases['default'] = dj_database_url.config() maybe supposed way since south tool production , therefore conflicts heroku

AppleScript parsing html from site -

what i'm trying names of tv shows on wikipedia page. ok, did first: property showsweblist : {} tell application "safari" set loaddelay 2 -- in seconds; test system make new document @ end of every document set url of document 1 "http://en.wikipedia.org/wiki/list_of_television_programs_by_name" delay loaddelay set nrofuls javascript "document.getelementbyid('mw-content-text').queryselectorall('ul').length;" in document 1 set nrofuls nrofuls - 1 number log nrofuls repeat ws 1 nrofuls delay loaddelay set nroflis javascript "document.getelementbyid('mw-content-text').getelementsbytagname('ul')[" & ws & "].queryselectorall('li').length;" in document 1 set nroflis nroflis - 1 number log nroflis repeat rs 0 nroflis delay 0.3 set ashow javascript "document.getelementbyid('mw-conte

wpf - Perform actions on DataTemplate's datas when they are completely loaded? -

i have itemscontrols in datatemplate "grid". i dynamically bind values itemscontrol itemsource. i donot know how itemsource's list count be!. i want perform actions on complete set of data , after datatemplate's data bounded . (i mean grids data, loaded). may know how find it? ex: <itemssource itemsource={bindiing listofdata}> <datatemplate> <grid> <textblock text={binding name} grid.coulm=0/> <textblock text={binding age} grid.coulm=1/> <textblock text={binding address} grid.coulm=2/> </grid> </datatemplate> </itemsource> public list < persons> listofdata; class persons { public string name; public string age; public string address; } now consider listofdata having 50 objects of type persons . may change @ runtime. now want perform operations on list of 50 person objects, after gets loaded itemscontrol. (not on individual

xcode - How to run presentViewController in IOS static library -

i trying build static library camera in ios, showing error in user application attempt present <uiimagepickercontroller: 0x17e2f740> on <camera: 0x17d3f5b0> view not in window hierarchy! i using code in camera.m inside static library libcamera.a -(void)callcamera { uiimagepickercontroller * picker = [[uiimagepickercontroller alloc] init]; picker.delegate = self; picker.sourcetype = uiimagepickercontrollersourcetypecamera; [self presentviewcontroller:picker animated:yes];// error line } i using library in application checkcamera.m importing libcamera.a -(void)viewdidload { [super viewdidload] camera cam=[[camera alloc]init]; [cam callcamera] } but showing above mentioned error, want know how run presentviewcontroller inside static library? try move [cam callcamera] viewdidload viewdidappear . according uiviewcontroller class reference viewdidappear exact method indicates view controller's view added window hierarchy. edi

jquery - Bottom Scroll Checked acts in reverse -

so i'm trying detect if page has scrolled way bottom, , found code: $(window).scroll(function() { if($(window).scrolltop() + $(window).height() == $(document).height()) { alert("bottom!"); } }); and works... in complete reverse! instead of letting me know when i've scrolled way bottom, detects when i've scrolled @ top. would tell me why it's doing on end? this function adding how far down you've scrolled $(window).scrolltop() height of viewport $(window).height() . when greater or equal height of webpage $(document).height() , triggers alert. my guess webpage isn't higher viewport, alert message triggers @ top of page. see jsfiddle . function working fine (view console log) because content of page taller viewport.

r - How to display 0 value in a bar chart using ggplot2 -

Image
i have data frame called data: head(data) date total_sold purchasability visibility 81 2014-05-01 3 3 3 82 2014-05-02 2 2 3 83 2014-05-03 1 2 3 84 2014-05-04 1 3 3 85 2014-05-05 3 2 3 86 2014-05-06 0 0 3 and bar chart x = date , y = total_sold color depending on purchasability. ggplot2 : bar <- ggplot(data = data, aes(x = date, fill=as.factor(purchasability),y = total_sold)) + geom_bar(stat = 'identity') the output nice problem total_sold = 0 there not chart , no way know purchasability. possible still display bar (maybe 0.5 -0.5) when total_sold = 0 ? thanks i'm not sure there's simple way go 0.5 -0.5 can show 0 value being fraction (eg -0.1) modifying value in bar= line to: bar <- ggplot(data = data, aes(x = date, fill=as.factor(purcha

sql - MySQL SUM calculation not based on number of rows but based on unique results -

i have query below: select count(c.status) num, sum(p.total_paid_nocred) lordo, sum(p.total_paid) netto coupons c, payments p, addresses p.payment_id=c.payment_id , c.address_id=a.address_id , c.offer_id='.$off['offer_id'].' , c.address_id!=0 , a.time <= '.$off['insertion_date'].' , c.user_id!=0 , c.status in (1,2) , a.shipment_num="" , p.status=0 , p.medium!=3 the problem having when query runs can find example 5 coupons, divided between 3 different payment transactions , other 2 of them in 1 transaction. to clear. client can buy 3 different coupons 3 different transactions, or can buy 2 coupons on 1 single transaction. so when query sum, if single transaction has 2 linked coupons duplicates amount of transaction 2. not good, because transaction amount final is, not have duplicated more times many coupons lin

html - jQuery ignores last element in returned set -

i'm working on internal plugin jquery datatables, , i'm experiencing weird behavior. take @ following fiddle: http://jsfiddle.net/bjllz/ the code below looking every 'tr' first 'td' element, , adds 'td' checkbox input before every match finds. (notice last row in fiddle above not have checkbox) $(function () { var checkbox = $('<input>', { "type": "checkbox" }) var td = $('<td/>', { 'class': "table-checkbox" }).insertbefore("tbody > tr > td:first-child") var checkboxes = $(checkbox).appendto(td) var th = $('<th/>', { 'class': 'text-center' }).insertbefore("thead > tr:nth(0) > th:nth(0)") $(checkbox).appendto(th) .change(function () { $(this).is(":checked") ? checkboxes.prop('checked', true) : checkboxes.prop('checked', f

r - Removing rows of data frame if number of NA in a column is larger than 3 -

i have data frame (panel data): ctry column indicates name of countries in data frame. in column (for example: carx ) if number of nas larger 3; want drop related country in data fame. example, country has 2 na country b has 4 na country c has 3 na i want drop country b in data frame. have data frame (this illustration, data frame huge): ctry year carx 2000 23 2001 18 2002 20 2003 na 2004 24 2005 18 b 2000 na b 2001 na b 2002 na b 2003 na b 2004 18 b 2005 16 c 2000 na c 2001 na c 2002 24 c 2003 21 c 2004 na c 2005 24 i want create data frame this: ctry year carx 2000 23 2001 18 2002 20 2003 na 2004 24 2005 18 c 2000 na c 2001 na c 2002 24 c 2003 21 c 2004 na c 2005 24 a straightforwa

c# - An object reference is required for the non-static field,method, or property dataGridView1 -

i have 2 forms in windows forms application. want take parameters second form filter datagridview in first form. here filtergrid method on first form: public void filtergrid(string query) { oledbconnection connection = new oledbconnection(); oledbdataadapter adapter = new oledbdataadapter(); oledbcommand command = new oledbcommand(); connection.connectionstring = @"provider=microsoft.ace.oledb.12.0;data source=c:\users\tamer memili\desktop\urun.accdb; persist security info=false;"; connection.open(); dataset dataset = new dataset(); datatable datatable = new datatable(); dataset.tables.add(datatable); adapter.selectcommand = command; command.connection = connection; command.commandtext = query; adapter.fill(datatable); datagridview1.datasource = datatable.defaultview; connection.close(); } i have define method public static void access form2, when that, error on line: datagridview1.datasource = datatable

Enabling a custom formatter in Rails -

i've written custom formatter rails: module logging class generalformatter < logger::formatter def call(severity, time, program_name, message) ... end end end and according rails guide , this answer , have use set config.log_formatter = logging::generalformatter.new unfortunately, doesn't seem work—my custom formatting isn't kicking in. , yet, if instead define well: module logging class generallogger < activesupport::logger def initialize(*args) super(*args) @formatter = generalformatter.new end end end then can config.logger = logging::generallogger.new , logs formatted desired. what doing wrong setting log_formatter ? i'd rather not define own logger when want custom formatting. edit (responding comments, , adding more detail little more digging): i'm setting config.log_formatter in application.rb , testing in development, , appears working to extent , in calling rails.logger.formatter

html - Background image in css being resized -

i have css code, creates triangle , background image fixed: .post-wrapper_pic2 { position: absolute; width: 922px; height: 1550px; -webkit-clip-path: polygon(0 50%, 100% 50%, 50% 100%, 0 50%); background: url("http://krishnaeverson.com/wp-content/uploads/2014/01/universe.png") center center; background-attachment: fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; z-index:10px; } but problem image beeing resized , though put hight quality image background appears pixelated. can figure what's wrong in i'm doing? you apparently wondering css property named background- size leads resizing of image … should’ve looked does. background-size : cover keyword specifies background image should scaled small possible while ensuring both dimensions greater or equal corresponding dimensions of background positioning area.

java - Existing Maven Project on Amazon Beanstalk -

i trying migrate existing maven project amazon beanstalk. looking @ amazon's documentation,i don't see maven project deployment instructions. i tried upload war file generated application not coming on beanstalk. i know if there existing documentation deploy on beanstalk maven. i have spring data jpa,spring mvc application,do need specific configuration or move configuration files within war file. for maven plugin, check beanstalk-maven-plugin @ http://beanstalker.ingenieux.com.br/beanstalk-maven-plugin/ , has lot of nice features, removing old versions, incremental fast deploys , many others. also, check eb log files in /var/log/eb-cloud-init.log find out why app not coming up, find need customization, download jdbc driver , configure datasource. can use elastic beanstalk configuration files this: http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/customize-containers-ec2.html and post again if have more specific issues. best of luck beanstalk!

java - Continue at first loop , inside the second loop -

this understand better: for(object o : objects){//first loop for(int j = 0; < y; j++){//second loop if(something_is_true) stop second loop , continue first loop } } am supposed use continue keyword that"? no, use 'break'. for(object o : objects){//first loop for(int j = 0; < y; j++){//second loop if(something_is_true) break; } }

java - Creating Json from XAgent -

i'm trying create json xpages "xagent" using java. there's particular format i'm trying , uses integer key , keep getting errors don't understand. here's example error: caused by: java.lang.classcastexception: java.lang.integer incompatible java.lang.string @ com.ibm.commons.util.io.json.jsongenerator$generator.outobject(jsongenerator.java:202) @ com.ibm.commons.util.io.json.jsongenerator$generator.outliteral(jsongenerator.java:163) @ com.ibm.commons.util.io.json.jsongenerator$generator.outliteral(jsongenerator.java:142) @ com.ibm.commons.util.io.json.jsongenerator$generator.tojson(jsongenerator.java:138) @ com.ibm.commons.util.io.json.jsongenerator.tojson(jsongenerator.java:64) @ com.ibm.commons.util.io.json.jsongenerator.tojson(jsongenerator.java:49) i'm trying create json output this: [ { // minimum 0:{src:'item_one_format_one.ext', type: 'video/...'} }, { // 1 content, multiple formats 0:{s

Does Netty provide reliable-ordered UDP messaging? -

does know if netty provides reliable messaging (acks) , sequence ordering upd messages? looking java messaging library allow me write game server provide functionality don't have write it. ok - found answer. does! provides udt via these packages: io.netty.channel.udt io.netty.channel.udt.nio which include these classes: udtchannel udtchannelconfig udtchanneloption udtmessage udtserverchannel udtserverchannelconfig and these ones: nioudtacceptorchannel nioudtbyteacceptorchannel nioudtbyteconnectorchannel nioudtbyterendezvouschannel nioudtmessageacceptorchannel nioudtmessageconnectorchannel nioudtmessagerendezvouschannel nioudtprovider and provides plain udp via these classes: datagramchannel datagramchannelconfig datagrampacket

linux kernel - interacting user space during system call -

i'm trying write block device driver implements read/write operations. tricky thing information not in hardware, in user space process. therefore, during read/write system call interact user space (i.e. sendign signal user space). however, user space process catching signal after read/write system call returned. adding wait in system call implementation seems ignored somehow. i used code @ read system call: ssize_t sleepy_read(struct file *filp, char *buf, size_t count, loff_t *f_pos) { struct siginfo info; struct task_struct *t; int ret; #define sig_test 44 memset(&info, 0, sizeof(struct siginfo)); info.si_signo = sig_test; info.si_code = si_queue; info.si_int = 1234; rcu_read_lock(); t = pid_task(find_pid_ns(current->pid, &init_pid_ns), pidtype_pid); if(t == null){ printk(kern_err "no such pid\n"); rcu_read_unlock(); return -enodev; } rcu_read_unlock(); ret = send_sig_info

Javascript object oriented pirate translator -

i need make object oriented pirate translator in javascript final, have idea , have code can't output correctly on page. have set type english phrase in 1 box , in other box spits out pirate version. not step through array of objects. post code. can get!!! var $ = function(id) { return document.getelementbyid(id); } var dictionary = [{ greetings: { hello:"ahoy", hi:"yohoho", pardon_me:"avast", excuse_me:"arrr" }, people: { stranger:"scurvy", sir:"matey", madam:"proud beauty", miss:"comely wench", officer:"foul blaggart", enemy:"scallywag" }, questions: { where_is:"whar be", can_you_help_me_find:"know ye", is_that:"be that", how_far_is_it_to:"how many leagues to" }, articles: { the:"

android - Google Play Services Game Leaderboard -

i cannot seem find answer anywhere else, asking here hoping know. with google leaderboard, need sort both high score , fastest completion time, possible? example: player: sally score: 50 time: 1:12:00 player: mike score: 50 time: 1:15:00 player: don score: 50 time: 2:22:00 i using own table , code website mysql, wanted move google play services leaderboard if can this. thank you. off-topic: think confusion not asking how code anything, asking if possible (if knew of way), using google play services leaderboard, have leaderboard sorts not high score or fastest time, both on same leaderboard in example. asked in google developer forum, , suggested ask here, go figure.... you have make 2 leaderboards, 1 time , 1 score, after can query them each highest, lowest, player, whatever, yes can though, little different doing mysql, have make 1 leaderboard score , 1 time

java - Why is my Android Thread so Slow? -

i have been trying write poker scoring algorithm... has 7 nested for-loops iterate through every combination of 7 card poker hands , score them. of course pretty intensive loop... under 110.5 million combinations. my algorithm raw work in progress... manages correctly score hand combinations in 8.5 seconds in eclipse on desktop. not bad thought... same algorithm in android thread takes 17 minutes on android emulator , 4 minutes on htc 1 xl. i prepared phone run slower newish desktop... not factor of 30. my code below; public void startthread() { runnable runnable = new runnable() { string bitstring; byte[] bitcount = new byte[8192]; byte[] isstraight = new byte[8192]; boolean[] isflush = new boolean[8912]; int c, c1, c2, c3, c4, c5, c6, c7; int[] cards = new int[7]; long stime, etime, score = 0; int[] handcount = new int[9]; int pipmask; int[] pips = new int[6]; int[] suit = new int[4]; @override public void run() { (c

java - Jersey Or Spring for restful webservices? -

i using apache cxf jax-ws webservices. i planning go restful webservices easier develop , understand. better on performance side. i new restful web services. read more it. question implementation(jersey or spring) go ? i bit biased towards spring using spring core in our project though not spring mvc. advice ? if using apache cxf jax-ws, why not use cxf jax-rs http://cxf.apache.org/docs/jax-rs.html here's example http://www.dreamsyssoft.com/blog/blog.php?/archives/7-simple-jax-rs-web-service-in-java-with-spring-and-cxf.html continuing use cxf mean can reuse of existing pojos (if not of them) if implementing jax-rs api similar in function existing jax-ws one. even if new jax-rs api different, time develop should reduced due existing familiarity cxf.

asp.net mvc 4 web api - data integrity/validation responsibility -

i'm new asp.net mvc , web apis, learning it. lets have models: public class student { public int studentid { get; set; } public string studentname { get; set; } } public class course { public int courseid { get; set; } public string coursename { get; set; } public ienumerable<int> studentids { get; set; } } controllers: user controller - implements post, put, get, delete course controller - implements post, put, get, delete each controller uses kind of repository get/add/remove/update data lets say: courses repository static dictionary<'int, course> courses students repository *static dictionary<'int, student> students * we not use entity framework! custom routing post /api/courses/ {courseid} /users/ {userid} should go course controller , add user id list [route("api/courses/{courseid}/students/{studentid}")] [httppost] public httpresponsemessage addstudenttocourse(int courseid, int studentid)

jsf 2 - javax.faces.FacesException: Cannot find public key for catpcha -

i want implement captcha in application, error can tell me reason ?? juin 01, 2014 12:22:04 pm com.sun.faces.context.partialviewcontextimpl$phaseawarevisitcallback visit grave: javax.faces.facesexception: cannot find public key catpcha, use primefaces.public_captcha_key context-param define one see message, need register captcha key add following web.xml <context-param> <param-name>primefaces.public_captcha_key</param-name> <param-value>your-publickey</param-value> </context-param> <context-param> <param-name>primefaces.private_captcha_key</param-name> <param-value>your-private-key</param-value> </context-param> to register goto : https://www.google.com/recaptcha/intro/index.html

c# - Making a Detailview Field Invisible and Acessible -

i had databound detailsviewcontrol . displaying questions , answer option , correct answer <asp:detailsview id="detailsview1" runat="server" autogeneraterows="false" backcolor="white" bordercolor="#999999" borderstyle="solid" borderwidth="1px" cellpadding="3" datasourceid="sqldatasource1" gridlines="vertical" height="50px" width="477px" forecolor="black"> <alternatingrowstyle backcolor="#cccccc" /> <editrowstyle backcolor="#000099" font-bold="true" forecolor="white" /> <fields> <asp:boundfield datafield="question" headertext="question" sortexpression="question" />

database - Given a relation with FDs, compute the closure of set of attributes -

consider relation schema r = abcdg following functional dependencies (fd) ab -> c c -> bc -> d acd -> d d -> eg -> c cg -> bd ce -> ag compute closure of bd , ca . how can find them? the closure of set of functional dependencies, f , means functional dependencies logically implied f . example, given bc -> d , and d -> eg we can apply armstrong's axioms derive d -> e , d -> g , bc -> e , bc -> g , and on. when you've derived every fd implied f , have closure of f respect r. in case, want derive every fd logically implied bd , ca. as far know, every textbook on relational database theory includes 1 or more algorithms compute closure of set of functional dependencies. best bet follow 1 of algorithms in textbook, if have one.

linux - Passing on IP camera through raspberry pi -

i've been having problems project of mine. had raspberry pi connected webcams found load rpi. why decided purchase , use ip camera. problem though, ip camera not wifi reception should placed have powerful directional antenna can attach rpi. want rpi route internet traffic camera plugged ethernet, on wifi. i'm not 1 hundred percent sure how far have giving wifi priority on ethernet , set dhcp server camera gets ip address. in current setup, when hard-wired raspberry pi, can connect camera (on 192.168.2.10) outside, can connect web server running on on rpi. i'm not sure if port forwarding of camera works want able access webserver on 192.168.1.117 (this works) , want see camera on 192.168.1.117:10 (this not work). try this, i followed tutorial cant seem results after finishing it. any appreciated! thanks. you may want try uv4l mjpegstream driver . turns ip camera (virtual) video device available on rpi. example here (in step 3 pass url of ip camera stream).

java - Converting string to UTF-8 using buffer -

i need convert (possibly large) string utf-8, don't want create byte array containing full encoding. idea use charsetencoder this, charsetencoder acts on charbuffer , means supplemental characters (outside unicode range 0x0000 0xffff ) should considered. now method was using charbuffer.wrap(string.substring(start, start + block_size)) , , bytebuffer created using bytebuffer.allocate((int) math.ceil(encoder.maxbytesperchar() * block_size)) . however, charbuffer contain block_size code points, not code units (characters); think actual amount of characters 2 times block_size maximum. means bytebuffer 2 times small well. how can calculate correct amount of bytes bytebuffer ? double in case each , every character supplemental character, seems bit much. other reasonable option seems iterate on code units (characters) or code points, @ least looks suboptimal. any hints on what's efficient approach encode strings piecemeal? should use buffer, iteration string.codepo

node.js - How can I use ng-repeat to display data stored inside a nested object? -

i working document contains nested data. i've figured out how store nested data (e.g., comments associated post), can't figure out how access data in query. here have: node.js app.get('post/:post_id/comments', function(req, res) { var post = require('./models/post'); post.find( {_id: req.params.post_id}, null, {}, function (err, data) { if (err) return console.error(err); return res.json(data); } ); }); mongoose: var mongoose = require('mongoose'); var postschema = mongoose.schema({ name : string, post : string, comments : [{ name : string, text : string }] }); module.exports = mongoose.model('posts', postschema); angularjs: $scope.getpostcomments = function(postid){ $http({ url: 'post/'+postid+'/comments', method: "get" }) .success(function (data, status, headers,

javascript - Youtube Data API v. 3 - Display channel author name of private / deleted video -

this 1 of them youtube internal decisions highly counter-productive. correct me if i'm wrong, don't want expose channel name of private / deleted videos. call 'bug' if happens ( http://code.google.com/p/gdata-issues/issues/detail?id=5893 ). happens if solely request video ids public beforehand later became private or deleted? get, via usage of youube data api v3, "response undefined" error message in console. happens when message happens? code breaks! this code use: function displaythemvideos(yeah) { var yeah = $("#thosemissingids").text(); var vidrequestoptions = { id: yeah, part: 'snippet', fields: 'items(id),items(snippet(channelid)),items(snippet(channeltitle)), items(snippet(title)),items(snippet(thumbnails(default)))' }; var vidrequest = gapi.client.youtube.videos.list(vidrequestoptions); vidrequest.execute(function(response) { var videoiditems = response.result.items; if (videoiditems) { // if results displayresults(v

3d - opentk pitch rotation deforms the shape -

Image
i'm using opentk in c# render 3d surface , rotate it. yaw works fine, pitch rotation (tilting object towards camera) causes surface deform. the image on left i'm rendering deformed , 1 one right correct. note when pitch zero, looks fine. here gist of code: private void glcontrol1_paint(object sender, painteventargs e) { gl.clear(clearbuffermask.colorbufferbit | clearbuffermask.depthbufferbit); matrix4 perspective = matrix4.createperspectivefieldofview(1.0f, aspect_ratio, 1.0f, 10000.0f); //setup perspective [fovy, aspect, znear, zfar] matrix4 lookat = matrix4.lookat(eye_pos.x, eye_pos.y, eye_pos.z, 0, 0, 0, 0, 0, 1); //setup camera [eyex, eyey, eyez, targetx, targety, targetz, upx, upy, upz)] gl.matrixmode(matrixmode.projection); //load perspective gl.loadidentity(); gl.viewport(0, 0, this.clientsize.width, this.clientsize.height); gl.loadmatrix(ref perspective); gl.matrixmode(matrixmode.modelview); //load camera gl.loadidentity();

javascript - idangero.us swiper update tabs on slide swipe -

building mobile mobile app demo using idangero.us swiper: http://www.idangero.us/sliders/swiper/ i've almost got working way want, 1 issue: when click on 1 of tabs in menu, changes it's class "active" , slides proper slide. need change tab class when user manually swipes 1 of slides. if swipe "about us" slide example, corresponding tab should change active. there's example of in action here: "tabs feedback" i can't figure out how make work when have 2 swipers on page (one nav, , 1 body). here's js: $(function(){ //init navigation var nav = $('.swiper-nav').swiper({ slidesperview: 'auto', freemode:true, freemodefluid:true, onslideclick: function(nav){ pages.swipeto( nav.clickedslideindex ) } }) $(".swiper-nav a").on('touchstart mousedown',function(e){ e.preventdefault() $(".swiper-nav .active").removeclass('active') $(this).addclass('active') tabsswiper.swi

javascript - How to write expression inside ng-if -

i have put expression inside ng-if should evaluated , content displayed based on value. code is <a ng-if="abc.status===failure" href="http://localhost:3000/abc/abc">image</a> currently never getting displayed. surprisingly syntax of double quotes works if want test if value null <a ng-if="value" href="http://localhost:3000/abc/abc">{{image}}</a> how evaluate abc.status===failure , assign result ng-if wrap failure in quote, change: <a ng-if="abc.status===failure" href="http://localhost:3000/abc/abc">image</a> to <a ng-if="abc.status==='failure'" href="http://localhost:3000/abc/abc">image</a>

javascript - Round decimal place only to 3 places -

i need round decimal places three: here code: var split_arr = subtotal_string.split(".", subtotal_string); var integer = split_arr[0]; var decimal = split_arr[1]; var decimal_new = decimal.tofixed(3); but not working.. please help, thanks you don't need split it, cast string number ( + ) call tofixed() : var threedp = (+subtotal_string).tofixed(3); // 9.43663436 -> 9.437

sql server 2012 - Unable to find the requested .Net Framework Data Provider. It may not be installed -

i using nlog error loggin. have configured nlog using following code in web.config programs throws error "unable find requested .net framework data provider. may not installed." <nlog xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" throwexceptions="true" internallogfile="c:\nlog.txt" internalloglevel="debug"> <extensions> <add assembly="nlog.extended" /> </extensions> <targets> <target name="console" xsi:type="console" layout="${level:uppercase=true} ${message}"/> <target name="delivroslogfile" xsi:type="file" filename="c:\delivroslogs\delivros.log" layout="${longdate} |${message}| ${stacktrace}"/> <target xsi:type="database" name="delivrosdatabaselogging" connectionstringname="delivrosentities" commandtext="insert tbl_errorlogin( event_id,priorit

java - Which data store can handle TB of audio calls in SWING -

which database best suits following scenario: i have created java application stores audio calls local file system. application, in order play audio calls, retrieves metadata database (mysql), has 1 column location call on local hd. the issue have amount of audio calls huge (around 50 tb) what should handle such amount of data the application built in java swing edit: i interested in database can handle such amount of data. have heard hadoop seems batch processing not real time querying. any suggestion? thanks consider compressing audio files. ideally, lossless compression if necessary, lossy compression (you can away low bitrate if audio calls speech). user suggested following java compression libraries: https://stackoverflow.com/a/10486007/2557554

android pay - Google Wallet Subscription Cancellation Postback and PHP -

i creating google wallet subscriptions via website , marking users active , stores orderid when subscription created postback . when subscription cancelled, unable set user status inactive. how know user mark inactive when postback comes through? the sellerdata nor orderid seem sent when postback sent. i've tried without luck: if($decoded_jwt->typ === "google/payments/inapp/subscription/v1/canceled") { $order_id = $decoded_jwt->response->orderid; $query = "update user set "; $query .= "user.activewalletsub = '0' "; //0 inactive $query .= "where user.walletsuborderid = '{$order_id}'"; mysqli_query($connection, $query); } how go associating user google wallet subscription ? thanks input.

spring - how to use if loop inside if loop using jstl -

i have requirement if status 0 add css class active else add css class active1 , have done follow <c:foreach items="${parentlist}" var="test"> <c:choose> <c:when test="${test[1] eq 0}"> <li><a href="#" class="active" value="${test[0].id}-${test[0].category}" id="${parent.id}" onclick="return getquestions(this);" > ${test[0].name }</a></li> </c:when> <c:otherwise> <li><a href="#" class="active1" value="${test[0].id}-${test[0].category}" id="${parent.id}" onclick="return getquestions(this);" > <img src="${pagecontext.request.contextpath}/resources/ui_resources/img/checked.jpg" alt="" height="20" width="20"/>${test[0].name }</a></li> </c:otherwise> </c:choose> </c:foreach> now requirement if ${t

How to execute all methods of an object in a certain queue in ios -

for ios app using main queue , root queue. have several objects , want mehtods run in root queue. far, have been doing add dispatch_async each time call 1 of methods become troublesome when use more queues , want go main queue. looking way assign objects root queue methods executed in roof queue. mean looking sth. this: [[testclass alloc] initinqueue:testqueue]; it possible create in manner similar kvo. swizzle methods wrap them dispatch_* calls, discourage it. level of magic high, , tie in knots. moreover, can't wrap arbitrary method in dispatch_async since can't have return result that. can't wrap arbitrary methods in dispatch_sync because deadlock. problems of solving general case spiral out of control in opinion. what should asking instead whether queue architecture correct. need keep calling many small methods on other queues? in many cases better encapsulate full work units (i.e. coherent sequence of operations take input , generate final result) rat

ruby on rails - Minitest and Test::Unit -

due of discussion in open source community regarding tdd, have read blogs simplicity of minitest. use rspec , think minitest may testing suite learn. feel silly asking this, minitest same test::unit? looked around online can't find answer question. want ensure when talk this, @ least ask question correctly. real question this: is minitest same test::unit, or test::unit component of minitest? if neither of options, 2 totally different testing suites? basically, test::unit got replaced minitest (which ships ruby now). minitest tests can written in test::unit syntax or in minitest::spec syntax. mini::test, standalone, doesn't have future... minitest faster, smaller, included default, , has great future and, imho, should make switch! although lacking in documentation, have found. part, can use test::unit documentation using minitest.