Posts

Showing posts from June, 2014

go - Golang close net listener -

i having trouble closing listener can reopen on same port. writing proxy server hot-configurable - i.e (redirects/blocks etc) can adjusted on fly. proxy runs in go routine. problem having when reconfigure listener , proxy listener still using port previous configuration. (fyi listener global pointer) i'm trying like: to kill listener: func killproxy() { if listener != nil { log.println(" *** trying stop proxy server") (*listener).close() listener = nil } } before reconfiguring like: log.println("listener (s1): ", listener) if listener == nil { // start listener listen on connection. l, err := net.listen(conn_type, conn_host + ":" + conn_port) if err != nil { log.println("error here: ", err) } listener = &l //set pointer newly created listener } log.println("listener (s2): ", listener) however doesnt seem work - error: listener (s1): err

ios - CloudKit compound query (query with OR) -

i query cloudkit using or 2 fields. can't find way how this. did is: nspredicate *predicate1 = [nspredicate predicatewithformat:@"(creatoruserrecordid == %@)", userid]; nspredicate *predicate2 = [nspredicate predicatewithformat:@"(touser == %@)", userid]; nscompoundpredicate *comppredicate = [nscompoundpredicate orpredicatewithsubpredicates:@[predicate1, predicate2]]; ckquery *query = [[ckquery alloc] initwithrecordtype:@"message" predicate:comppredicate]; but unfortunately ckquery not support or query (as written in documentation) can achieve effect other way? ckquery supports , and not, imagine use simple boolean algebra create query based on fact not(not , not b) == or b. however, documentation says: "the not compound operator not supported in following cases: you cannot use negate , compound predicate." so must query each of ored predicates separately save them each set , take intersection of 2 sets final result

c++ - Implicit this parameter in GDB -

i'm using clion. how see value of this parameter in gdb? isn't in "variables" section now. i've tried print using "evaluate expression", didn't me, printed {void (my_class * const)} 0x7fff5fbff298 . also, can explain why happening? well, technically, this pointer object owns it, should regular pointer address points class. it's nothing special. now, once dereference pointer, referring actual object. should try referencing *this when want print out actual object.

Ruby on rails find an associated objects which has another association too -

i have 3 models, organized way: class task < ar::base has_one :taskable class taskable belongs_to :task has_many :supplies class supply < ar::base belongs_to :taskable how can fetch tasks, taskable has @ least 1 supply? you need join query . # fetch tasks, taskable has @ least 1 supply task.joins(taskable: :supplies)

Use data-* attribute in grails g.link generated in tagLib -

is there way use data- attributes in g.link generated taglib? want store dom info instead of using params in g.link results in query parameters. example: out << g.link(controller: "calendar", action: "info", params: [id: cal_id], data-info: "abc") { "click me " } unfortunately works when using normal g.link syntax view: <g:link controller="calendar" action="info" id="${cal_id}" data-info="abc">click me</g:link> just put quotes around data attributes : out << g.link(controller: "calendar", action: "info", params: [id: cal_id], "data-info": "abc") { "click me " }

php - Custom wordpress function not showing the right number of posts -

