Posts

Showing posts from March, 2013

Convert varchar data to datetime in SQL server when source data is w/o format -

how can convert varchar data '20130120161643730' datetime ? convert(datetime, '20130120161643730') not work. however, convert (datetime, '20130120 16:16:43:730') works. guess needs data in correct format. is there valid way can used convert datetime directly unformatted data ? my solution : declare @var varchar(100) = '20130120161643730' select concat(left(@var,8),' ',substring(@var,9,2),':',substring(@var,11,2),':',substring(@var,13,2),':',right(@var,3)) it works fine. however, i'm looking compact solution. you can make little more compact not forcing dashes, , using stuff instead of substring : declare @var varchar(100) = '20130120161643730'; set @var = left(@var, 8) + ' ' + stuff(stuff(stuff(right(@var, 9),3,0,':'),6,0,':'),9,0,'.'); select [string] = @var, [datetime] = convert(datetime, @var); results: string dateti

c# - Visual Studio 2003 can't navigate to the definition of "IIdentity" or "StringTable" -

i have following code: using system; using system.collections; using system.security; using system.security.principal; public class systemprincipal : iprincipal { private iidentity _identity; private stringtable _roles; public systemprincipal(iidentity id, stringtable roles) { _identity = id; _roles = roles;; } public iidentity identity { { return _identity; } } public bool isinrole(string role) { bool result = false; if (null != _roles) { result = _roles.contains(role); } return result; } } i want see definition of iidentity or stringtable right click , choose goto definition "cannot naviate to" iidentity or stiringtable. based on google soultion rebuilt project did not solve issue.

javascript - Google Places and ZERO_RESULTS -

