Posts

Showing posts from August, 2012

Files not getting deleted in android -

in app, want delete 1 sqlite file , 1 txt file, doesn't work time. i have given read/writes permissions in android manifest file. is problem specific android version or there other way delete file in java.? i using below code. if(file.exists()){ file.delete() } any idea? maybe file still in use , cannot deleted. can use fileobserver check when file accessed. see http://developer.android.com/reference/android/os/fileobserver.html

vb.net - Windows 10 Universal App compiled Bindings / x:bind not working -

i've got following code test out new compiled bindings in universal windows 10 apps. xaml: <page x:class="xbindtest.mainpage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:xbindtest" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:ignorable="d" datacontext="{binding relativesource={relativesource self}}"> <grid background="{themeresource applicationpagebackgroundthemebrush}"> <stackpanel horizontalalignment="center" verticalalignment="center"> <textblock x:name="tester" text="{x:bind mybindclass.testtext, mode=oneway}" ></textblock> <textblock x:name="tester2" text="{binding mybindclass.testtext, mod

How to get the key of a CustomData in SAPUI5? -

i access key of customdata, inside list. xml view: <standardlistitem title="{name}" press="getselectedid" type="navigation"> <customdata> <core:customdata key="{id}"/> </customdata> </standardlistitem> i can't pass id of standardlistitem {id} because integer, , reason, not allow. i've created customdata it. so, whenever press list item key of item. here's exemple of i've tried it. getselectedid: function(oselected){ sap.m.messagetoast.show(oselected.getsource().getkey()); } the messagetoast see if got right value. unfortunately getkey() cannot used after getsource, or oselected how can key of selected item? calling oselected.getsource().data("key") should it. (for readibility better rename oselected oevent , give event handler name indicating handles event.)

node.js - Keep Mocha tests alongside source files -

i have nodejs source files in src , test suites in test , e.g.: /src/bar/baz/foo.js /test/bar/baz/foo.spec.js this leads awkward require statements var foo = require('../../../src/bar/baz/foo') . , it's hard see @ glance source files missing tests. instead keep test suites in same directory relevant source files: /src/bar/baz/foo.js /src/bar/baz/foo.spec.js but running mocha --recursive src causes errors mocha tries run source files tests. i've seen suggestions of using find or gulp filter file list find surprising can't done plain mocha. what's recommended way of organising files way? just pass pattern of test files mocha, like: mocha "src/**/*.spec.js" this going run .spec.js files in subdirectories of src .

jquery - One page scroll with subsections -

