Posts

Showing posts from March, 2014

How to get the name of an object in an associative array (javascript) -

lets suppose have object var clicorp14={ "id":13, "url":"corp_longboard.html", "logo":"img/corp/logolongboard.png", "alt":"longboard store", "name":"longboard", }; i want put text "alt" in var. don't want put "longboard store", want put text "alt". how access object? object.keys(clicorp14); // -> ["id", "url", "logo", "alt", "name"] note object.keys() es5+ method, , available in ie9+ (although easy polyfill).

angularjs - Ng-if not refreshed when input changed -

problem i have form subsequent fields not show until previous ones have been completed. in order @ previous ng-model variable. if null (ie not been filled out) fields not show. works great select, however, when add text input next field fails show up. example var app = angular.module('insight', []); app.directive('insightform', function() { return { restrict: 'ea', scope: {}, controller: insightformcontroller, controlleras: "ctrl", replace: true, template: "<div class=\"gradient-background stage1\">\n" + " <div class=\"location\"><span>please select location</span><span>\n" + " <select ng-model=\"location\">\n" + " <option value=\"us\">united states</option>\n" + " <option value=\"eu\">europian union</option...

android - Remember ListView selection using SQL - AFTER closing the App -

having thoroughly serched before, not find question me. my issue having listview, automatically gets populated sql-database upon opening app. now, user can make selection 1 item in list. selection treated public void onitemclick() in order increase usability, i'd have selection remembered after closing , re-opening app. i've tried everything.. hope can me idea. create column in data base called checked, (create table ..... checked int...) when user checks listitem in onlistitemclick { sqlitedatabase db = getdb(); //set unchecked db.exec("update ..table.. set checked = 0"); //set choice checked db.exec(update ...table... set checked=1 id = "+cellid+"); } then on start in list adapter value of checked out of database , update ui accordingly. i have used pattern in several apps , work well.

dronekit python - High-rate telemetery / position / attitude -

from high level, trying combine pixhawk telemetry data (specifically gps position , vehicle attitude) other sensor data on rasppi 2, connected via dronekit. have pixhawk connected via gpio header, @ 115200 baud rate on telem 1 port. -i turned sr_1 telemetry rates 10hz. -running logging code @ 10hz, have verified similar results @ higher rates. -i using 'attributes' function, i.e. curr_attitude = vehicle.attitude the first problem seeing updates come through @ ~3-4 hz. there reason discrepancy between sr_1* rates , vehicles attributes? my seconds question: there better/faster way raw attitude , position information? it possible there stuff being sent. when channel full, ardupilot start dropping streams, in order make space packets thinks more important. solution decrease other stream rates, streams sent before it. streams sent in order: params //don't worry one. raw_sens ext_stat position raw_ctrl rc_chan extra1 extra2 extra3 so recommend decrea...

php - How to redirect all request to subfolder with it's own .htaccess file -

i know such questions has been answered lot of time, neither of found answers works me. have following url http://dummy.com/api access root folder going have project (laravel project). deploying remote hosting have no acceess parent directories. project (simple laravel project) consists lot of folders, way should placed in parent directories ( app,bootstrap,config... ) , public folder main index.php of laravel project located. have url http://dummy.com/api/public/index.php directory includes own .htaccess file following content. <ifmodule mod_rewrite.c> <ifmodule mod_negotiation.c> options -multiviews </ifmodule> rewriteengine on # redirect trailing slashes if not folder... rewritecond %{request_filename} !-d rewriterule ^(.*)/$ /$1 [l,r=301] # handle front controller... rewriterule ^ - [e=http_authorization:%{http:authorization}] rewritecond %{request_filename} !-d rewritecond %{request_filename} !-f ...

database - Insert SQL statement on access which would let me extract data according to data from another table? -

so far i've managed extract data 1 table another. insert town ( town_name) select distinct locality students_record locality <> null ; what tried there error locality not found or tried different methods sub queries dont seem return anything. what i've thought like first extracted town_names previous query, then... insert town(country) select id country town_name = (select locality students_record) , country_name = (select country students_record) the town table connected via country country id (country) country (town). difficulty i'm facing ; i cannot automatically insert towns along country fk (the countries extracted students_records simple sql statement using distinct). town names being extracted table students_record denormalized table in i'm trying fix. so question is... how indicate country id in insert statement correspond distinct locality (student_records) match country in student_re...

optimization - Compute new column based on values in current and following rows with dplyr in R -

i have big dataset (10+ mil x 30 vars) , trying compute new variables based on complicated interactions of current ones. clarity including important variables in question. have following code in r interested in other views , opinions. using dplyr package compute new columns based on current/following row values of 3 other columns. (more explanation below code) i wondering if there way make faster , more efficient, or maybe rewrite it... # main function-data dataframe, windowsize , ratio ints computenewcolumn <- function(data,windowsize,ratio){ #helper function used in second mutate down... # args ints, return boolean out windowahead <- function(timeto,window,reduction){ # subset original dataframe-only observations values of # timetogo between timeto-1 , window (basically following x rows # current one) subframe <- data[(timeto-1 >= data$timetogo & data$timetogo >= window), ] isthere <- any(subframe$price <...

angularjs - IQueryable cannot implicity convert type using .single or .first -

public iqueryable<project> getprojectpid(int projectid) { return _ctx.projects.include("tenninehours").where(r => r.projectid == projectid).firstordefault(); } i trying single result here not have use ng-repeat base single object project should return. have tried without .include well. or should filter result in controller. have made effort there without results. error cannot implicitly convert type 'tennineapp.data.project' 'system.linq.iqueryable'. explicit conversion exists (are missing cast)? new linq! still working on this. thanks, because attempting return iqueryable of project. return single project object; public project getprojectpid(int projectid) { return _ctx.projects.include("tenninehours") .firstordefault(r => r.projectid == projectid); }

android - The correct way of using Mediaplayer to show Streaming Videos -

i've been looking best way of playing videos. tried many ways, in someway couldn't see video , heard audio. , showed video stop playing in 5 seconds. tried understand lifecycle , everytime try make work happens. here code i've been struggling past 6 days. don't know wrong make app crash. can give me best implementation of media player streaming videos using media player? package playingpackage; import android.app.fragment; import android.app.progressdialog; import android.media.audiomanager; import android.media.mediaplayer; import android.os.asynctask; import android.os.bundle; import android.support.annotation.nullable; import android.view.layoutinflater; import android.view.surfaceholder; import android.view.surfaceview; import android.view.view; import android.view.viewgroup; import com.example.ptivi.ptivi.r; import java.io.ioexception; /** * created peyam on 2015-07-22. */ public class playvideo extends fragment implements mediaplayer.onpreparedlisten...

javascript - Bootstrap showing and collapsing table rows -

so writing program uses php collect data database , data creating html strings shown below. i echoing data in html file , using bootstrap create table, , table comes out perfectly, looking able have user using website able click on row , more detailed data row clicked on comes down. code wrote try , accomplish looks so: $htmlstr .= '<tr data-toggle="mycollapse" data-target="#details" class="accordion-toggle">'; $htmlstr .= '<td>' data '</td>'; $htmlstr .= '<td class="text-center">' . number_format(more data) . '</td>'; $htmlstr .= '<td class="text-right">' . round(percentage of data) . '%</td>'; $htmlstr .= '</tr>'; $more = functionfordetails(details looking for); $htmlstr .= $more; where functionfordetails() returns: $htmlstr .= '<tr id="details" class="mycollapse">'; $htmlstr .=...

javascript - Set origin when parsing HTML document -

my javascript app retrieves webpage xhr parses this: var el = document.createelement( 'html' ); el.innerhtml = xml; var links = el.getelementsbytagname( 'a' ); in process, links' href tags reinterpreted relative this document, links http://localhost:8000/download.zip . i tried hacking way around it: if (link.origin === document.origin) { link.href = link.href.replace(link.origin, h.url.replace(/\/$/, '')); } but can't distinguish between foo.org/bar (foo.org/bar/download.zip) , foo.org/bar.php (foo.org/download.zip), , don't want go down rabbit hole of working out substitutions perform. i tried injecting either <base href=...> or <xml:base=xxx> document, didn't work. what missing? seems common enough need? i'm not using jquery or similar (and can't.)

c# - Converting a part of hard coded sample project in MVC to soft code (pulling the data from the database) -

i'm following along sample project this website . reached point constructing action method in action method hardcoded data using. i tried think of pull same data database failed. still beginner mvc i'm asking assistance in doing because i've got project in mind , long same line sample project. the action method looks public actionresult index() { var evalvm = new evaluation(); var q1 = new question { id = 1, questiontext = "what favouritelanguage" }; q1.answers.add(new answer { id = 12, answertext = "php" }); q1.answers.add(new answer { id = 13, answertext = "asp.net" }); q1.answers.add(new answer { id = 14, answertext = "java" }); evalvm.questions.add(q1); var q2 = new question { id = 2, questiontext = "what favourite db" }; q2.answers.add(new answer { id = 16, answertext = "sql server" }); q2.answers.add(new answer { id = 17, answertext = "mysql" }); ...

macvim - vim syntax highlighting - highlight only 128 characters -

Image
my vim editor highlight 128 characters in string. in .vimrc file set syntax enable. when change color scheme it's same 128 characters highlighting. check .vimrc. suspect have 'set synmaxcol=128'. or maybe it's weird default on system. in vim :help synmaxcol more details.

matlab - How to use user-created class in Guide-created GUI -

i creating application in guide. i've found using "handles" structure provided guide store data leads messy/hard read code. decided best solution create own class handle data store methods used in callback functions. i've been able call constructor method in "annotatorgui_openingfcn" (seen below), when call class method in different callback function, can't find reference class. furthermore, line "annotatorengine = ...." underlined in yellow statement "value assigned variable might unused". seems class declaration doesn't propagate throughout entire gui script. want avoid using "handles" structure or declaring "annotatorengine" global. thanks! edit: far seems thing has worked declaring class object global. however, still annoying because in each callback, have write "global annotatorengine". % --- executes before annotatorgui made visible. function annotatorgui_openingfcn(hobject, eventdata, h...

html - Vertically responsive panel with overflow scroll -

could give new ideas how realize following? if possible). the content of left panel changed dynamically angular. so, can have several items or, example, 50 items on panel. in accordance that, height of panel shorter or overflow hidden displayed. here fiddle draft https://jsfiddle.net/b9on9gup/7/ first of div class="filter-title" should fill 100% height. second, title container shouldn't in scrolling area. scroll should inside div class="radio-container" . add class .shown on div class="main-container" display bottom panel. additional condition displaying , without scroll (different quantity of items, different screen resolutions etc). in fiddle trying different ways, css properties can odd. <body> <div class = "main-container"> <div class="left-panel"> <div class="filter-container"> <div class="table"> ...

javascript - change centre of google map with change in city name from action method in controller -

i have simple java script code this--- <script type="text/javascript"> $(document).ready(function () { var localityurl = '@url.action("fetchlocalities")'; var sublocalityurl = '@url.action("fetchsublocalities")'; var localities = $('#selectedlocality'); var sublocalities = $('#selectedsublocality'); $('#selectedcity').change(function () { codeaddress(); localities.empty(); sublocalities.empty(); $.getjson(localityurl, { id: $(this).val() }, function (data) { if (!data) { // codeaddress(); return; } localities.append($('<option></option>').val('').text('please select')); $.each(data, function (index, item) { localities.append($('<option><...

firefox - Cross-Origin Failure with Express Node Server -

my code works on localhost when uploaded debian vps server not fire. curl -h -origin request works perfectly... i've tried please help!! lol here firefox-firebug error::: cross-origin request blocked: same origin policy disallows reading remote resource @ http://localhost:10005/threadpreview . (reason: cors request failed). this huge problem me. i've tried every access-control-allow-headers/methods/origin combination possible. @ loss. i've tried preflight requests. shouldn't need 1 i've still tried no avail. could server security? working off of vps debian squeeze server.... firewall maybe? this portfolio need online can myself employed.... sigh! please , thanks!! when accessing webpage on remote server can't use local host. you want make request against vps ip address. or domain name if have it. calling local host on browser client going request resources client computer opposed server

django - Twisted connections timeout under heavy load -

we have django web app serves moderate number of users, running on ubuntu machine 8 cores , @ least 32gb ram. have no problems users connecting via browser. however, on backend (on same server) running twisted server. django webapp tries connect our twisted server, after 1100-1200 such connections (including bunch of persistent connections other devices on backend), connections start timeout. our twisted server worked fine under low load server seems unable handle new connections django. connections time out. not see wrong our code (which have been working on couple of years should pretty stable). have set our soft , hard ulimits in /etc/security/limits.conf 50000/65000 , have upped somaxconn 65536. print of limits our twisted process listed below. total number of files across tope 25 processes on 5000. unfortunately still cannot more 1100-1200 simultaneous connections our twisted server. things should @ make our twisted connections start connecting again? there other sysctl or oth...

javascript - Bitwise operation on octal number -

i want bit operation in javascript on variable. have numbers: min: 153391689 (base 10) - 1111111111 (base 8) max: 1073741823 (base 10) - 7777777777 (base 8) now want use variable storing 10 "vars" options 0 7. that, need , set every octal digit (meaning 3 bits). unfortunately, didn't made it, came something: var num = 153391689; function set(val, loc) { num |= val << (loc * 3); } function get(loc) { return (num & 7 << loc * 3) / math.pow(8, loc); } thank you. as mentioned amit in comment, set function doesn't clear bits before setting value, if there value @ location new value ored it. you can clear location anding number bitwise not of bitmask position. applying bitwise not mask means bits not in location interested in remain set. function set(val, loc) { num &= ~(7 << (loc * 3)); // clear bits num |= val << (loc * 3); // set bits } note bra...

mysql - SQL Order by Letters Ascending and Numbers Descending Same Column -

i trying sort column via mysql. sort should ascending letters descending numbers. might bit confusing here example: data sorted: access 2003 access 2007 access 2013 aliens excel 2003 excel 2007 happy powerpoint 2003 powerpoint 2007 becomes access 2013 access 2007 access 2003 aliens excel 2007 excel 2003 happy powerpoint 2007 powerpoint 2003 also point out fields in question follow same pattern above: name followed year after space. if isn't possible using built in mysql function. potentially split field 2 fields after first space , sort number first actual field itself? you can use code separate field in 2 fields , order them required. select substring_index(substring_index(fullname, ' ', 1), ' ', -1) string_name, trim( substr(fullname, locate(' ', fullname)) ) numberpart table

oauth 2.0 - Google oAuth2 redirect_uri_mismatch in token access -

i trying access token one-time code using google oauth2. getting error message redirect_uri_mismatch in response. i've added redirect_uri in console. i have authorized redirect uri as: http://localhost:3020/api/users/google_oauth_store_token my request: request url = https://www.googleapis.com/oauth2/v3/token?code=xxxxxx&client_id=xxxxxx&client_secret=xxx&redirect_uri=http://localhost:3020/api/users/google_oauth_store_token&grant_type=authorization_code my response: response = { "error": "redirect_uri_mismatch", "error_description": "bad request" } that mistake. had use redirect_uri had used in one-time redirect uri. google uses 1 of redirect_uri rest client origin.

javascript - Identify OAuth for Multiple Google Accounts/Calendars -

we have chrome extension adds on information google calendar meetings (based on user action). accomplish this, perform oauth on user logged calendar, , use google api add our information. this works fine when 1 google account being used calendar/gmail. however, when there multiple accounts (such personal , google apps business account), have figure out account owns given calendar. handle looking @ dom elements , tying correct account have stored. however, proving fragile, , causes major pains when fails. we have evaluated chrome.identity, appears information account logged chrome browser itself, not account active in web session. is there programmatic way tell google user active under these circumstances can make appropriate api calls?

python - how to calculate the (pandas) timedeltas between TimesStamps in a column? -

so have pandas dataframe timestamp column. want add column timedeltas 1 cell next. easiest way this? use df['timestamp'].diff() answered @edchum

z3 - After changing from 4.3.2 to 4.4 I get often status UNKNOWN where I got SATISFIABLE or UNSATISFIABLE first -

my scenario follows: first follow optimistic assumptions well; check assertions without asking unsat core (just using assert). when status unsatisfiable during 1 of tests change strategy , use assertandtrack beginning full unsat core. with version 4.3.2 works perfectly, after switching 4.4 (stable , latest) z3 returns status unknown (even checks delivered satisfiable in 4.4 without assertandtrack). does can give me hint how solve problem or further analyze problem? thanks christian for second argument assert-and-track need pass propositional atom or negation of one. not checked in previous versions. may explanation of why seeing different behavior.

javascript - async.timesLimit() will not accept a valid callback function -

problem i working api using async library node. i've hit obstacle can't seem around. i modifying object in database through restful api. command i'm using called modifyobject , works. making function allows me edit multiple objects @ once asynchronously. but, don't want hit server 100 requests @ once, i'm using async.timeslimit() . can find the documentation function here . here shared.js utility function file: var async = require('async'); exports.modifyobject = function (objectid, data, callback) { setup.api() .json() .patch('/object(' + objectid + ')') .header("x-apikey", setup.apikey()) .send(data) .end(function (err, res, body) { if(err) throw err; callback(res); }); }; exports.modifymultipleobjects = function (arrayofobjectids, data, callback) { var failedarray = []; async.timeslimit(arrayofobjectids.length, 3, function (n, next) { ...

ruby on rails - Postgres server not starting after unexpected Yosemite shutdown -

i'm trying start rails server i'm getting error... /users/kweihe/.rvm/gems/ruby-2.1.6/gems/activerecord-3.2.22/lib/active_record/connection_adapters/postgresql_adapter.rb:1222:in `initialize': not connect server: connection refused (pg::connectionbad) server running on host "localhost" (::1) , accepting tcp/ip connections on port 5432? not connect server: connection refused server running on host "localhost" (127.0.0.1) , accepting tcp/ip connections on port 5432? if check postgres server processes ... kweihe-mac:pmpaware-webapp kweihe$ ps auxw | grep postgres kweihe 11687 0.0 0.0 2432772 636 s000 s+ 10:56am 0:00.00 grep postgres so i've tried following ... kweihe-mac:pmpaware-webapp kweihe$ rm -rf /usr/local/var/postgres kweihe-mac:pmpaware-webapp kweihe$ initdb /usr/local/var/postgres files belonging database system owned user "kweihe". user must own server process. database cluster in...

groovy - Builder pattern with reactive programming -

i'm attempting use reactive programming (rxgroovy) create objects using builder pattern, property values come database queries. i'm looking first of all, how it, , second of all, thoughts on whether or not idea. the objects i'm trying create of type: class foo { final string name; final long[] relatedids; foo(string name, long[] relatedids) { this.name = name; this.relatedids = relatedids; } } and builder: class foobuilder { string name; linkedlist<long> relatedids; { relatedids = new linkedlist<>(); } foobuilder name(string name) { this.name = name; return this; } foobuilder relatedid(long id) { this.relatedids.add(id); return this; } foo build() { return new foo(this.name, this.relatedids.toarray()); } } i have 2 queries, 1 returns names of foo objects, , separate query run once each foo object related ids. i have method...

VBScript - Create a dynamic variable name based on another variable's value -

i have stored 'servicename' values in excel file parametrization (code - line 4). format in excel: servicename (header) eisordamd entcanamd i want use dynamic variable names 3rd argument in 'fnexcquery' function based on parameters passed (line 5), i.e., 1st loop variable name should 'strquery_eisordamd' , 2nd loop should 'strquery_entcanamd' 1. ststrquery_eisordamd = "select * eisordamd" 2. strquery_entcanamd = "select * entcanamd" 3. while (not objrecordset_testdata.eof) 4. strservicename = trim(objrecordset_testdata.fields("servicename")) 5. blnresponse_request = fnexcquery(struser, strpwd, strquery_<strservicename>) '1st loop: strquery_eisordamd ; 2nd loop: strquery_entcanamd 6. objrecordset_testdata.movenext 7. loop how create dynamic variable name 3rd argument. couldn't able find solution using vbscript, please help. like eval(...

excel - Least number of whole tiles to use to fill a space -

per this thread , tim makes point trying again. writes, the problem of minimizing total number of smaller rectangles used fill total space real world problem. take @ floor of bathroom , you'll see why. mason needs know how can cover space destroying least number of tiles, , depending on algorithm used different results. so, if have space of w width , l length , constant rectangle of 48 width , 96 length, what's best way fill said space minimum waste? there's this gives combinations run through , pick best solution. don't understand answer/java though xd unless big surface multiple of tile dimensions, have cut some tiles , there some waste. have perfect saw can cut tile 0 waste. cut each 96 x 48 tile 4608 1 x 1 squares. determine number of tiles need, divide total area of big surface 4608 , round nearest integer tile!

sql - What is the optimal select according to you? -

Image
what optimal select according you? select @mailto=isnull((select data filedata descid=3104 , dataid=evt04) ,'') event_21 evtid=@nfileid or select @mailto=isnull(data ,'') event_21 innerjoin filedata on event_21.evt04=filedata.dataid descid=3104 , evtid=@nfileid obviously "join" faster "inline select query". have tested 1000 rows. can test. here sample test code. create table [dbo].[tablea]( [id] [int] identity(1,1) not null, [name] [nvarchar](100) not null, constraint [pk_tablea] primary key clustered ( [id] asc )with (pad_index = off, statistics_norecompute = off, ignore_dup_key = off, allow_row_locks = on, allow_page_locks = on) on [primary] ) on [primary] go create table [dbo].[tableb]( [rowid] [int] identity(1,1) not null, [id] [int] not null, [designation] [nvarchar](100) null, constraint [pk_tableb] primary key clustered ( [rowid] asc )with (pad_index = off, statistics_norecompute...

Solr spell check mutliwords -

could not figure out actual reason why configured solr spell checker not giving desire output. in indexed data query: symphony+mobile has around 3.5k+ docs , spell checker detect correctly spelled. when miss-spell "symphony" in query: symphony+mobile showing results "mobile" , spell checker detect query correctly spelled. have searched query in different combination. please find search result stat query : symphony **resultfound**: 1190 **spellchecker**: correctly spelled query : mobile **resultfound**: 2850 **spellchecker**: correctly spelled query : simphony **resultfound**: 0 **spellchecker**: symphony **collation hits**: 1190 query : symphony+mobile **resultfound**: 3585 **spellchecker**: correctly spelled query : simphony+mobile **resultfound**: 2850 **spellchecker**: correctly spelled query : symphony+mbile **resultfound**: 1190 **spellchecker**: correctly spelled in last 2 queries should suggest miss-spelled word "simphony...

intellij idea - Where are the "exclude folders/files from build" and "exclude files larger than X in search" settings in Intelllij 14 -

those settings used under combination of file|settings and intellij|preferences in earlier versions of ij. after having searched of menu items can locate either 1 in ij14. i have searched menu items , no longer able locate excludes options. build, execution, deployment | compiler | excludes to best of knowledge, option never in settings.

vba - How do I reference outlook custom form userdefined fields in vb code? -

i have custom form has userdefined fields unique projects. form works make more useful emailing or printing referencing userdefined field. example field "accountno". have tried oltsk.userdefined("accountno"): tsk.userdefined("accountno"); ("accountno") preceded dim userdefined fields strng; have seemed try every variation google find me. have outlook 2013 @ work. can work on older version @ home nothing seems work @ work. appreciated. if property added user properties, can use taslkitem.userpropertiers.find or using taskitem.propertyaccessor.getproperty. latter work both user properties , properties set using taskitem.propertyaccessor.setproperty. to figure out dasl names of custom properties, take @ item these properties set using outlookspy - click imessage button on outlookspy ribbon, select property, @ dasl edit box.

java - Customize Chrome webdriver using selenium to save files without prompting to save or discard files when downloading -

i trying automate downloading files using selenium chrome browser using chromedriver. when try downloading exe files prompting me "this type of file can harm computer, discard or save it". want download anyway without prompt. i have looked few solutions below: chromeoptions = webdriver.chromeoptions() prefs = {"browser.helperapps.alwaysask.force" :false,"browser.helperapps.neverask.savetodisk" : "application/octet-stream"} chromeoptions.add_experimental_option("prefs",prefs) browser = webdriver.chrome(executable_path=//path//to//chrome_driver, chrome_options=chromeoptions) but didn't still throws prompt. on appreciated. thanks, from understand, there no way tell chrome not warn on potentially dangerous binary file downloads, see: chromedriver has no way accept dangerous downloads (archived) add option automatically accept dangerous downloads (wontfix) as simplest workaround, might want approa...

postgresql - Get error code number from postgres in Go -

i'm unable retrieve error code number when error in postgres. in test of program know i'll following error " pq: duplicate key value violates unique constraint "associations_pkey"". looking in postgres docs pq error code of 23505. i need number in go program can check on different types of errors , respond end user in helpful way. however, can't seem hold of error code in go, error message. code follows: stmt, _ := db.prepare("insert table (column_1) values ($1)") _, err = stmt.exec("12324354") if err != nil { log.println("failed stmt .exec while trying insert new association") log.println(err.error()) fmt.println(err.code()) } else { render.json(w, 200, "new row created succesfully") } you need type assert error type *pq.error : pqerr := err.(*pq.error) log.println(pqerr.code)

javascript - Phantomjs : How to download and save a PDF file which is received as attachment in response header? Please give solution using Phantomjs only -

i trying download pdf file using phantomjs. there no direct url downloading pdf calls internal javascript function when click submit button. here code using download pdf file :- page.open(url, function(status){ page.evaluate(function(){ document.getelementbyid('id').click(); }); }); page.onresourcereceived = function(request){ console.log('received ' + json.stringify(request, undefined, 4)); }; the 'id' element id submit button. problem here though getting response (inside onresourcereceived callback) json format not able save attachment pdf file. when run above code, following output json string. output : received { "contenttype": "application/pdf", "headers": [ // other headers. { "name": "content-type", "value": "application/pdf" }, { "name": "content-disp...

javascript - How to process users in one specific order using map o each function? -

i create cloud function process items in specific order , make network request api each item , update them result of api. i tried this. order not respected , computation of "remainingcredits" wrong. note function "getuserpageview()" make api call , return promise result. query.descending("createdat"); return query.find().then(function(items) { var remainingcredits=0; var promises= _.map(items, function(item){ var credit=item.get("credit_buy"); return getuserpageview(123, new date()).then(function(pageviews){ var usedcredit=credit-pageviews; if(remainingcredits>0) return remainingcredits+credit; if(credit-usedcredit<=0){ console.log("usedcredit:"+usedcredit); item.set("used",true); return 0; }else{ remainingc...

xcode - Unable to simultaneously satisfy constraints in uitableviewcell with uiimageview -

first, system automatically removes proper constraint working expected understand how make code better. uitableview working in ios 8.0 automatic mode , not implement heightforindexpath method. the uitableview displays images in uitableviewcells , trying add ratio constraint uiimageview image displayed correctly. seems working expected there might don't understand (order of method called or constraint not given @ right moment not sure). below part of code can have at. image width , height stored in database , used set constraint before downloading image. - (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath { postimagetableviewcell *cell = [tableview dequeuereusablecellwithidentifier:cellidentifierpostimage]; if (cell == nil) { cell = [[postimagetableviewcell alloc] initwithstyle:uitableviewcellstyledefault reuseidentifier:cellidentifierpostimage]; } // adding image [cell.imagepost setimagewithurl:[nsurl urlwiths...

android - Google Cloud messaging with java EE -

is there tutorial documented code regarding google cloud messaging using java ee one.. http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/ using php. making chat application using websockets in android. have working code android websocket endpoint class interaction. problem how use gcm in current enviroment. please guide it's best gcm tutorial ever: http://javapapers.com/android/google-cloud-messaging-gcm-for-android-and-push-notifications/ php server code: <?php //generic php function send gcm push notification function sendpushnotificationtogcm($registatoin_ids, $message) { //google cloud messaging gcm-api url $url = 'https://android.googleapis.com/gcm/send'; $fields = array( 'registration_ids' => $registatoin_ids, 'data' => $message, ); // google cloud me...