i've been working on simple google places search , cannot zero_results. makes no sense me @ point map working , displays markers database within separate ajax function. i've logged objects , variables , seem fine. why success callback go right else statement zero_results? $( "#submit3" ).click(function(e) { e.preventdefault(); findplaces(); $('#results').text("triggah3!"); }); function findplaces() { var lat = document.getelementbyid("latitude").value; var lng = document.getelementbyid("longitude").value; var cur_location = new google.maps.latlng(lat, lng); // prepare request places var request = { location: cur_location, radius: 50000, types: 'bank' }; // send request service = new google.maps.places.placesservice(map); service.search(request, createmarkers); } // create markers (from 'findplaces' function) function createmarkers(

c# - BindingFlags.OptionalParameterBinding varying behaviour in different frameworks. Bug in .NET? -

i've tried force activator.createinstance use constructor default parameters. i've found suggestion, repeated few times on (first comment) http://connect.microsoft.com/visualstudio/feedback/details/521722/system-activator-createinstance-throws-system-missingmethodexception-with-constructor-containing-an-optional-parameter i wanted run on mono , didn't work, throwing missingmethodexception . before filing bug i've made experiment on .net 4.5: class program { static void main(string[] args) { new a(); activator.createinstance(typeof(a), bindingflags.createinstance | bindingflags.public | bindingflags.instance | bindingflags.optionalparambinding, null, new object[] {type.missing}, null); } } class { public a() { console.writeline("first"); } public a(int = 5) { console.writeline("second"); } } of course, result p

jquery mobile - JQueryMobile - position and size of select menu -

i working on jquerymobile page. page contain select element (dropdown) custom menu. trying position menu right below select button , change width width of select button. further stylizing follow well. in firebug figured out jqm changes css classes of select menu (here: select-choice-1-listbox-popup) position attributes. thought might proper approach element , change top attribute. doesn't work though. guess code executed because first alert not show value "top" attribute. <script type="text/javascript"> function positionmenu() { alert(document.getelementbyid('select-choice-1-listbox-popup').style.top); // prints "" document.getelementbyid('select-choice-1-listbox-popup').style.top="300px"; alert(document.getelementbyid('select-choice-1-listbox-popup').style.top); // prints "300px" } </script> [...] <div onclick="positionmenu();" data-role=&

database - CakePHP, number of views -

suppose, db table in project : <table> <tr> <th>id</th> <th>title</th> <th>description</th> <th>created</th> <th>modified</th> <th>........</th> </tr> <tr> <td>1</td> <td>some title</td> <td>some description</td> <td>7/8/2013 8:50</td> <td>7/8/2013 8:50</td> <td>........</td> </tr> </table> now, want number how many times record 1 (id=1) has been seen. , in cakephp. there easy way information ? know created , modified 2 fields values automatically generated cakephp. so, there field or can used here ? marked ......... . or, there other way ? thanks. there's nothing built-in, it's not hard make yourself. (the hard part not increment counter when search engine bots access page if it's reachable them.) in databa

c++ - rapidjson: working code for reading document from file? -

i need working c++ code reading document file using rapidjson: https://code.google.com/p/rapidjson/ in wiki it's yet undocumented, examples unserialize std::string, haven't deep knowledge of templates. i serialized document text file , code wrote, doesn't compile: #include "rapidjson/prettywriter.h" // stringify json #include "rapidjson/writer.h" // stringify json #include "rapidjson/filestream.h" // wrapper of c stream prettywriter output [...] std::ifstream myfile ("c:\\statdata.txt"); rapidjson::document document; document.parsestream<0>(myfile); the compilation error state: error: 'document' not member of 'rapidjson' i'm using qt 4.8.1 mingw , rapidjson v 0.1 (i try upgraded v 0.11 error remain) the filestream in @raanan's answer apparently deprecated. there's comment in source code says use filereadstream instead. #include <rapidjson/document.h> #include <

android - Real-time wireless sensor data transfer. WiFi or Bluetooth? TCP or UDP? -

in project, have been using bluetooth module (panasonic pan1321) transfer real-time data sensors android tablet @ approx 200hz (this rate @ data packets transferred). considering use wifi instead. understanding has longer range , more robust. plus many wireless systems out there use easier integrate system existing setups. intend use bluegiga wf121 wifi node. module offers tcp or udp communication. have no knowledge of tcp or udp. appreciate if has answers following questions: is worthwhile shift bluetooth wifi? will able point-to-point data transfer between wifi module , android tablet (just bluetooth module)? on wifi can achieve data transfer rate of upto 500hz data packet size of approx 80 120 bytes? 500hz more enough real-time feedback in project 200hz suffice. having lower data transfer rate possible increase memory requirement embedded system , can bottle-neck. there time-stamp included in data packet timing of packets not important order of packets more important. pac

node.js - How to read PassportJS session data? -

i think don't quite understand passport.session meant for. says nothing on configuration page . what need save person's data once he's been authenticated, use name in required file, put socket.io code. i've read on google , here, , couldn't find need. don't know how read connect.sess has data once user logged-in. so line do? app.use(passport.session()); note - don't use db. user logs-in id , name, that's pretty basic. i'm not sure if case, finished writing blog uses node , passport, , whenever user logged in credentials stored in req.user (assuming req request json called). might want check there.

regex - Converting a string that is a bit Lisp-like to a Ruby array -

i have string this: s = '+((((content:suspension) (content:sensor))~2) ((+(((content:susp) (content:sensor))~2)) (+(((content:height) (content:control) (content:sensor))~3)) (+(((content:height) (content:sensor))~2)) (+(((content:level) (content:control) (content:sensor))~3)) (+(((content:rear) (content:height) (content:sensor))~3)) (+(((content:ride) (content:height) (content:sensor))~3))))' i'd convert array of strings like: ["suspension sensor", "susp sensor", "height control sensor", "height sensor", "level control sensor", "rear height sensor", "ride height sensor"] here ugly bit of code accomplishes that: a = s.gsub('content:', '') \ .gsub(/\+/, '') \ .gsub(/~\d/, '') \ .gsub(/\((\w+)\)/) { $1 } \ .gsub(/\(([^\(]*[^\)])\)/) { "#{$1}" } \ .gsub(/[\(\)]/,', ') \ .split(/\s?,\s?/) \ .reject {|x| x.strip == ''} i thi

Simple youtube javascript api 3 request not works -

i've tried write simple youtube request search video youtube javascript api v3. this source code: <!doctype html> <html> <head> <script type="text/javascript"> function showresponse(response) { var responsestring = json.stringify(response, '', 2); document.getelementbyid('response').innerhtml += responsestring; } // called automatically when javascript client library loaded. function onclientload() { gapi.client.load('youtube', 'v3', onyoutubeapiload); } // called automatically when youtube api interface loaded function onyoutubeapiload() { // api key intended use in lesson. gapi.client.setapikey('api_key'); search(); } function search() { var request = gapi.client.youtube.search.list({ part: 'snippet', q:'u2' });

animation - re-binding a click event / toggling between 2 elements, simple Jquery Quiz -

so im bit stuck on working on; i'm brand new jquery , javascript world , i'm sure there more efficient way this, now, have. basically when user clicks on 'answer' element animate on page. there 2 answers matching elements animate if corresponding 'answer' clicked. right now, when user clicks on 1 answer multiple times, continues animate; need when user clicks on answer, animates once, , stops, user either leaves it, or when click other' answer', performs animation, becomes re-binded reclick. sort of toggling , forth between 2 answers/corresponding animations. i'm having trouble re-binding becomes available click again. sort of in loop. hope im explaining ok! can point me in right direction this. here js, fiddle below of im at. /*answer1*/ $('ul#quiz li:nth-child(2)').on("click", function() { $(this).addclass('active'); $(this).siblings().addclass('deactive'); $(this).siblings().removeclass(

javascript - How to add both toggle and validate options to x-editable? -

i use x-editable inline editor http://vitalets.github.io/x-editable/docs.html i want toggle inline form other link: $("#how").click(function(e) { e.stoppropagation() e.preventdefault() $("#com").editable({ 'toggle', validate: function(value) { if($.trim(value) == '') { return 'the content can not blank!'; } } }) }) but not work, want know how pass both toggle , validate option. seperate options declaration , 'toggle' part trick: $("#how").click(function(e) { e.stoppropagation(); e.preventdefault(); $("#com").editable({ validate: function(value) { if($.trim(value) == '') { return 'the content can not blank!'; } } }); $("#com").editable('toggle'); }); hope helpful others :)

Create a hierarchical dynamic grid with GWT -

i'm trying create grid in gwt representing hierarchical data. columns different levels same , represent if product available category or not. something that: | b | c | d + product 1.1 x x x + product 1.2 x x x + product 1.3 x x + product 2.1 x + product 2.2 x ... i though use celltable , add handlers show/hide rows, how shall manage hiding descendant? basically, work in mvc. controller catches event, update model, , asks dataprovider refresh display. the simplest can think of when catch event asking hide descendant of, instance, product 2.1, cycle through model objects (a list guess) , update child element accordingly. refresh celltable using appropriate methods on dataprovider.

html - How to - If using IE8 don't load web content -

i have web site functional ie8. have web site displaying banner takes visitor upgrade ie. i'd more... what i'd is, display banner in addition message says "sorry browser not meet requirements view site". don't want load other page content. is there way don't load rest of page in ie if statement? <!--[if lt ie 8]> <div style=' clear: both; text-align:center; position: relative;'> <a href="http://windows.microsoft.com/en-us/internet-explorer/products/ie/home?ocid=ie6_countdown_bannercode"><img src="http://storage.ie6countdown.com/assets/100/images/banners/warning_bar_0000_us.jpg" border="0" height="42" width="820" alt="you using outdated browser. faster, safer browsing experience, upgrade free today." /></a> </div> -- here want don't load else. -- maybe automatically redirect blank page? <![endif]--> the

scala - Better solution to case class inheritance deprecation? -

i working through (admittedly old) programming scala [subramaniam, 2009] , encountered troubling compiler warning when working through section 9.7 "matching using case classes" (see below). here solution devised based on interpretation of error message. how improve upon code solution closer original intent of book's example? particularly if wanted use sealed case class functionality? /** * [warn] case class `class sell' has case ancestor `class trade'. * case-to-case inheritance has potentially dangerous bugs * unlikely fixed. encouraged instead use * extractors pattern match on non-leaf nodes. */ // abstract case class trade() // case class buy(symbol: string, qty: int) extends trade // case class sell(symbol: string, qty: int) extends trade // case class hedge(symbol: string, qty: int) extends trade object side extends enumeration { val buy = value("buy") val sell = value("sell") val hedge = value("hedge&qu

Import error for large negative numbers from CSV to Access using TransferText -

Image
i'm importing data csv file access table. number like -21000000 (-2.1e7). i'm using transfertext import. docmd.transfertext acimportdelim, , "matching report temp", source_folder & "\" & source in "matching report temp" table, field set double. import generates type conversion failure. however, when open csv file in excel , copy offending row, can use paste append add table manually - number doesn't exceed capacity of field. as far can tell, happens large negative numbers. smaller numbers, , positive numbers of same magnitude seem import fine. know can specify import specification in transfertext, don't see way set field type double. how can around problem? don't want have manually track down import errors , append them hand. don't let transfertext create access table you. create access destination table first , assign field types need. when run transfertext , csv data appended existing tabl

Copy a mysql database from one server to another PHP cron Job automated -

ok first off not backup job, , know using phpmyadmin , on. what have live server , test server, people work on live one, modifying it. want database on live server copied test server every night. does have php script run either copy down whole thing (or @ least specific tables)? i'm not confident using command line if there way of doing way pretty specific instructions :p i have dug around seems suggesting doing manually or using third party tools. any appreciated. you this: in mysql host machine: 1- create .sh file 2- inside of sh, put: - mysqldump -u myuser -p mypass mydatabasename > mydumpfile.sql - scp mydumfile.sql user@remote_host:remote_dir 3- add sh cron job, daily execute (or meets requeriments) in remote machine: 1- 1 sh script file(mysqldumpfile.sql) in specific dir 2- line : mysql -u remotemysqluser -p remotemysqlpass database < mydumpfile.sql 3- rm mydumpfile.sql 4- add sh on daily cron 1 or 2 hours past host cron.

javascript - triggering method on a formerly invisible element -

i use 2 jquery plugins slidecontrol , icheck , use script $(document).ready(function(){ $('.slidecontrol').slidecontrol({ 'lowerbound' : 1, 'upperbound' : 10 }); $('.form-horizontal input').icheck({ checkboxclass: 'icheckbox_flat', radioclass: 'iradio_flat' }); $("input").on("ifchecked",function(e){ $(this).parent().next().removeclass("invisible"); }); }); $(this).parent().next() has class .slidecontrol , should display slider, doesn't work. information, ifchecked corresponds check event customized icheck api. tried add $("input").on("ifchecked",function(e){ $(this).parent().removeclass("invisible"); $('.slidecontrol').slidecontrol({ 'lowerbound' : 1,

Using PHP $_GET to grab data and define content -

i want use php 's $_get in url grab data define content within page. basically, want url this- /page.php?p=1 then, php automatically include ../content/1.txt later in code, because 1 after p= . if url /page.php?p=2 , include ../content/2.txt because in url. want automatically, , within page, basic skeleton can put together, , file included in skeleton. want php automatically, instead of having define every single p= , have that. try this... <?php if(isset($_get['p'])){ $filename = $_get['p']; /* validate user input here */ $filename = "../content/" . $filename . ".txt"; //include file include($filename); //or echo link file echo "<a href=\"" . $filename . "\">link</a>"; //or echo file's contents echo file_get_contents($filename); } ?>

javascript - Typescript, signalR and date in an object -

i have strange problem , unsure on causing , not sure how fix in clever way. i have signalr app sends object, contains date client. client written in typescript, although not sure if has influence on or not. the date in object local date, not uat. need show date way, when date arrives in client converted. if client assumes date uat , converts automatically local time of client. i not want converted. want displayed is. 1 solution can think of convert date on server side (c#) string first , send on that. any better ideas? don't know if signalr doing or it's sort of std js behavior. c# developer , confuses me completely. i stuck in datetime issue how solved keep datetime in utc in server , let js handle conversion ,

click - jQuery event stops working after alert -

i have jquery event works fine until alert called. function calls script on the server adds item (inserts row in database) cart. 8 items allowed in cart, when user tries add ninth item, message returned jquery script that not allowed. here jquery script: jquery(document).on('click', 'a.add.module, a.remove.module', function(e) { if (blnprocessing == true) { return false; } else { blnprocessing = true; } e.preventdefault(); objlink = jquery(this); strlink = objlink.attr('href'); if (objlink.hasclass('add')) { objlink.text('adding'); } else { objlink.text('wait'); } jquery.get(strlink, function(data) { if (data.success) { if (data.success != true) { alert(data.success); // message says not allowed -- part stops script functioning further } else { // part works jquery('#cart

Transform standard output from Gradle's Exec task on the fly? -

is possible transform standard output logs gradle exec task produces, on fly? we have task executing command line tool takes minute run logs a lot . filter out few of lines , log them show progress without cluttering build log. you set own outputstream implementation exec.setstandardoutput . or execute shell command runs tool , filters output.

c++ - Recursive Reverse Function -

i wondering whether explain how small code snippet works. void reverse(char *s) { if(*s) reverse(s+1); else return; cout << *s; } when call function in main, supposedly prints out reverse of string put in (ie. hello cout olleh) don't understand how. understand it, if statement increases value of s until reaches end of string, printing out each value in string goes. why doesn't re-print string. missing something. (sorry btw, new c++ , recursive functions) consider how "hello" string stored in memory: let's address of 'h' character happens 0xc000 . rest of string stored follows: 0xc000 'h' 0xc001 'e' 0xc002 'l' 0xc003 'l' 0xc004 'o' 0xc005 '\0' now consider series of invocations of reverse : initial invocation passes 0xc000 ; call of reverse inside reverse passes s+1 , next level gets 0xc001 ; next 1 gets 0xc002 , , on. note each level calls next level, un

ios - UIButtons receiving touch events when added directly to scrollview but not indirectly -

i have 10 uibuttons stacked side side in app , , total dimensions of buttons 640x96. if add these buttons directly uiscrollview, register touch events , scrollable. but if try add them plain uiview, add uiview scrollview, dont work. this code: - (void)viewdidload { [super viewdidload]; uiview *fview = [[uiview alloc] init]; fview.frame = cgrectmake(0, 0, 640, 96); fview.backgroundcolor = [uicolor blackcolor]; [fview setuserinteractionenabled:yes]; [_sv setuserinteractionenabled:yes]; (int i=0; i<10; i++) { uibutton *button = [uibutton buttonwithtype:uibuttontypecustom]; button.frame = cgrectmake(64*i, 0, 64, 96); [button settitle:@"click me!" forstate:uicontrolstatenormal]; [button addtarget:self action:@selector(buttonclicked:) forcontrolevents:uicontroleventtouchupinside]; [fview addsubview:button]; } [_sv addsubview:fview]; _sv.contentsize = cgsizemake(640, 96); } -(void)buttonclicked:(id)sender { nslog(@"c

python - SWIG void * parameters -

i have 2 structs (from third party lib actually) in swig .i file follow form: typedef struct my_struct { void* pparameter; unsigned long plen; } my_struct; %extend my_struct { my_struct() { my_struct *m= new my_struct(); m->pparameter = null; m->plen = 0; return m; } } typedef struct another_struct { char * another; unsigned long len; } another_struct; %extend another_struct { another_struct() { another_struct *p= new another_struct(); p->another = null; p->len = 0; return p; } unsigned long __len__() { return sizeof(another_struct); } } the pparameter in my_struct void * because can char * or pointer struct (such another_struct). handling char * mapping simple using %typemap(in) void* = char*; , attempt use struct fails. here's i'd see in python: s = my_struct() = another_struct() s.pparameter = # should pass struct pointer s.ppar

interface - Is it possible to convert an anonymous class from Java to JRuby? -

i working on implementing jruby wrapper around snmp4j-agent library, found here: website: http://www.snmp4j.org/ javadocs: http://www.snmp4j.org/agent/doc/ it's been pretty fun far, having trouble deciphering following piece of java code implement in jruby: server = new defaultmoserver(); vacmmib = new vacmmib(new moserver[] { server }); the problem - far can tell - casting new moserver[] (which interface) creates anonymous function passed server object, , can't seem find right way express jruby. i've included information java classes: defaultmoserver defined as public class defaultmoserver implements moserver { public defaultmoserver() { ... } ... } javadoc: http://www.snmp4j.org/agent/doc/org/snmp4j/agent/defaultmoserver.html vacmmib defined as public class vacmmib implements mogroup, mutablevacm { public vacmmib(moserver[] server) { this.server = server; ... } ... } javadoc: http://www.snmp4j

Java floating point clarification -

i reading java puzzlers joshua bloch. in puzzle 28, not able understand following paragraph- this works because larger floating-point value, larger distance between value , successor. distribution of floating-point values consequence of representation fixed number of significant bits. adding 1 floating-point value sufficiently large not change value, because doesn't "bridge gap" successor. why larger floating point values have larger distances between values , successors? in case of integer , add 1 next integer , in case of float , how next float value? if have float value in ieee-754 format, add 1 mantissa part next float? you can think of floating point base-2 scientific notation. in floating point, limited fixed number of bits mantissa (a.k.a. significand ) , exponent. how many depends on whether using float (24 bits) or double (53 bits). it's little more familiar think of base-10 scientific notation. imagine mantissa limited

javascript - Two identical Strings that don't equal each other -

hi i'm having trouble comparing 2 strings should same when evaluate in alert(f==g) evaluates false. var otrackcarriers = { "9045": [ ["a"], ["b"], ["c"] ], "9046": [ [" "] ] }; var oheadingcarriers = { "ripplefold": [ ["a"], ["b"], ["c"], ["d"] ], "pinchpleat": [ ["c"], ["d"] ] }; var headinglist = oheadingcarriers["ripplefold"]; var tracklist = otrackcarriers["9045"] var f = (tracklist[0].valueof()); var g = (headinglist[0].valueof()); alert(f); alert(g); alert(f == g); is because i'm putting 2 values array beforehand? here's running http://jsfiddle.net/sqrst/17/embedded/result/ help ["a"] array. can either string value tracklist[0][0] , headinglist[0][0] or check if every string contained in tracklist[0] , headinglist[0] equals. usually, 2 arrays differents when comparing them d

java - Error Code Returned when using Midi Sequencer -

i have been playing midi sequencer , doing exercise involving repainting squares on panel in random colors, shapes, , locations based on beat of music using controleventlistener. when on laptop, works fine. however, when on pc, error: aug 07, 2013 1:10:11 pm java.util.prefs.windowspreferences <init> warning: not open/create prefs root node software\javasoft\prefs @ root 0x80000002. windows regcreatekeyex(...) returned error code 5. build successful (total time: 27 seconds) the program works fine. compiles , it's supposed do, and, stated earlier, have no problems exact code on laptop. also, of code taken out of book java, made few changes panel tweak code same thing little differently. know code means? i've googled , found nothing. book states nothing kind of code. any appreciated. thank in advance time reading , time spend helping question. this code in entirity: import javax.swing.*; import java.awt.*; import javax.sound.midi.*; public class check implemen

c# - XNA - Moving an animated rectangle horizontaly (no user input, but timer) -

here want move animated rectangle horizontaly without user input, using timer, maybe? animated rectangle should move left , right (from starting point end point, whole path = 315 pixels). mean 315 pixels between point 1 (start on left) , point 2 (end on right). here's code: variables: //sprite texture texture2d texture; //a timer variable float timer = 0f; //the interval (300 milliseconds) float interval = 300f; //current frame holder (start @ 1) int currentframe = 1; //width of single sprite image, not whole sprite sheet int spritewidth = 32; //height of single sprite image, not whole sprite sheet int spriteheight = 32; //a rectangle store 'frame' being shown rectangle sourcerect; //the centre of current 'frame' vector2 origin; next, in loadcontent() method: //texture load texture = content.load<texture2d>(&q

How to do event handling in Android similar to C# -

as aware can various types of event handling based on completion of background thread on c# , aware can use asynctask in android handle background threads. in completion possible event handling tasks on android. afaik onpostexecute can used throw messages or ui updates can trigger event @ point in code? if can provide me small snippet or tutorial. has been nagging quite while. thanks you can trigger ui events within method on runonuithread() .

mongodb - does enableLocalhostAuthBypass override --auth ? -

in docs ( link ) says "specify 0 disable localhost authentication bypass. enabled default" enablelocalhostauthbypass. when start mongod --auth: mongod --port 30xxx --dbpath=/home/dev/xxxx --auth and connect via localhost: mongo --host localhost --port 30xxx mydb and try anything: > show collections wed aug 7 11:07:50.420 javascript execution failed: error: { "$err" : "not authorized query on configuration.system.namespaces", "code" : 16550 bzzt, no go. can connect -u -p , run show collections though. from docs sounds connecting via localhost bypass auth default. that's not i'm seeing. docs unclear? reading wrong? enablelocalhostauthbypass used case when have no user defined @ auth enabled on mongodb , don't want able connect @ all. not meant turn off authentication localhost altogether. as have user defined, enabledlocalhostauthbypass nothing , have authenticate first. it described in

ember.js - Rerouting from existing Rails app to Ember -

intro this first attempt @ ember (existing rails app) , there great resources out there on interweb, given have read them , still wanting more great check notes here. i have new model: newslink have built api it: api/v1/newslinks.json api works: http://localhost:3000/api/v1/newslinks.json data {"newslinks":[{"id":1,"title":"a sample post","navlink":"this simple post record."}]} code the issue ember seems letting route slip through hands (something did wrong in code below, i'm sure): application.js //= require jquery //= require jquery-ui //= require jquery_ujs //= require jquery-fileupload/basic //= require jquery-fileupload/vendor/tmpl //= require chosen-jquery //= require bootstrap //= require bootstrap-notify //= require jquery.limit-1.2.source //= require bootstrap-switch //= require handlebars //= require ember //= require ember-data //= require_self //= require app app.js a

java - Unable to use VisualVM profiler with Maven Jetty plugin -

i'm attempting profile java 7 application executed using mvn jetty:run visualvm 1.3.6. cpu shows unavailable, , profile tab lists following error: warning! class sharing enabled jvm. can cause problems when profiling application , may crash it. please see visualvm troubleshooting guide more information , steps fix problem: https://visualvm.java.net/troubleshooting.html#xshare. i able profile other application normally. the visualvm log shows following error number of times: java.io.ioexception: unable open socket file: target process not responding or hotspot vm not loaded potentially relevant details: - osx 10.8.3 - both app , visualvm running under jdk 1.7u25 i can presume downvotes related fact there documented bug related issue advice set xshare:off , i'll include this link bug report, lists fixed after 1.6u6. running 1.7u25, not apply me. for mac try passing these vm args: -xverify:none -xshare:off if you're working jconsole , other jmx

async javascript function issue -

i having problem javascript function callback. for example have code this: var base = { // constructor of class createnew: function(name) { var base = {}; base.ajax = function(callback, url) { // create xmlhttprequest object var httprequest; if (window.xmlhttprequest) { httprequest = new xmlhttprequest(); } else if (window.activexobject) { httprequest = new activexobject("microsoft.xmlhttp"); } httprequest.onreadystatechange = function() { // check status of our request // called on every state change if (httprequest.readystate == 4 && httprequest.status == 200) { // call callback function callback.call(httprequest.responsetext); } }; httprequest.open("get", some_url, true); httprequ

android - Get _ID Calendar.Events changed on provider -

searching here , on internet, found several examples of how capture updated calendar. did not find how capture id ("_id" events table). has done similar. i'm trying this: public class calendarreceiver extends broadcastreceiver { @override public void onreceive(context context, intent intent) { log.d("calendar", "updated " + intent.touri(intent.uri_intent_scheme)); } } and manifest: <receiver android:name=".calendarreceiver"> <intent-filter> <action android:name="android.intent.action.provider_changed"/> <data android:scheme="content"/> <data android:host="com.android.calendar"/> </intent-filter> </receiver> the log invoked when event on calendar updated, need _id of edited event. i believe intent can see not know how capture.

sql - MySQL count columns in table by name -

is possible count number of columns in table name? eg select count(*) information_schema.columns column '%name%' , table_schema = 'db_name' , table_name = 'table_name' i have table adds columns table custom fields added user , need count added columns use result in while loop yes, possible. there's chance need use column_name in where in place of column -- @ least, that's how listed in mysql docs : select count(*) information_schema.columns column_name '%name%' , table_schema = 'db_name' , table_name = 'table_name'

animation - android animating buttons from offscreen bottom to onscreen are blank -

i have relativelayout container 5 buttons on it. when use translationanimation offscreen (below screen), buttons blank until animation done. @ end of animation, explicitly draw buttons , appear in correct locations. i have similar container , buttons animated onscreen right offscreen. container shows of buttons during animation , after expect to. also, when animate first set of buttons down offscreen location below, visible during entire animation. the problem happens when animating below screen onscreen.

Best way to display HTML in Android with images and disables links -

i have html content want display in activity, disable links - in fact disable ability interact, except viewing , scrolling. i'm not sure if best way using webview (how disable interactivity?) or textview. the html may refer images , content local - i.e. don't need point url, have html local string - although string has been obtained dynamically in part of app , not same time, nor images local. i happy have app dynamically edit content remove tags, there may more elegant solution? what's best approach in instance? i'm not sure if best way using webview (how disable interactivity?) or textview. if html fits within boundaries of supported html.fromhtml() -- , here's blog post of mine long time ago giving idea of supports -- welcome use prepare spanned use textview . i happy have app dynamically edit content remove tags, there may more elegant solution? it depends upon nature of "interactivity". simple hyperlinks, attach

c# - Display "Select an item" in Combobox when selectedItem is null -

i have wpf combobox bound list of viewmodel objects. selecteditem null, , combobox display blank. when selected item null, prefer combobox display "select item" guide user select combobox. sort of way, text boxes contain gray text such "enter user name" any ideas on how this? edit: i ended using suggestion overlay textbox, , change visibility based on value of selecteitem try this- change itemssource , selectedvalue according code.i showed how can achieve this.. <combobox height="23" name="combobox1" width="120" itemssource="{binding ocstring,mode=twoway,updatesourcetrigger=propertychanged,relativesource={relativesource ancestortype=window}}" selectedvalue="{binding selected,mode=twoway,relativesource={relativesource ancestortype=window},updatesourcetrigger=propertychanged}"> <combobox.style> <style targettype="{x:type combobox}">

c# - How to register two WCF service contracts with autofac -

i have wcf service implements 2 service contracts... public class myservice : iservice1, iservice2 and self-hosting service... host = new servicehost(typeof(myservice)); everything working fine when service implemented 1 service contract, when attempt set autofac register both this: host.adddependencyinjectionbehavior<iservice1>(_container); host.adddependencyinjectionbehavior<iservice2>(_container); ... throws exception on second one, reporting: the value not added collection, collection contains item of same type: 'autofac.integration.wcf.autofacdependencyinjectionservicebehavior'. collection supports 1 instance of each type. at first glance thought saying 2 contracts somehow being seen same type on second reading believe saying autofacdependencyinjectionservicebehavior type in question, i.e. cannot use twice! and yet, found this post explicitly showed using multiple times in different form: foreach (var endpoint in host.description.endpo

css - Android web app rendering font/type strangely (shifting up) -

i'm taking mobile web app design stages development stages. during process, i'm importing custom font family used in interface, via @font-face. tried using strictly otf before , getting strange font rendering issue type being shifted upwards 4px (2px if not high-density). ios rendering , keeping in right place, desktop experience. figuring font rendering issue, went , added eot, woff, tff, , svg @font-face properties. still, same issue persisted. is there known reason why android experience shifting type upwards?

multithreading - Programmatically find the number of CPUs on a machine (CPUS, not cores) -

is there way find programmatically (c code only, linux os) number of physical cpus (not cores) ? (something similar sysconf(_sc_nprocessors_conf)) all solutions found on site explain how find number of cores. need information set threads exchange data run on same physical cpu. can information /proc/cpuinfo prefer chose second option.

java - How do I import a class in a package into a jsp file? -

it seems have correctly imported package , class, yet reason, variable user not found. user object of type string created in class addto. <%@ page import= "package1.addto" %> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>jsp page</title> </head> <body> <p> shopping cart</p> <%= system.out.println(user.name); %> </body> </html> you import class package, , not it's fields. that being said, should add addto object request attribute in servlet, , access attribute in jsp using el . should not use scriplets in new code. in servlet do: request.setattribute("addto", addto); then in jsp, can access user property of attribute addto as: <p> shopping cart</p> ${addto.user} <!-- access user property of addto attribute, object of type `addto` --> see also: how

rest - Hypermedia API Link Traversal & Practicality -

i've been trying build hypermedia based api. things seem working well. when fetch /books/isbn/12313441213 this: <book> <id>123</id> <name>hypermedia apis</name> <description>basic api design techniques</description> <tags> <tag>rest</tag> <tag>api</tag> <tag>service</tag> </tags> <authors> <link rel="author" uri="/authors/id/22" /> <link rel="author" uri="/authors/id/18" /> </authors> </book> now can traverse authors resource. when fetch /books/by/author/id/18 this: <books> <book id="123"> <name>hypermedia apis</name> <link rel="self" uri="/books/id/123" /> </book> <book id="191"> <name>chef recipes rails developers</name> <link rel="self" uri="/bo

LinkedIn API oauth issues with sending message node.js -

i have same issue: how post linkedin "share" node-auth? essentially using linkedin-js npm module works great requests. using module in conjuncture passport , generating oauth token , secret. when post did not work messaging went oauth dependency library , changed content-type headers application/json , x-li-format headers json. also, other bases covered. have "w_messages" set in scope , other requests working. i not need x-li-format header since have application/json header. thing can think of access tokens off (perhaps step missing - unlikely since other requests requiring authentication work) or plaintext signature thrown off application/json content-type (following error not thrown): if( signaturemethod != "plaintext" && signaturemethod != "hmac-sha1") throw new error("un-supported signature method: " + signaturemethod ) i went error message: { statuscode: 401, data: '<?xml version="1.0" enc

node.js - How set start page in nodejs -

i use node js without frameworks etc. , have problem, don't understand how set "start html page" first request server. i tried this var server = new http.server(); server.listen(1137, '127.0.0.1'); server.on('request', function(req, res) { fs.readfile('../public/index.html', function (err, html) { if (err) { throw err; } else { res.write(html); res.end(); } }); }); when request 127.0.0.1:1137 - got html in browser, links css/js files isn't correct , how can fix don't know :( i want html page ../public/index.html in browser when first request server. my server location project/server/server.js my html-page location project/public/index.html your page includes references images , stylesheets, said don't work. well, responding every single http request contents of specified html page. when browser parses html, see image , stylesheet links , i

ruby on rails - Accessing attributes from other model -

i have 3 models : user, location, picture. location has several pictures, , user can provide several pictures. use rabl render result of query in json. problem don't know how display user name user id in relation ? i designed models : picture : class picture < activerecord::base ... belongs_to :location belongs_to :user ... end user : class user < activerecord::base ... has_many :pictures accepts_nested_attributes_for :pictures attr_accessible :name, :email ... end location : class location < activerecord::base ... has_many :pictures, :dependent => :destroy accepts_nested_attributes_for :pictures attr_accessible :name, :address ... end my rabl file : object false collection @locations attributes :id, :name, :address child :pictures attributes :id, :location_id, :url, :user_id, :created_at end i tried add :user_name in child :pictures block, fails... how can access ? edit : when add node(:user_name) { |pictur

web applications - Web App to run Python Scripts - Run as a background process. -

i have python script want user run in server, out giving ssh login permission. got web app below link. how connect webpage python mod_wsgi? here modified version that's working me import web class echo: def get(self): return """<html><form name="script-input-form" action="/" method="post"> <p><label for="import"><font color=green><b>press button import csv</b></font)</label> import: <input type="submit" value="importcsv"></p> </form><html>""" def post(self): data = web.input() return data obj = compile('execfile("importcsv.py")', '', 'exec') result = eval(obj, globals(), locals()) web.seeother('/') urls = ( '/.*', echo, ) if __name__ == "__main__": app = web.appli

timer - javascript timeout in loop -

i'm learning javascript fun, , having weird problem. i'm trying create own fade-in function. however, code doesn't work, shows "content" div in full opacity. the setcontentopacity function does work, i've tested , works charm. ideally think should happening 1000 "settimeout" calls should placed on "stack", first 1 setting opacity low no timeout, second 1 setting opacity little higher small timeout, way last call sets opacity 1000 3000 timout. so basically, should setting opacity 0 right away, ~333 in 1 second, ~666 in 2 seconds, , 1000 in 3 seconds. think logic sound here; calls setting opacity should resolve in manner on time creates fade in effect. so here's relevent code: <script language='javascript' type='text/javascript'> //takes value 0-1000 function setcontentopacity(value) { document.getelementbyid('content').style.opacity = value/1000; document.getelementbyid('content'

python - UnicodeDecodeError: 'utf8' codec can't decode byte - Euro Symbol -

i build connection google finance api gives me stock quotes. working fine until switch courses europe. these contain € symbol , following error: traceback (most recent call last): file "c:\users\administrator\desktop\getquotes.py", line 32, in <module> quote = c.get("sap","fra") file "c:\users\administrator\desktop\getquotes.py", line 21, in obj = json.loads(content[3:]) file "c:\python27\lib\json\__init__.py", line 338, in loads return _default_decoder.decode(s) file "c:\python27\lib\json\decoder.py", line 365, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) file "c:\python27\lib\json\decoder.py", line 381, in raw_decode obj, end = self.scan_once(s, idx) unicodedecodeerror: 'utf8' codec can't decode byte 0x80 in position 0: invalid start byte the following code using. guess error appears while json trying processing string can not resolve euro symbo

objective c - NSPredicates and NSSets, how to reject things in the intersection of two sets? -

my code looks like: nspredicate* pred = [nspredicate predicatewithformat:@"(title in %@)", prev_set]; nsset* remainingset = [goal_set filteredsetusingpredicate:pred ]; where prev_set , goal_set 2 different sets. "title" in property in objects contained in both sets. my objective goals rejected if have been met (each goal having unique title). if have predicate "title in %@" of objects in goal_set rejected. if use "not("title in %@)", none of objects in goal_set rejected. if print out both sets, see have (but not all) objects in common (that is, title same). am confused use of "in" nspredicates? how accomplish objective? try [nspredicate predicatewithformat:@"not (title in %@.title)", prev_set] . your predicates assume prev_set contains nsstring objects, according description, contains objects have string property , never contain titles themselves. hope makes sense.

c# - Why does multithreading give a worse performance here? -

i enumerate through bitarray setting every second bit false. now i'd speed splitting 2 threads.. weird reason though, time per thread half amount of work takes 64% more time, , wonder why's that? could due kind of cpu caching effect? how do properly? i have tried 8 threads lambda expressions around ~1400 ms, in single threading constandly got 850 ms. when let single thread work, took me 830 ms. don't understand, knowing cause here? code: class program { static int count = 0x10000000; static int half = count / 2; static bitarray bitarray = new bitarray(count); static unsafe void main(string[] args) { stopwatch sw = stopwatch.startnew(); #if single (int = 0; < bitarray.count; += 2) bitarray.set(i, true); #else thread thread1 = new thread(thread1); thread thread2 = new thread(thread2); thread1.start(); thread2.start();