i have been looking jquery plugin handle one-page scrolling site apple-style scroll. there few options (such pagepiling , alton) near need. in addition, need subsections , dot menus represent them dots (in different style) appear , highlighted scroll, , hidden again once next main section comes view. does such solution exist? enquired pagepiling , author says plugin not support functionality. think jquery or javascripting build functionality may beyond expertise welcome links existing code or sites have this, or suggestions on how coded. does work? $(document).ready(function () { $(".page").css({ height: $(window).height(), lineheight: $(window).height() + "px" }); $("nav a").click(function () { thehref = $(this).attr("href"); $("html, body").animate({ scrolltop: $(thehref).offset().top }, 500); return false; }); }); * {font-family: 'segoe ui'; margin: 0;

c++ - Direct2D: Convert ID2D1Image to ID2D1Bitmap -

i'm working on programm needs modify on screen. have id2d1bitmap created using prendertarget->copyfromrendertarget . what i'm trying is, applying effects bitmap. effect returns id2d1image , need have id2d1bitmap . is there way this? edit1: id2d1bitmap* mybitmap //the bitmap want apply effect id2d1effect* effect = null; pdevicecontext->createeffect(clsid_d2d1saturation, &effect); effect->setvalue(d2d1_saturation_prop_saturation, 0.0f); effect->setinput(0, mybitmap); id2d1image* pimg = null; effect->getoutput(&pimg); if cast image, getpixelsize() raises access violation. i solved it. it's dirty, works. id2d1bitmap* convertimagetobitmap(id2d1image* pimg, d2d1_size_u size) { id2d1image* oldtarget = null; id2d1bitmap1* targetbitmap = null; //create bitmap "d2d1_bitmap_options_target" d2d1_bitmap_properties1 bitmapproperties = d2d1::bitmapproperties1( d2d1_bitmap_options_target, d

python - How to select nodes in html from lxml? -

i have html code http://chem.sis.nlm.nih.gov/chemidplus/rn/75-07-0 previous post how set xpath query html parsing? , want create logic process since many of other pages similar, not same. with, <div id="names"> <h2>names , synonyms</h2> <div class="ds"> <button class="toggle1col" title="toggle display between 1 column of wider results , multiple columns.">&#8596;</button> <h3>name of substance</h3> <ul> <li id="ds2"><div>acetaldehyde</div></li> </ul> <h3>mesh heading</h3> <ul> <li id="ds3"><div>acetaldehyde</div></li> </ul> </div> and in python script select nodes "name of substance" , "mesh heading" , check if exist , if select data in them otherwise return empty string. there way in python in javascript use node mynode = doc.documentnode.selectnode(/ [tex

copy - Ansible template - Destination directory does not exist error -

i new ansible , using template statement in playbook copy file local machine remote machine. error saying destination directory not exist, there much. i using centos 6.5 version (both local , remote). appreciated. create destination directory ansible - - name: create target directory file: path=/etc/some_directory state=directory mode=0755 ref: http://docs.ansible.com/file_module.html

django - Elasticsearch DSL queries not finding results -

i'm working on setting elasticsearch dsl django project. when use elasticsearch dsl set index , doc_type works. use sense(chrome plugin) , curl double-check if index , doc_type mapping added, , objects want store added, , is. the problem arises when use elasticsearch dsl api definitions submit queries - no results found. def experimental_test(): connections.create_connection(hosts=['localhost:9200']) tests_index = index('tests_index') tests_index.settings( number_of_shards=1, number_of_replicas=0 ) tests_index.doc_type(test) tests_index.delete(ignore=404) tests_index.create() test.init() test = test(title='foo') test.save() s = search() s = s.doc_type(test) s = s.query('match', title='foo') print s.to_dict() response = s.execute() here debug says sent elasticsearch (the actual query

Retrofit with simple json response containing only an integer or a string -

the rest api i'm calling returns integer: 12. as far know valid json although have been happier if change response on server side more canonical. unfortunately not option me. is there way use retrofit handle response too? edit see: this question , spec so seems new spec allows use simple string or integer json text i found way it: use integer template parameter restcallback : new restcallback<integer>() {...}

android - Enable and disable dialog depending on correct input? -

this popup button needs disabled if user clicks submit without entering input first: new alertdialog.builder(getactivity()) .setview(view) .setpositivebutton(android.r.string.ok, new dialoginterface.onclicklistener() { @override public void onclick(final dialoginterface dialog, final int which) { edittext nameedittext = (edittext) view .findviewbyid( r.id.save_search_dialog_name); posttobus(new savesearchevent( nameedittext.gettext().tostring(), search)); posttobus(new googleanalyticevent( ga.category_search_control, ga.event_search_save_search)); dialog.dismiss(); } //check see if dialog empty private boolean isempty(edittext ettext) { return ettext.gettext().tostring().trim().length() == 0; } } i trying c

smartface.io - How perform basic authentication with SMF.Net.WebClient? -

with smf.net.webclient how can perform basic authentication? webclient_validation.requestheaders = ['content-type : application/json','www-authenticate ' + credentialsencoded]; or webclient_validation.requestheaders('authenticate ' + credentialsencoded) there documents webclient object , it's properties. you can check links below : http://www.smartface.io/developer/guides/data-network/rest-services-2/ http://docs.smartface.io/html/p_smf_net_webclient_requestheader.htm also, can check smartface in action project, there webclient objects in it. open welcome page in smartface app studio.

php - Where's apachectl in Mac Yosimite -

since apache installed in mac yosimite in default. why can't find apachectl under /etc/apache2 ? can still use apachectl start start server , visit ' http://localhost ' successfully. anyone knows what's going on here? another question, followed tutorials here , after uncommented line says php, difference have loadmodule php4... . after did that, ' http://localhost ' doesn't work. it grateful if can this. because apachectl binary not stored there. can use which locate binary. $ apachectl /usr/sbin/apachectl php 4 obsolete. i'm not sure attempting do, recommend using php 5.4 or higher. older versions of php not receiving security patches.

Java connection failed with MySQL -

this question has answer here: connect java mysql database 12 answers i have created mysql database @ hostinger.co.uk , trying make connection between database , java application, , have written java code: import java.sql.connection; import java.sql.drivermanager; import java.sql.preparedstatement; import java.sql.resultset; public class db_connection { public static void main(string arg[]) throws exception { makeconnection("u335300563_myname", "pass12345"); } public static void makeconnection(string username, string password) throws exception { class.forname("com.mysql.jdbc.driver"); connection connection = drivermanager.getconnection("jdbc:mysql://u335300563_database",username,password); preparedstatement statement = connection.preparestatement("select * example");

ruby - Rails 4 - Invalid route name, already in use -

i have problem routing in rails 4 on production. my config/route.rb: rails.application.routes.draw root to: redirect("/#{i18n.default_locale}", status: 302), as: :redirected_root post '/rate' => 'rater#create', :as => 'rate' scope ':locale', defaults: {locale: i18n.locale} activeadmin.routes(self) end scope ':locale', locale: /#{i18n.available_locales.join("|")}/ devise_for :admin_users, activeadmin::devise.config devise_for :users # post '/rate' => 'rater#create', :as => 'rate' root :controller => 'static', :action => 'index' resources :categories resources :authors resources :messages resources :books resources :tags resource :static resource :users end # match '/:locale' => 'static#index' # priority based upon order of creation: first created -> highest prior

linux - BigQuery: Does bq load command support loading from named pipe as a source? -

i trying load data google bigquery using bq load named pipe. console window1: $ mkfifo /usr/pipe1 $ cat /dev1/item.dat > /usr/pipe1 console window2: $ bq load --source_format=csv projectid:dataset.itemtbl /usr/pipe1 field1:integer,field2:integer got following error: bigquery error in load operation: source path not file: /usr/pipe1 the bigquery client bq.py not support named pipes. explicitly requires files: https://code.google.com/p/google-bigquery-tools/source/browse/bq/bigquery_client.py?r=30df4638ff2ddb01d3f495af5c131ed3c2cfbd04#617 allowing named pipes feature suggestion. can request here: https://code.google.com/p/google-bigquery/issues/list it looks tweak copy of bigquery_client.py pretty make work well. luck!

google cloud messaging - Android Studio doesn't recognize InstanceID class -

i want implement gcm client on android. following guide here https://developers.google.com/cloud-messaging/android/client have downloaded configuration file , copied google-services.json file app/ directory of project. i have added dependencies in project's build.gradle classpath 'com.google.gms:google-services:1.3.0-beta1' and plugin in app level build.gradle apply plugin: 'com.google.gms.google-services' i have included google play services sdk compile 'com.google.android.gms:play-services:6.+' i have updated androidmanifest.xml file shown here https://developers.google.com/cloud-messaging/android/client to registration token, when use following code instanceid instanceid = instanceid.getinstance(this); android studio not recognize class. "cannot resolve symbol 'instaceid'". reason why happening? update play services sdk compile 'com.google.android.gms:play-services:7.5.0' then clean proje

Loading a html page with pure Javascript using AJAX -

there main page , there links on page. when individual links clicked, supposed load contents link loads inside div tag of main page. example: mainpage.htm <html> ... <body> ... <div id="maincontent"> </div> ... <a href='link1.htm'>link 1 </a> ... </html> link1.htm <script src="main.js">... <div> other contents here </div> when user clicks on link 1, browser doesn't go page, instead ajax used fetch linked document , load inside #maincontent . but, problem linked page has table , there table manipulation codes needed run when first loads. in fact linked document has link separate script , functions supposed run on window.onload . when load linked document using ajax using following approach: maincontent.innerhtml = xhr.responsetext; this not helping run window.onload codes on linked document. are there solutions or workaround type of problem?

database - Firebase for a Web Application -

i working on new web application. love idea behind firebase (augularfire) realtime data sync. can't figure out how organize data, make each customer (enterprise) have own data, , ensure no data shared between each enterprise. in regular mysql server, can create database per enterprise (best implementation speed , security) or add table enterprise , table customer enterprise_id. best approach in firebase db?

c# - How to fix borderless form resize with controls on borders of the form? -

Image
i have borderless winform needed resize, , managed way: protected override void wndproc(ref message m) { const int wmnchittest = 0x84; const int htleft = 10; const int htright = 11; const int httop = 12; const int httopleft = 13; const int httopright = 14; const int htbottom = 15; const int htbottomleft = 16; const int htbottomright = 17; if (m.msg == wmnchittest) { console.write(true + "\n"); int x = (int)(m.lparam.toint64() & 0xffff); int y = (int)((m.lparam.toint64() & 0xffff0000) >> 16); point pt = pointtoclient(new point(x, y)); size clientsize = clientsize; ///allow resize on lower right corner if (pt.x >= clientsize.width - 16 && pt.y >= clientsize.height - 16 && clientsize.height >= 16) { m.result = (intptr)(ismirrored ? h

javascript - CORS header not set - can I request an image url and then serve it back to myself? -

i attempting populate webgl earth meshes compiled images. these images cross-domain, , hosted on server setting appropriate headers isn't option. can xmlhttprequest image urls, , serve them myself via php bypass cors errors? or, more specifically, can use own webserver proxy serve img urls myself (to around cors) in webgl context? edit : real question here if can use own webserver proxy pass urls, or if i'll have download each image server use it. i had similar issue once using api. first tried in js getting same error message do. my solution switch php , server side since modern browsers block want do. so yes, possible. get pictures on backend , provide them frontend. simply retrieve pictures first , send them output browser. can synchronously doing like: $ch = curl_init ... ... $pic = curl_exec ... // picture // , echo this have done once don't remember correctly. or can async, done when using img-tags. i'm not sure how works webgl s

javascript - Working with JS objects and functions -

Image
i'm newbie in javascript , i'm wondering why bob.age still 30 while age 50 when called it. set age 50 in setage assigned 50 this.age , know reference bob.age , age , bob.age should have same value. // here define our method using "this", before introduce bob var setage = function (newage) { this.age = newage; }; // make bob var bob = new object(); bob.age = 30; // , down here use method made // change bob's age 50 here bob.setage = setage(50); bob.setage = setage(50); all doing setting setage property of bob result of calling setage(50) - setage retunrs undefined, you've set bob.setage = undefined. perhaps intended bob.setage = setage; bob.setage(50); untested, think it's right

urllib2 - Writing a script to sign in web automatically using Python -

i want sign www.renrendai.com using python. script works other websites cannot sign website. i don't know why? can me? import requests import sys bs4 import beautifulsoup url = 'https://www.renrendai.com/loginpage.action' sess = requests.session() html1 = sess.get(url).text soup1 = beautifulsoup(html1) p1 = soup1.select("[name=targeturl]")[0]["value"] p2 = soup1.select("[name=returnurl]")[0]["value"] print p1 print p2 data = { "targeturl": p1, "returnurl": p2, "j_username": "15101030402", "j_password": "qwerty123456" } r = sess.post(url, data) msg = beautifulsoup(sess.get('http://www.renrendai.com/lend/detailpage.action? loanid=643702').text) type = sys.getfilesystemencoding() print msg.decode("utf-8").encode(type)

css - align text center with icon next to it -

i have following code: <div class="icon-search small-collapse large-2 medium-12 small-12 hide-for-medium-down js-hide-for-small columns"> <input type="submit" value="{{ 'search'|trans }}" class="button"> </div> and css icon is: .icon-search:before{ top: 15px; left: 18px; position: absolute; z-index: 9999; color: white; font-size: 2.2rem; } however value "value='{{ 'search'|trans }}'" dynamic because of language selection. how can make sure "icon-search" 5px away value return "{{ 'search'|trans }}" , both aligned centered?

mockito - Java unit test mock a method with predicate as an argument -

i have 2 classes: classa { public string methoda(string accountid, predicate<user> predicate) { // more code }; } classb { methodb(){ classa objecta = new classa(); objecta.methoda("some id", predicatesprovider.isuservalid()); // more code ... } } class predicatesprovider { static predicate<user> isuservalid(){ return (user) -> { return user.isvalid(); } } in unit test, need mock classa, use mockito's mock method following: classa mockobjecta = mockito.mock(classa.class); mockito.when(mockobjecta).methoda("some id", predicatesprovider.isuservalid()).thenreturn("something"); mockito couldn't find signature match. the java.lang.assertionerror: expected:<predicatesprovider$$lambda$5/18242360@815b41f> was:<predicatesprovider$$lambda$5/18242360@5542c4ed> this kind of simplified version of trying achieve. guess problem equals() function of predicate. idea how mock m

python - Count occurrences of digit 'x' in range (0,n] -

so i'm trying write python function takes in 2 arguments, n , num, , counts occurrences of 'n' between 0 , num. example, countoccurrences(15,5) should 2 . countoccurrences(100,5) should 20 . i made simple iterative solution problem: def countoccurrences(num,n): count=0 x in range(0,num+1): count += counthelper(str(x),n) return count def counthelper(number,n): count=0 digit in number: if digit==n: count += 1 return count this ran obvious problems if tried call countoccurrences(100000000000,5) . question is how can make more efficient? want able handle problem "fairly" fast, , avoid out of memory errors. here first pass @ recursive solution trying this: def countoccurence(num, n): if num[0]==n: return 1 else: if len(num) > 1: return countoccurence(num[1:],n) + countoccurence(str((int(num)-1)),n) else: return 0 this won't hit memory problems, until max_num small enough fit in c

material design - Toolbar is not shown in android application -

i have started migrate old app material design , decided use toolbar instead of actionbar more customization.i tried add toolbar 1 activity following code : layout.xml <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <android.support.v7.widget.toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?attr/colorprimary" android:minheight="?attr/actionbarsize" > </android.support.v7.widget.toolbar> <android.support.design.widget.tablayout android:id="@+id/tabs" android:layout_width="match_parent&q

Add Efficient searching feature in Android App from Sqlite Database -

i have 1 problem table problemtable id problemtitle problemdescription 1 machine got hand water motor got jammed 2 motor not working induction motor not working 3 water connection not proper water connectivity problem in city 4 electric power machine problem electric power generator not working 5 power down in city power down in city i need add searching feature, may keyword searching or full text search,both description , title. if search "motor" reasults 1 machine got hand water motor got jammed 2 motor not working induction motor not working if search " power down in city " search result 4 electric power machine problem electric power generator not working 5 power down in city power down in city 3 water connection not proper water connectivity problem i

AngularJS & UI-Router - How do i prevent a full page reload on URL bar change? -

setup: i'm using angularjs v1.4 ui-router v0.2.15 i have 2 sibling routes, lets call them /apple & /orange if load app , go 'apple' - apple's view loads correctly i can use $state.go('orange') goto orange - view reloads correctly. 'use strict'; angular.module('loadzapp', [ 'ngcookies', 'ngresource', 'ngsanitize', 'ui.router', 'ui.bootstrap' ]) .config(function ($stateprovider, $urlrouterprovider, $locationprovider) { $urlrouterprovider .otherwise('/'); $stateprovider .state('main', { url: '/', templateurl: 'app/main/main.html', controller: 'mainctrl' }) .state('apple', { url: '/apple', templateurl: 'apple.html', controller: function ($scope) { $scope.feedback = {} } }) .state('orange', { url: '/orang

swift - Best way to build a proximity app within 200 meter range of the user? -

i using swift develop personal app family , have been researching methods of toolset use build app allows user see other people using same app in vicinity of around 0 - 200meters. i looking @ bluetooth , trying work out how tinder finds other users. use gps? if how 1 best implement that. what effective way determine users location within 200 meters? note: 1 user search surrounding area devices on app - tell user location. doing both, finding distance between 2 locations , how should location. personal use, security issues arent of concern. as may have expected, have many options of different approaches accomplish goal. suggest start taking @ couple open-source projects: peerkit locationchat both of these libraries demonstrate way transfer payload of data between devices. in addition, both projects provide helpful example apps. assuming choose use peerkit, each device responsible obtaining own location (via corelocation) , broadcasting other devices (via peer

css - How can i set different hover properties from different elememtns in an HTML page? -

i have created 2 divs (topnavlinks & bottomnavlinks) , both divs contain links. hover property every link on page set black. want know how can set different hover colors 2 divs? <!doctype html> <html> <head> <title>home</title> <style> body { font-family:"myriad pro"; } #topnavlinks { background-color:#d5d5d5; color:#1f8f3c; font-size:20px; padding:20px; margin-bottom:20px; } #bottomnavlinks { background-color:#2b88b5; color:#ffffff; padding:20px; } a:link, a:visited { color:inherit; padding:inherit; text-decoration:none; } a:hover, a:active { color:#0e0e0e; } </style> </head> <body> <div id="topnavlinks"> <a href="#">link1</a> <a href="#">link2</a> <a href="#">link3</a> </div> <div id="bottomnavlinks"> <a href="#">link1</a> <a href="#">link2<

oracle - update/insert PL/SQL -

let's customer 4 wishes increase order 23 100. enable user type in: the number 4 customer_id 100 updated quantity. i want write pl/sql function receive these 2 values , update sales table reflect change. print out on screen main section of code total quantity customer 4 before , after update. please have tried following code not sure structure create or replace trigger orders_before_insert before insert on ord each row declare v_price number; new number; begin select pr v_price product product_id =:new.product_id ; -- update create_date field current system date :new.total_cost := :new.quantity * v_price; end; here proof of concept procedure. doesn't have validation or error handling expect in proper procedure. create or replace procedure update_order (p_order_id in orders.id%type , p_additional_qty in orders.qty%type , p_orig_total out number , p_new_total out number ) l_total number; l_orig number; begin

pipe - Redirect last action's stdout using >>= in haskell -

how can output previous action , print using >>= in haskell? in shell, like, echo "hello world" | { read test; echo test=$test; } in haskell, looking like, putstrln "hello world" >>= {x <- getargs; print x} getargs stdin must take input putstrln's stdout. edit#1, alexey & aochagavia, inputs. works. x :: io string x = return "hello world" main = x >>= print no, >>= doesn't have stdout. can use capture_ function silently package: x <- capture_ (putstrln "hello world") print x or capture_ (putstrln "hello world") >>= print .

c# - Can't update a foreign key on an attached graph -

i have attached graph object , can't figure out how change foreign key on record. have load record saved in db. retrieve said record id tracking on. public partial class load { [key] public virtual int id {get;set;} [required] public virtual int accountid { get; set; } public virtual account account { get; set; } [required] public virtual int customerid { get; set; } [foreignkey("customerid")] public virtual customer customer { get; set; } } i retrieve customer record want associate load record public partial class customer { [key] public virtual int id {get;set;} [required] [maxlength(100)] public virtual string name { get; set; } } no matter do, sort of exception thrown. var customer = context.customers.where(x => x.id == customerid).singleordefault(); load.customer = customer; load.customerid = customer.id; load.modifiedbyapplicationuserid = userid; l

javascript - HTML / jQuery: How to properly include external jQuery file -

i new js , programming in general , hope can me this. i working on building website every page has separate html / php file. jquery , global / general js functions included in footer of these pages through separate includes file " footer.php ". so far works intended. now have pages use specific jquery functions want load corresponding js if such page loaded. to saved corresponding codes in separate js files (e.g. nameofexternaljsfile.js ) , wrapped in there in following: $(document).ready(function(){ // ... }); i made following updates corresponding php pages (example): <head> <?php require_once("includes/header.php"); ?> <!-- here want include specific jquery functions --> <script src="includes/js/nameofexternaljsfile.js"></script> </head> <!-- ... --> <!-- here include main js functions --> <?php require_once("includes/footer.php"); ?> i ha

php - Advanced Custom Fields - Adding Linkedin -

Image
i having trouble creating clickable linkedin link in wordpress via advanced custom fields plugin. simple when wanted add phone number , email. can not figure out how make linkedin icon appear each user clickable link. code: function member_contact() { $vcard = get_field('vcard'); $bio = get_field('bio_pdf'); $linkedin = get_field('linkedin'); $phone = get_field('phone'); $fax = get_field('fax'); $email = get_field('email'); $post_info = ''; if (isset($vcard['url'])) { $img = get_stylesheet_directory_uri() . "/images/mail-icon.png"; $post_info .= '<a class="vcard" href="'.$vcard['url'].'"><img src="'.$img.'" /> download contact</a>'; } if (isset($bio['url']) && isset($vcard['url'])) { $post_info .= ' | '; } if (isset($bio['url'])) { $post_info .= '<a class

c++ - Adding all values of map using std::accumulate -

i trying add values of map defined in program below: std::map<int, int> floor_plan; const size_t distance = std::accumulate(std::begin(floor_plan), std::end(floor_plan), 0); std::cout << "total: " << distance; i following error: error c2893: failed specialize function template 'unknown-type std::plus::operator ()(_ty1 &&,_ty2 &&) const' std::begin(floor_plan) gives iterator pointing @ std::map<int, int>::value_type std::pair<const int, int> . since there no operator+ defined pair type , integer, code fails compile. option #1 if want sum mapped values floor_plan , you'd need provide own binary operator able extract second element of dereferenced iterator passed in: std::accumulate(std::begin(floor_plan) , std::end(floor_plan) , 0 , [] (int value, const std::map<int, int>::value_type& p) { return value + p.second; }

javascript - How do I pull values from a radio button with a label? -

in regards question getting text of radio button instead of values , how pull values radio button label? i did not post question there, fealt did not go original question. how value of selected radio? have tried both $("input[type='radio'][id='rblunitofmeasuretype']:checked").val() , $("input[type='radio'][id='rblunitofmeasuretype']:checked + label").val() , both return undefined. i using form, form there tag, rest of html formless form (if makes sense). function listunitofmeasureset_change() { if (listunitofmeasureset.value.tostring().tolowercase() === "new") { $("#divnewtypeunitcontentholder").html(""); callservice("get", g_webserviceunitsofmeasuretypeunitsurl, null, function(jsonresult) { if (jsonresult.success) { (i = 0; < jsonresult.unitofmeasuretypelist.length; i++) { $("#divnewtypeunitcontentholder").html($(&qu

rails combining two models in form form without association -

i have 2 models primeaccount , ticket. want create ticket in primeaccount new form. trying in primeaccount controller def create ticket = ticket.new(ticket_params) # ticket.event_id = params[:event_id] ticket.save! ............. end def ticket_params params.permit(:price, :quantity, :event_id) end def prime_account_params params.permit(:country) end i confused how write new form accept both ticket , prime account fields. also in url sending event params like http://localhost:3000/prime_accounts/new?event_id=11 i want pass event_id ticket_params . please tell me how create new form.

java - how to implement a variable whose value is not lost after every run? -

i wish implement variable (in java) value either stored somewhere or not reset every time run program. it's related "booking reference number" flight program. know database connectivity make new data base 1 variable pretty pointless. ideas should/can do? don't want numbers random want them in order if first booking id 100 next 1 should 101 , on. organize data in structure , serialize it.when re-run program, serialized version in file system, if there any, read it. viola.!

python - Relabel levels in pandas -

in pandas dataframe i'm trying relabel 2 levels of variable 1 single name leave 'nan' values in variable untouched. below reproducible example using modified version of 'mtcars' dataset. here want relabel 'yes' , 'no' levels of 'am' variable 'new' example. mpg cyl disp hp drat wt qsec vs mazda rx4 21.0 6 160.0 110 3.90 2.620 16.46 0 yes mazda rx4 wag 21.0 2 160.0 110 3.90 2.875 17.02 0 nan datsun 710 22.8 6 108.0 93 3.85 2.320 18.61 1 no hornet 4 drive 21.4 2 258.0 110 3.08 3.215 19.44 1 nan hornet sportabout 18.7 6 360.0 175 3.15 3.440 17.02 0 yes valiant 18.1 2 225.0 105 2.76 3.460 20.22 1 nan duster 360 14.3 2 360.0 245 3.21 3.570 15.84 0 no result this: mpg cyl disp hp drat wt qsec vs mazda rx4 21.0 6 160.0 110 3.90 2.620 16.46 0 new mazda rx4

tkinter - Python - AttributeError: 'str' object has no attribute 'items' -

i'm beginner in tkinter . i'm trying make phone book gui application. so, i'm in beginning step, here source code: #this python 'source.py' learning purpose tkinter import tk tkinter import button tkinter import left tkinter import label tkinter import frame tkinter import pack wn = tk() f = frame(wn) b1 = button(f, "one") b2 = button(f, "two") b3 = button(f, "three") b1.pack(side=left) b2.pack(side=left) b3.pack(side=left) l = label(wn, "this label!") l.pack() l.pack() wn.mainloop() as run, program gives following error: /usr/bin/python3.4 /home/rajendra/pycharmprojects/pythonproject01/mypackage/source.py traceback (most recent call last): file "/home/rajendra/pycharmprojects/pythonproject01/mypackage/source.py", line 13, in <module> b1 = button(f, "one") file "/usr/lib/python3.4/tkinter/__init__.py", line 2164, in __init__ widget.__init__(self, master, 'b

c++ - How to compare (the order) of two bidirectional iterators? -

i wondering if there build-in way in c++ compare order of 2 bidirectional iterators. example, have sum function calculate sum between 2 iterators in same list: double sum(std::list::const_iterator start, std::list::const_iterator end){ double sum=0; (start;start!=end;start++) sum+=*start; return sum; } then: sum(my_list.begin(),my_list.end()); fine, sum(my_list.end(),my_list.begin()); cause runtime error. i thinking putting if (start>end) return 0; prevent error. seems cannot compare iterators this. you should read introduction stl explains various refinements of iterator concept. only randomaccessiterators support comparison < because not efficient operation non-randomaccessiterators. the way tell if bidirectionaliterator i less-than another, j , incrementing i 1 step @ time , seeing if ever reach j , never happen if j not reachable i , , error if i not incrementable, e.g. because past-the-end iterator range. alter

UITextView link not clickable iOS 8 -

i followed : uilabel , nslinkattributename: link not clickable , uitextview link clickable, when click it, safari doesn't open no avail. i have : uitextview.attributedtext = ... attributed string "http://google.com" ... "links detection", "selectable" , "user interaction enabled" enabled. "editable" disabled. i implemented uitextviewdelegate - (bool)textview:(uitextview *)textview shouldinteractwithurl:(nsurl *)url inrange:(nsrange)characterrange { return yes; } however, link appears blue when click, nothing happens. i had same issue. nothing did help. the problem was, added uitextview scrollview , used sizetofit . for example: had view.frame (0,0,320,440). , scrollview contentsize (0,0,320,1000) , links in view.frame works when scroll down - not. than tried check view selecting when scroll down , tap on uitextview. added uitapgesturerecognizers , find out when tap in bounds of self.view fra

java - How to get request parameter from actionB on execution of actionA -

i have requirement need request parameter actionb on execution of actiona . can see below there complex logic behind working out strb in actionb . want value of strb in actionb without having repeat complex logic. what's best way that? <action name="actiona" class="com.mycompany.action.actiona" method="input"> <result name="input" type="tiles">page.actiona</result> </action> <action name="actionb" class="com.mycompany.action.actionb" method="readfromcache"> <result name="input" type="tiles">page.actionb</result> </action> public class actiona extends actionsupport private string stra = new string(); private string strb = new string(); public string input() throws exception { stra = "hello"; // here strb actionb strb = ...need here...

Cloned SharePoint Environment on Test Server - Pages Appear in Document Libraries but SharePoint Says They are Deleted -

i have created test sharepoint server close our production server possible. production sharepoint databases backed , restored our test server. 3 main web.configs (central admin, main site, security token service application) modified include our custom app settings. the site comes fine, logging in using both ad , our custom fba membership provider works well. certain pages visible in site libraries through view site content , using sharepoint designer sharepoint says page(s) not found if try view them or check them in. not pages not available. if delete bad page , replace copy our production application, displays fine. i've found , tried possible solutions such restarting search query , site settings service , checking alternate access mapping. found possible solution has go component services , modify security relative osearch14 property. not able modify since right clicking on property did not pop menu options. continue this. any ideas? appreciate help. thanks.

c++ - Significance of Equal To in Binary Search -

i implementing binary search in c++. here code: #include <iostream> #include <vector> #include <algorithm> using namespace std; int bs(vector<int> a, int val) { int l =0, r = a.size()-1; while(l<=r) // significance of == { int mid = l + (r-l)/2; if(a[mid]==val) return mid; if(a[mid]>val) { r = mid-1; continue; } else { l = mid + 1 ; } } return l; // deliberately returning } int main() { vector<int> = {1,3}; cout << bs(a,1) <<endl; return 0; } question 1 in implementations, see people use while(l<r) while in use while(l<=r) is there conceptual difference between preferring 1 way ? possible sources of error if don't use == ? question 2 in case element not found, l guaranteed position in element inserted list still remains sorted ? valid while using equal or not using equal ? it depend

ios - Facebook and keyboard animation management -

Image
does know how implement composerbar , keyboard appearing in facebook messenger? after scrolling tableview up, keyboard appears bottom smoothly , without jumps . in similar implementation works this: after scrolling up, when tableview bottom offset < 0, composerbar's input text field become first responder , keyboard jumps finger. yes, use uiscrollviewkeyboarddismissmodeinteractive . how facebook implement smooth animation? edit: try explain how works in facebook messenger, step step. i have inputaccessoryview on viewcontroller (tableviewcontroller). start scroll tv (pic 1) then, if bottom inset become more value (for example 10) (pic 2), set firstresponder inputtextfield (pic 3) so, in common case, 'uiscrollviewkeyboarddismissmodeinteractive', keyboard jumps finger position (pic 4) but! in facebook messenger keyboard drags bottom distance equal distance traveled finger. (pic 5) so, facebook messenger somehow control keyboard moving. question

swift - Thread 1: EXC_BAD_ACCESS (code=1, address = 0x38) -

in view controller have action method button. in body of method says if audioplayer.playing { audioplayer.stop } when audio player playing, works. when audio player not playing crash error. i'm literally losing sanity me please love of god. try stop player: @ibaction func stoptapped(sender: anyobject) { if let player = audioplayer{ player.stop() } } for more info check this sample project.