i have custom wordpress function shows number of featured recipes. function works fine when showposts=-1 in query. when put 'showposts=5' 2 of posts shown. below function function pika_featured_recipes_shortcode() { ob_start(); echo '<div class="featured-box-heading"> featured recipes </div>'; echo '<div class="featured-box">'; $temp = $wp_query; $wp_query = null; $wp_query = new wp_query(); $wp_query->query('showposts=5&post_type=cp_recipe&order=desc&orderby=date' . '&paged=' . $paged); while ($wp_query->have_posts()): $wp_query->the_post(); $entry_id = get_the_id(); $entry_link = get_permalink($entry_id); $entry_image = get_post_thumbnail_id($entry_id); $entry_title = get_the_title($entry_id); $entry_description = get_post_meta($entry_id, '_cp_recipe_short_description', true); $entry_excerpt = get_post

php - display validation error message next to the textbox in codeigniter -

Image
i'm newbie codeigniter.i want display error message next text box.my view file create.php contains following code. <?php echo validation_errors(); //validation echo form_open('news/create'); //create form ?> <div class="boxes"> <div class="common"> <div class="lables"> <label for="name">name</label> </div> <div class="text_boxes"> <input type="text" name="uname" /><div id="infomessage"><?php echo $message;?></br> </div> </div>` and below controller model: public function create() { $this->load->helper('form'); $this->load->library('form_validation'); $data['title'] = 'insert items'; $this->form_validation->set_rules('uname','required|min_length[6]|m

cordova - Javascript app with local communication -

i reading around see if can find answer problem no luck far, hope can me. what i'm trying mobile app (ios, android, windows phone) can communicate on lan wifi without need of internet share info. example variable or plain text, or example use phone local server share pdf file. way i'm going use phonegap answer must in plain javascript/html/css please.

mysql - Count and group by in same query -

bid_count returning 1 ... how return correct bid count? know it's not returning right count because i'm grouping user_id . can alter query counts also. "select id, bid, item_id, user_id, max(bid) max_bid, count(bid) bid_count, bid_date bids item_id = ? group user_id order id desc" you shouldn't use unaggregated expressions in group unless same within group. if want return record holding counts user_id, should use subquery counts join them result: select id, bid, item_id, user_id, bid_date, max_bid, bid_count bids left join (select user_id,max(bid) max_bid, count(bid) bid_count bids item_id = ? group user_id ) group_table on bids.user_id = group_table.user_id bids.item_id = ?

Digit Sum in Python with user input -

i have code: def digit_sum(n): total = 0 while true: = n % 10 n = n // 10 total = total + if n < 1 : break return total print digit_sum(12584521) in code above want allow user input number. example, user inputs 12584521, hits enter , result appears (in example result 28). how modify code above that? thanks try this print digit_sum(input("enter num: ")) for python2.x , 3.x print(digit_sum(int(input("enter num: "))))

javascript - Using Multiple Functions in AngularJs -

i'm new angular , using function load data using $http, worked me. after decided form validation see it's behaviour. can individually bit confused on how can merge code above both of functions work well. code as: var app = angular.module('app', []); app.controller('datactrl', function($scope, $http) { $http.get('any url or file') .then(function(result) { $scope.data = result.data; }); }); the controller defined in body attribute this: <body ng-controller="datactrl"> now when put other function in same app.js file, doesn't work, can me out on this, validation code this: app.controller('datactrl', function($scope) { $scope.submitform = function(isvalid) { if (isvalid) { alert('submitting data'); } }; }); the thing need make them work this: 1. load data (working) 2. implement validation of second code block. just try explain how thing working :)

javascript - Meteor function executes before publish and subscribe finishes loading collection -

i have meteor template helper function searches document of scores. if can't find matching document, creates new 1 user. unfortunately, meteor function executes var score = userscores.findone(); before publish , subscribe functions finish. every time, new userscore document created. if turn on autopublish problem goes away , doesn't create duplicate record. how can ensure publish , subscribe functions execute first, before template helper executes? do need place meteor method in /lib folder execute or there way client-side? var score = userscores.findone(); if(!score) { score = { userid: meteor.userid(), total: 0, goal: 200 }; userscores.insert(score); } the easiest way template-level subscriptions. template.mytemplate.oncreated(function() { var subscription = this.subscribe('publicationname', publicationarguments); } that simplified way of doing it, should have no problems helper running first. edit: discover meteor blog has gre

console - Different output showing on Xcode's Playground -

Image
i can console output if "show assistant editor", don't want there whole time, want when i'm checking values. i've seen in videos people can click little (+) circle see results , when click appears wondering how i'd able looks when press (+) ? using: xcode 6.4 i see since xcode 6.4, think need println :( ui use xcpshowview function xcplayground library. first need import xcplayground, then: xcpshowview("your title", youruiviewobject)

javascript - Non responsive Bootstrap via lie @media queries -

i have develop complex responsive webpage layout using bootstrap 3. layout nicely shows arrangement & display expected on different screen size. however, possible can disable responsive case use set specific layout display such xs , shows xs layout no matter screen is? i thinking done using javascript lying @media queries? or, easier done using other method? in way interesting question. have @ fiddle , resize window can see happening bootstrap col-xx-xx @ same time. i have set groups of cols show happen if used xs class... want do. when resizing window watch how other classes vary compared violet ones xs cols. you can if needed roll own here , set own breakpoints. full size fiddle here.

How to filter results based on frequency of repeating terms in an array in elasticsearch -

i have array field lot of keywords , need sort documents on basis on how many times particular keyword repetation in arrays. eg,if field name "nationality" , document 1, consists of following doc1 nationality : ["us","uk","australia","india","us","us"] and doc2 nationality: ["us","uk","us","us","us","china"] i want documents shown term "us" occurs more 3 times. make doc2 shown. how this? you can use scripting implemented. { "query": { "filtered": { "filter": { "script": { "script": "_index['nationality']['us'].tf() > 3" } } } } } here in scripy array "nationality" checked term "us" , count taken tf (term frequency). documents term frequ

swift - Alamofire: Cannot invoke 'URLRequest' with an argument list of type '(Method, NSURL)' -

i playing request router pattern, looks this: enum router: urlrequestconvertible { static let baseurlstring = "https://somewhere" case dosomething var urlrequest: nsurlrequest { let (method: method, path: string, parameters: [string: anyobject]) = { switch self { case .dosomething: var params = [string: anyobject]() return (.get, "/dosomething", params) } }() let url = nsurl(string: router.baseurlstring)!.urlbyappendingpathcomponent(path) let request = urlrequest(method, url) // <- error here let encoding = parameterencoding.url return encoding.encode(request, parameters: parameters).0 } } and i'm getting aforementioned "cannot invoke 'urlrequest' argument list of type '(method, nsurl)'" looking @ method signature of urlrequest see: func urlrequest(method: method, url: urlstringconvertible) -> nsurlrequest nsurl conforms urlstringconvert

javascript - How do I use setInterval with my form to create an alarm clock? -

i'm trying learn javascript , i've decided make things more interesting creating instead of endless reading & no practice. i'm trying build alarm clock. here's code: http://codepen.io/anon/pen/dcsax function wakeup() { window.location = "https://www.youtube.com/watch?v=dqw4w9wgxcq" } i need create function uses setinterval check every few seconds if time set in form equal current time, , if is, execute wakeup function plays rick astley - never gonna give up. i don't know how write piece of code. please me out can see how it's done? thanks in advance. i added id button, , on click set timer function below: <input id="scheduletimer" type="button" value="schedule alarm"></input> function gettimeoutsec() { var dt = new date(); var currsecs = dt.getseconds() + (60 * dt.getminutes()) + (60 * 60 * dt.gethours()); var am_pm = document.getelementbyid('t').value; var

javascript - Cannot read InputStream from HttpListenerRequest -

i've been creating download manager receive file name , download link chrome extension. in case decided use javascript background page send xmlhttprequest loopback , create simple server receive message background page this. background.js function showmessagebox(info, tab) { var link = decodeuricomponent(info.linkurl); var index = link.search(/[^/\\\?]+\.\w{3,4}(?=([\?&].*$|$))/); var filename = link.substring(index); alert("will download " + link + " soon\n file name : " + filename); sendmessage(filename,link); } function sendmessage(filename, link) { var xhr = new xmlhttprequest(); xhr.open("post","http://localhost:6230", false); xhr.setrequestheader("content-type", "application/json; charset=utf-8"); var jsonstring = json.stringify({ filename: filename, downloadlink: link }); xhr.send(jsonstring); } and part of server. private void startreciever() {

python - Evaluate slope and error for specific category for statsmodels ols fit -

i have dataframe df following fields: weight , length , , animal . first 2 continuous variables, while animal categorical variable values cat , dog , , snake . i'd estimate relationship between weight , length, needs conditioned on type of animal, interact length variable animal categorical variable. model = ols(formula='weight ~ length * animal', data=df) results = model.fit() how can programmatically extract slope of relationship between weight , length e.g. snakes? understand how manually: add coefficient length coefficient animal[t.snake]:length . cumbersome , manual, , requires me handle base case specially, i'd extract information automatically. furthermore, i'd estimate error on slope. believe understand how calculate combining standard errors , covariances (more precisely, performing calculation here ). more cumbersome above, , i'm wondering if there's shortcut extract information. my manual method calculate these follows. edit (0

node.js - node-inspector get nothing in browser -

i trying debug node-inspector on newly installed iojs 2.3. i npm install -g inspector v0.10.2, , type server:~ vince-fan$ node-inspector node inspector v0.10.2 cannot start server @ 0.0.0.0:8080. error: listen eaddrinuse 0.0.0.0:8080. there process listening @ address. run `node-inspector --web-port={port}` use different port. my app running on port 8080, should change web port of inspector? tried: server:~ vince-fan$ node-inspector --web-port=3000 node inspector v0.10.2 visit http://127.0.0.1:3000/?ws=127.0.0.1:3000&port=5858 start debugging. when open address show above, browser give me big blank page, nothing, nothing showing there. i tried chrome, safari, nothing works. anyone has idea, what's going on? node inspector not until there's process inspect. try running node program option --debug or --debug-brk after launching node-inspector .

CodeIgniter date - wrong time -

i'm using: date("d-m-y h:i:s") in controller, time later actual time. example, in country it's 01:02, date return 20-06-2015 01:06:38. how fix it? 1st step : go config/config.php , write //specify region date_default_timezone_set('europe/warsaw'); 2nd step: can use time date("d-m-y h:i:s") //for 21/12/2010 20:12:00 date("h:i:s") //for 12:12:11 time

How integrate Paypal Payment with Ruby on Rails -

i use gem integrate paypal ruby paypal ruby sdk goes perfect, can redirect users paypal sandbox account , user can confirm payment. once user confirm payment redirect site paymentid, token , payerid in url. the problem when want execute payment code payment = payment.find(@payment.id) if payment.execute( :payer_id => params[:payerid] ) # success message # note you'll need `payment.find` payment again access user info shipping address else payment.error # error hash end nothing happens. standard paypal integration rails app active merchant gem : step 1: -> add 'gem activemerchant' in  gem file -> bundle install step 2: -> go "www.developer.paypal.com" , create account(also known merchant account) address details. -> create 2 dummy test account buyer , seller(alias facilitator) in "sandbox.paypal.com".   ex:       seller account  --->  naveengoud-facilitator@gmail.com      buyer account  ---

c# - Move a file from a SharePoint library to a UNC path -

i have number of files in document library in sharepoint , url paths files. want able move files sharepoint unc path location file.exists() , file.move() doesn't work url's. answering own question because wasn't able find specific answer this. found called davwwwroot allows access files through windows explorer. i created method converts url's form allows me use file.move() on files in sharepoint library. private string convertsharepointurltouncpath(string sharepointfileurl) { return sharepointfileurl.replace(@"http://mysharepointsite/", @"\\mysharepointsite\davwwwroot\").replace('/', '\\'); }

php - Incremental MySQL Timestamp conversion for highstock -

i'm using highstock library show output data magnetometer, have little problem. store data in 2 fields in bd. first value datetime data saved, , second sensor value: 2015-06-10 01:29:43 | 15 but because sensor send more 1 value in 1 second, need convert time, unix in incremental way let's suppose it's raw data: 2015-06-10 01:29:43 | 15 2015-06-10 01:29:43 | 16 2015-06-10 01:29:43 | 40 2015-06-10 01:29:43 | 50 2015-06-10 01:29:43 | 15 2015-06-10 01:29:43 | 11 i convert timestamp: 1444094983 | 15 1444094983 | 16 1444094983 | 40 1444094983 | 50 1444094983 | 15 1444094983 | 11 the last step convert time milliseconds. it's not problem. thing is, need every second repeated, have incremental millisecond this 1444094983001 | 15 1444094983002 | 16 1444094983003 | 40 1444094983004 | 50 1444094983005 | 15 1444094983006 | 11 but when new second begins, incremental number must restarted , start 0 again. i'm working php , way solve it $i =

visual c++ - Converting a String^ to a const void* in C++ -

i using c++/cli create gui controls external gpib device. gui has textbox user can enter voltage. able read voltage textbox this... string^ v1 = textbox1->text; assuming user enters decimal number textbox, need concatenate value other text , produce const void* pass gpib library command. so question how can convert string^ const void* ? able convert string^ double this... double volt1 = double::parse(textbox1->text); so solution how convert double const void* work well. it's odd external library wants const void* , not character pointer, assuming wants ansi string, can use marshal_context class convert string^ const char* pointer: // marshal_context_test.cpp // compile with: /clr #include <stdlib.h> #include <string.h> #include <msclr\marshal.h> using namespace system; using namespace msclr::interop; int main() { marshal_context^ context = gcnew marshal_context(); string^ message = gcnew string("test string mar

Bootstrap Image Gallery using Blueimp is not working -

i trying add image gallery feature on bootstrap framework website. i using blueimp gallery. problem doesn't show images shows next , previous buttons. please me. here html code: <div id="blueimp-gallery" class="blueimp-gallery"> <!-- container modal slides --> <div class="slides"></div> <!-- controls borderless lightbox --> <h3 class="title"></h3> <a class="prev">‹</a> <a class="next">›</a> <a class="close">×</a> <a class="play-pause"></a> <ol class="indicator"></ol> <!-- modal dialog, used wrap lightbox content --> <div class="modal fade"> <div class="modal-dialog"> <div class="modal-content"&

javascript - How to compare grouped data between two dates using the mongodb aggregate framework -

consider data set follows sector value date 2 1/1/2015 b 5 1/1/2015 c 8 1/1/2015 3 1/1/2015 6 1/1/2015 1 1/1/2015 c 1 1/1/2015 sector value date 2 2/1/2015 b 10 2/1/2015 b 5 2/1/2015 c 8 2/1/2015 is there way use mongodb aggregate framework find difference between each grouped sector 2 dates in question? in other words possible output this: a -> (2+3+6) - 2 = 10 b -> 5 - (10+5) = -10 c -> (8+1) - 8 = 1 using aggregation framework , $cond operator change sign of value on 2/1/2015, simple sum. given test collection: { name: 'a', value: 2, date: isodate('2015-01-01') }, { name: 'b', value: 5, date: isodate('2015-01-01') }, { name: 'c', value: 8, date: isodate('2015-01-01') }, { name: 'a', value: 3, date: isodate('2015-01-01') }, { name: 'a'

java - Validation in JSF -

i'm trying implement validation of form don't accept when fill in numbers or characters. this login.xhtml <?xml version='1.0' encoding='utf-8' ?> <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://xmlns.jcp.org/jsf/facelets" xmlns:c="http://xmlns.jcp.org/jsp/jstl/core" xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:f="http://xmlns.jcp.org/jsf/core"> <h:body> <ui:composition template="./templates/template.xhtml"> <ui:define name="content"> <p><h:link outcome="/index" value="to home page" /></p> <h:form> username: <h:inputtext id="username" value=&qu

c++ - recursive permutations using vector -

i have function suppose return possible permutation of integers inside vector. code based existing code permutation of strings, tried remodeled work on vectors apparently, dont work thought.. i'll appreciate offer thanks; vector<vector<int>> permute(vector<int> &v1, vector<int> &v2){ vector<vector<int>> v; if( v1.empty() ) { v.push_back(v2); return v; } for(auto = v1.begin(); != v1.end(); it++){ vector<int> temp1 = v1; temp1.erase(it); //there's runtime error on line vector<int> temp2 = v2; temp2.push_back(*it); permute(temp1, temp2); } return v; } this original code permutes string. void string_permutation( std::string& orig, std::string& perm ) { if( orig.empty() ) { std::cout<<perm<<std::endl; return; } for(int i=0;i<orig.size();++i

c# - OData no http resource was found that matches the request uri -

i'm having trouble getting odata service working mvc 4 site. can me figure out i'm doing wrong? here webapiconfig: public static class webapiconfig { /// <summary> /// register method /// </summary> /// <param name="config">the config.</param> public static void register(httpconfiguration config) { config.mapodataserviceroute("odata", "odata", getedmmodel(), new defaultodatabatchhandler(globalconfiguration.defaultserver)); config.ensureinitialized(); } private static iedmmodel getedmmodel() { odataconventionmodelbuilder builder = new odataconventionmodelbuilder(); builder.namespace = "thisclassesnamespace"; builder.containername = "defaultcontainer"; builder.entityset<queryrequest>("queryrequests"); var edmmodel = builder.getedmmodel(); return edmmodel; } } here global.asax

vsts - Deploy to Remote Server using Visual Studio Online -

how 1 deploy code remote server using visual studio online after build completes? my google skills apparently lacking today not finding information on anywhere. i use release management vso. if download release manager client visual studio can create release pipeline tge vnext template lets deploy , number of environments remotely. called agent-less deployment , have migration path new release capability in tfs 2015 (and vso when hits)

python - wxPython - implementing wx.EVT_TEXT_PASTE -

i'm creating wx.pyvalidator textboxes: class ipvalidator(wx.pyvalidator): "validator validating ip addresses" def __init__(self): super(ipvalidator, self).__init__() self.bind(wx.evt_text_paste, self.onpaste) def clone(self): """cloning validator""" return self.__class__() def validate(self, win): """the validate function""" return self.onvalidate(self.getwindow().getvalue()) def onvalidate(self, text): """returns true or false given text""" return re.match(text, ip_pattern) def onpaste(self, event): ####### text = event.getstring() if self.onvalidate(text): event.skip() def transfertowindow(self): return true def transferfromwindow(self): return true i have problem in onpaste method. how can string pasted before being pasted , ma

python - Added items to the list is not in expected ordered -

contacts added list in 1,2,3 order, query return shows list strange order 2,1,3. follow test gives pass, pay attention last 3 lines before , after commit. class staff(mydb.model): __tablename__ = 'staff' staff_id = mydb.column(mydb.string(20), primary_key = true) first_name = mydb.column(mydb.string(64)) last_name = mydb.column(mydb.string(64)) email = mydb.column(mydb.string(62), unique=true, nullable = false) password = mydb.column(mydb.string(), nullable = false) class staffcontact(mydb.model): __tablename__ = 'staff_contact' staff_id = mydb.column(mydb.string(20), mydb.foreignkey('staff.staff_id'), primary_key = true) department = mydb.column(mydb.string(50), primary_key = true) office = mydb.column(mydb.string(50)) phone = mydb.column(mydb.string(15)) staff_obj = mydb.relationship('staff', backref='contact_list') def test_add_contact_to_new_staff(self): staff = staff( staff_

php - Apache + mod_php how to manually log error? -

i have apache 2.4 , php 5.6 module. there way send custom error current 'errorlog' file? 'errorlog' directive depends on time (daily logs). , have specific requirements: i cant call trigger_error function (error message should not displayed, logged); i cant use display_errors none value i cant use @ operator any variants? any language let write stderr. stderr redirected base servers errorlog. try fprintf.

ios - Will push token change when app is rebuilt? -

i'm planing rebuild 1 of applications(new xcode project), heavily relay on push notifications. will push token change after update installed? i need notifications work if user doesn't open new app after update. what mean rebuild? tokens don't change every time app rebuilt. the tokens can change unfrequent when do, when not documented apple, have noticed occur if backup restore app itunes 1 example. however system should designed cope them changing - client code should token each time launches , compare cached version, , if differ must send new 1 server. if app doesn't have cached 1 send retrieved 1 server.

java - Is it possible to use Mockito to completely stop a method from running? -

i'm unit testing method has lot of logic in it. goes this: public void dosomething(int number){ //... complex logic if (number % 2 == 0) someinstanceobject.setodd(false); else someinstanceobject.setodd(true); //... more complex logic , database connections } is possible mockito end method execution after if-else statement? reason why want because want test both conditions using mockito.verify() . want stop right away because after if-else blocks, there lot of stuff needs mocking database connections. believe me, if can refactor this, put if-else statement in other utility class , expose public, would. turns out can't refactor code anymore. i don't think possible stop after if using mockito. how mockito @ point want stop? but can try dirty solution - mock method call succeedes if throw exception , in test method catch it. stop method execution , don't have mock db stuff.

sql server - Computing minimum path lengths in an SQL table -

i'm having problem exercise: table friend : friend1 friend2 table relationship : friend1 friend2 gradeoffriendship i need create trigger in must obtain symmetric tuple, example: luc mark mark luc in both tables. if there direct contact between 2 people gradeoffriendship = 1 if there no contact between pair of people gradeoffriendship = 0 . in other cases gradeoffriendship must calculated minimum distance on possible paths connecting these 2 people (we must consider table directed graph) my problem not obtain symmetric tuple, how calculate possible paths between 2 people. example: luc marc 1 marc john 1 luc john 2 i using sql server. @ moment don't have idea how solve problem - think must use recursive function don't know how.... this 1 way create recursive fried network: ;with data ( select person1, person2, 1 grade friends union select person2, person1, 1 grade friends ), cte ( selec

ajax - Correct method to submit complex data from EditorTemplates in MVC5 -

i'm working on userprofile editor , i'm using editortemplates this, can't figure out right way submit data complex objects using method. don't know if have right views or not, , how roll complex object partial views. simplify, pare down bit, userprofile has many sub-objects representing user preferences. create table [dbo].[userprofile] ( [userprofileid] int identity (1, 1) not null, [nickname] varchar (max) not null, [thumbnailimageid] int null, ); in entities, have navigation objects point thumbnailimage object, in editortemplate (for userprofile) can this: <div class="form-group"> @html.labelfor(model => model.nickname, htmlattributes: new { @class = "control-label col-md-2" }) @html.editorfor(model => model.nickname, new { htmlattributes = new { @class = "form-control" } }) </div> <div class="form-group"> @html.labelfor(model => mod

python - Merging dataframes in pandas - Keep getting key error? -

i'm trying merge 2 data frames, testr , testc, keep getting key error on "channel id" , not sure problem is. dataframes have same size or have same datatype pd.merge work? here code merge .info() on each dataframe: def matchid_rc(rev,cost): rc = pd.merge(rev, cost, on='channel id', how = 'outer') return rc testr.info() <class 'pandas.core.frame.dataframe'> int64index: 169 entries, 0 168 data columns (total 7 columns): channel id 169 non-null int64 channel name 169 non-null object impressions 169 non-null object fill rate 169 non-null object gross rev 169 non-null object impression fees 169 non-null object exchange fees 169 non-null object dtypes: int64(1), object(6) memory usage: 10.6+ kb testc.info() <class 'pandas.core.frame.dataframe'> int64index: 63 entries, 0 62 data columns (total 3 columns): channel id 62 non-null object campaign 63 non-null object ad

mysql - mysql_connect(): Access denied for user -

i getting weird error message mysql_connect(): access denied user 'spaceagent_dk@10'@'10.246.64.59' don't have clue of how fix , don't understand why "breaks" in middle. and on top last part 10.246.64.59 not server , in code. can me? lot. have tried find answers over. guess not experienced yet... best, louise

javascript - Pass Buffer to ChildProcess Node.js -

here have on node.js want image processing in sub process. as see take file image.jpg , want write hello.jpg in subprocess: var node = require('child_process').spawn('node',['-i']); var fs = require('fs'); node.stdout.on('data',function(data) { var fs = require('fs'); var gm = require('gm').subclass({ imagemagick: true }); gm(data) .resize(500, 500) .tobuffer("jpg", function(err, buffer) { if (err) { console.log(err); }else{ fs.writefile("hello.jpg", buffer); } }); }); var buffer = fs.readfilesync(__dirname + "/image.jpg"); node.stdin.write(buffer); however when run file error: [error: stream yields empty buffer] for me seems buffer not passed correctly subprocess? wrong? what can run image processing in subtask. me important not read file in subprocess. because want read 1 file again , send buffer several subprocesses im

bash - Check whether a Kafka topic exists in Python -

i want create kafka topic if not exist. know how create topic via bash, don't know how check whether exists. topic_exists = ?????? if not topic_exists: subprocess.call([os.path.join(kafkabin, 'kafka-topics.sh'), '--create', '--zookeeper', '{}:2181'.format(kafkahost), '--topic', str(self.topic), '--partitions', str(self.partitions), '--replication-factor', str(self.replication_factor)]) you can use --list (list available topics) option kafka-topics.sh , see if self.topic exists in topics array, shown below. depending on number of topics have approach might bit heavy. if case, might able away using --describe (list details given topics) likely return empty if topic doesn't exist. haven't thoroughly tested this, can't sure how solid solution ( --describe ) is, might worth investigate bit further. wanted_topics = ['host_updates_queue', 

ArcGIS / Esri Custom Theme not showing in appbuilder -

i've followed instructions here: https://developers.arcgis.com/web-appbuilder/guide/create-a-theme.htm created correct scaffold, placed in stemapp/themes can't show up. also, when edit demotheme, changes aren't displaying. i've cleared cache, using incognito it's not working. i've used yo generator scaffold theme, no dice. https://github.com/esri/generator-esri-appbuilder-js what doing wrong? two possibilities: if using demo theme, default, disabled. enable it, open .repoignore file in client\stemapp\themes, remove demotheme file, , restart node server. during development, use " http://your host/webappbuilder/?id=stemapp" access theme directly. if doesn't appear here, not following instructions correctly. make sure theme names placed. there must instances still have names copied theme(e.g demotheme), replace of them theme's name. should appear.

osx - Homebrew Python Fab can't see yaml -

i've installed several different versions of pyyaml @ point , in no instance fab see yaml. i've done brew install libyaml , pip install pyyaml , in neither instance fabric see yaml module. when import yaml in python, works right. result import yaml , print(yaml) is: <module 'yaml' '/usr/local/lib/python2.7/sitepackages/yaml/__init__.pyc'

c# - How to flatten nested dictionaries within Class using LINQ -

the closest solution looking thread how flatten nested objects linq expression but error trying approach the type arguments method 'system.linq.enumerable.selectmany(system.collections.generic.ienumerable, system.func>)' cannot inferred usage. try specifying type arguments explicitly. my code: var aa = t.data.selectmany(x => x.value.innerdata.selectmany(y => new { /*error @ selectmany*/ url = x.key, disp = x.value.disp, date = y.key, count = y.value.count, rank = y.value.rank, })); my classes: public class tdata { public dictionary<string, tdetail> data { get; set; } } public class tdetail { public string disp { get; set; } [newtonsoft.json.jsonproperty("data")] public dictionary<string, metrics> innerdata { get; set; } } public class metrics { public string count { get; set; }

swift - Local AngularJS application hosted in WKWebView -

i have hybrid application built using wkwebview. have gotten around loading local files issue, having trouble loading angularjs application local files. getting following error: cross origin requests supported fro http. with android able update setting on webview control allow file:// schemes. there similar missing in ios? or solution? i using xcode 6.3 (6d570) this known issue wkwebview in ios 8, , suspect that's why uiwebview remains undeprecated. i haven't had time use betas yet, suggestion give latest xcode 7/ios 9 shot, , use new wkwebview api - (wknavigation * _nullable)loadfileurl:(nsurl * _nonnull)url allowingreadaccesstourl:(nsurl * _nonnull)readaccessurl which ideally let pull in other html files templates in readaccessurl provide. please file bugs see in latest beta. apple way slow move on issues in wkwebview . if need angular app work now , you'll need switch uiwebview , confirmed work angular-based webapps stored on dev

node.js - Best practice to store secret for generating JWTs in a NodeJS app -

i using jwts authenticating users on spa (nodejs backend, angular frontend). have function in user model generate jwt when user signs in: // ./models/user.js - waterline orm var waterline = require('waterline'); var bcrypt = require('bcrypt'); var jwt = require('jsonwebtoken'); // [...] generatejwt: function() { // set expiration 60 days var today = new date(); var exp = new date(today); exp.setdate(today.getdate() + 60); return jwt.sign({ _id: this.id, username: this.username, exp: parseint(exp.gettime() / 1000), }, 'secret'); // todo: real secret } // [...] this 'secret' shouldn't hardcoded. , should not in codebase or in repo. best / secure way handle this? config file in shared folder symlinked when deploying? database?

plugins - Graph representation - display individuals by data property and group by type -

i use ontograf 1.0.3 (via "class views"/"ontograf") display small ontology created in protege 5 beta-17 graph; not out of choice because first tool found. my chosen display mode "horizontal directed". unfortunately, within layer order of items appears random; clarity if grouped type. is possible , how? furthermore, nodes in graph displayed uri. individuals have data property "name" however, , labelled property instead of uri. is possible , how? bonus question: when displaying whole ontology, layers of tree strictly arranged based on relation jumps; push individuals below deepest class layer. to elaborate, how looks like: c |\ c <- same layer, no correlation /| | c <- same layer, no correlation this how it: c |\ c \ /| | | c | <- same layer, same level of abstraction | if there better solution produce graphical tree such characteristics, gladly accept instead.

Updating a Rails 3.2 app to Rails 4 or wait for Rails 5 -

i update rails 3.2 app rails 5 app when 5 released. will possible or need go 3.2 -> 4.x -> 5 personally, have had more issues making larger jumps on rails projects smaller, more "incremental" ones. 2.x 4.x jump in one, well, sucked :). however, found rails 3.2 -> 4.2 not bad jump app @ work. in fact, protected_attributes gem added 4.2 version of our app, did not need worry strong params change in rails 4.2 (this gem lets continue use attr_accessible in models). over time, changing our many models/controllers utilize newer strong params approach, nice other benefits of 4.x branch (enums in particular have been helpful in our particular app) without having refactor dozens upon dozens of controllers/models strong params. with said, think ideal approach on features of 4.x (and/or 5.x) , ask whether or not features improve app, code, development experience, etc. if yes, i'd update sooner rather later. if no, i'd wait , upgrade when have app

excel - VBA - Outlook Task Creation - Recipient based on Dynamic Range -

as of right now, below function works, need change recipient.add field corresponding email address, each change. of email address listed in column on worksheet, , ideally function automatically add correct email based on row. i calling function using =addtotasks(a1,c1,d1) a1 date, c1, , text, , d1, amount of days prior a1, need reminder pop up. of outlook references correctly added, need figuring out email address. excel , outlook 2010 option explicit dim bwestartedoutlook boolean function addtotasks(strdate string, strtext string, daysout integer) boolean dim intdaysback integer dim dtedate date dim olapp object ' outlook.application dim objtask object ' outlook.taskitem if (not isdate(strdate)) or (strtext = "") or (daysout <= 0) addtotasks = false goto exitproc end if intdaysback = daysout - (daysout * 2) dtedate = cdate(strdate) + intdaysback on error resume next set olapp = getoutlookapp on error goto 0 if not olapp nothing set objt

php - Is there anyway to add rel="next"/rel="prev" into "Page Template" with WordPress SEO by Yoast? -

our site using "wordpress seo yoast" rel="next" , rel="prev" working fine on category , archive page, in page template created, rel="next" , rel="prev" not showing. (this page template has pagination) our website structure => have " article " post type in article have category credit card cash card loan etc. as want url www.sitename.com/loan without having ../category/loan i created 'page' called 'loan' , using page-loan.php page template query post type 'article' category 'loan' i want have rel="next" , rel="prev" appear in page template wonder there anyway use wordpress seo yoast it? or there anyway modify below script in plugin make rel="next" , rel="prev" appear in page template well? the script found in plugin public function adjacent_rel_links() { // don't genesis, way genesis handles homepag

How do I can display a string value without using the standard libraries in C language? -

how can display string value without using standard libraries in c language? please see following code: //without using standard libraries other created int main() { string str = "hello"; //how can display str value without using standard libraries other created it? } here's how can : // declare prototype write() function, // unspecified parameters because why not. extern long write(); int main(void) { char const *str = "hello"; // retrieve length unsigned long size = 0; while(str[size]) ++size; // write stdout (fd 1) write(1, str, size); return 0; } live on coliru . of course, it's non-portable gets, , fail link or trigger ub on majority of systems other 1 pulled declaration (it's linux system call, declared in unistd.h retrieved coliru). then, that's why have standard library in first place.

Jenkins slave not working on mesos -

i'm using jenkins mesos plugin ci. initially, followed following tutorial: http://www.ebaytechblog.com/2014/05/12/delivering-ebays-ci-solution-with-apache-mesos-part-ii/ but jenkins not being setup via this. (i got error not load config.xml file, there one) then followed https://rogerignazio.com/blog/scaling-jenkins-mesos-marathon/ , , able run jenkins master (jenkin framework/scheduler), when define scripts run, jenkins-slaves not being created. think i'm missing configuration regarding slaves. can tell me, what's reason slaves not being created run jobs. on jenkins build page, i'm getting : (pending—waiting next available executor) and in jenkins-logs, i'm getting following error: info: provisioning jenkins slave on mesos 1 executors. remaining excess workload: 0 executors) jun 19, 2015 4:02:55 pm hudson.slaves.nodeprovisioner$standardstrategyimpl apply info: started provisioning mesoscloud mesoscloud 1 executors. remaining excess workload: 0 jun