Posts

Showing posts from May, 2010

Remove input R object in C++ function environment -

i have rcpp function inside r function. r function produces object (say large list) , feeds rcpp function. inside rcpp function, copy r object's data number of c++ classes, , on r object practically useless. want release memory r object (or maybe mark garbage if deleting hard?). the idea is: // [[rcpp::export]] void cppfun(list structureddata) { // copy structureddata c++ classes // want structureddata gone save memory // main algorithms ... } /***r rfun(input) { # r creates structureddata input cppfun(structureddata) } */ i tried calling r's "rm()" in c++ can identify object names in r's global environment. example: // [[rcpp::export]] void cppfun() { language("rm", "globaldat").eval(); language("gc").eval(); } /***r globaldat = 1:10 ls() # shows "globaldat" created. cppfun() # shows "globaldat" no longer in environment. ls() */ however, following not work: // [[rcpp::export]] void

ruby on rails - How to access xml in Feedjira parser classes -

say have following feedjira nested parser subclasses. how can access xml trunk, branch, , leaf classes can log/save in case of error? preferably xml parsed element, i'd take xml whole trunk in case of branch or leaf. thanks! module feedjira module parser class trunk include saxmachine include feedentryutilities element :trunkname elements :branch, as: :branches, class: branch def createmodel begin trunk = activerecordtrunk.create( name: trunkname ) branches.each_index |n| branch = branches[ n ].createmodel branch.trunk_id = trunk.id branch.save! end rescue standarderror => e # log error , xml trunk element. how?? ::rails.logger.error "parse error, xml = #{ xml }" end end end class branch include saxmachine include feedentryutilities element :branchname elements :leaf, as: :l

How to extract PHP array values and remove data -

i have seen bunch of ways, none seem work. array data coming this. array ( [0] => result=0 [1] => respmsg=approved [2] => securetoken=8cpcwfzhah02qnliofegz1wo4 [3] => securetokenid=253cad735251571cebcea28e877f4fd7 i use this: <?php echo $response[2];?> too each out, works. need remove “securetoken=” im left number strings. have been trying out success. function test($response){ $secure_token = $response[1]; $secure_token = substr($secure_token, -25); return $secure_token; } also im putting end number form input “value” field. not that matters, unless does? thanks this do: $keyresponse = []; foreach ($response $item) { list($k, $v) = explode('=', $item, 2); $keyresponse[$k] = $v; } now can access value part of each item based on name: echo $keyresponse['securetoken']; // output: 8cpcwfzhah02qnliofegz1wo4 the advantage method code still works if order of items in $response c

environment variables - How to update .env file and share among teammates? -

i created .env file params, pushed github, teammates downloaded repo. in next push added .env file .gitignore . need make changes .env file, how if .env ignored. right way of doing such of manipulation? you not store .env in repo create .env.dist (or named that) , put in project repository instead. such file template or example of how production .env should , such stores keys, but no values , i.e.: db_host= db_user= the main benefit not have .env in repo, each developer can setup own system likes/needs (i.e. local db, etc) , there's no risk of having such file accidentally overwritten on next pull, @ least frustrating. also, not store sensitive data in repository, noone can i.e. run code agains production machine. depending on development environment use, can automate creation of .env file, using provided .env.dist template (whcih useful i.e. ci/cd servers). dotenv file pretty simple, processing easy. wrote such helper tool php myself, pretty simple co

go - Form Always Empty -

i've been building go todo list , i'm trying add ability add new items, every time access form value, comes out empty. here's handler built: func addhandler(w http.responsewriter, r *http.request) { err := r.parseform() if err != nil { fmt.print(err) } cook, _ := r.cookie("userid") id := cook.value r.parseform() text := r.formvalue("todo") addtodo(text,id) //inserts database http.redirect(w,r,"/todo",http.statusfound) } and here's html <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>title</title> </head> <body> <table> {{range .}} <tr><td>{{printf "%s" .text}}</td><td><a href="/delete/{{.id}}">delete</a></td></tr> {{end}} </table> <form action="/add" method="post"><input t

reactjs - Sending event handlers as props into a React component using TypeScript -

i have following code react component. what's right way declare 2 onclick handlers passed component? interface loginformprops { loginclicked: ???? <--- onclick handler signature cancelclicked: ???? <--- onclick handler signature } class loginform extends react.component<loginformprops, {}> { render() { <form> <button onclick={loginclicked}> login </button> <button onclick={cancelclicked}> cancel </button> </form> } } i typically use: interface iloginformprops { loginclicked: (ev) => void; // } but if want strict typing: interface iloginformprops { loginclicked: (ev: react.mouseevent<htmlbuttonelement>) => void; // }

javascript - Change ad cookies -

i want able add cookies "smart ads" or ads track search history read off of cookies, if makes sense. i.e, put apple-related cookies in, , start seeing apple ads. have no clue how approach this. can explain how tracker ads work , how feed them data with code ? let me know if needs clarification. john you won't able create cookies affect ads other servers. searches on other servers saved on servers.

php - Fatal error - Cannot use object of type stdClass as array (Eloquent) -

error trying row database using eloquent: fatal error: cannot use object of type stdclass array in... i'm using wamp. make observation because i've implemented similar codes in remote servers , got no problems. $row = $database::table('users')->where('email', $email)->first(); the issue when i'm trying take $row content: if($row['first_name']) { // causes fatal error } why? next, database configuration file: use illuminate\database\capsule\manager capsule; $database = new capsule(); $database->addconnection([ 'driver' => 'mysql', 'host' => 'localhost', 'database' => 'animalfm', 'username' => 'root', 'password' => '' ]); $database->setasglobal(); $database->booteloquent();

reactjs - React / Redux App Issue Fetching Data from MongoDB via API -

i new redux , setting app campaign / products / users along posts mern v2.0 boilerplate. i have setup app have fetchposts action. page has following (code bottom half) // actions required provide data component render in sever side. postlistpage.need = [() => { return fetchposts(); }]; // retrieve data store props function mapstatetoprops(state) { return { posts: getposts(state) }; } postlistpage.contexttypes = { router: react.proptypes.object, }; export default connect(mapstatetoprops)(postlistpage); get posts passes state , should add posts object store. can hit api route , see back-end working , loading json object expected. however, app giving me error within postreducer -- // posts export const getposts = state => state.posts.data; the error when go route -- typeerror: cannot read property 'data' of undefined @ getposts (/users/yasirhossain/projects/showintel/client/modules/post/postreducer.js:31:34) @ mapstatetoprops (/users/yasirh

python 3.x - tensorflow hidden state doesn't seem to change -

i'm trying follow along rnn tutorial on medium , refactoring go along. when run code, appears work, when tried print out current state variable see what's happening inside neural network, got 1 s. expected behavior? state not being updated reason? understand, current state should contain latest values in hidden layer batches, shouldn't 1 s. highly appreciated. def __train_minibatch__(self, batch_num, sess, current_state): """ trains 1 minibatch. :type batch_num: int :param batch_num: current batch number. :type sess: tensorflow session :param sess: session during training occurs. :type current_state: numpy matrix (array of arrays) :param current_state: current hidden state :type return: (float, numpy matrix) :param return: (the calculated loss minibatch, updated hidden state) """ start_index = batch_num * self.settings.truncate end_index = start_index + self.settings.truncate

php - Avoid requests that take much time Apache -

i programm class validates data browsers , 1 of methods validates length of strings, came mind: if sends big string 2 millions of characters or more (or whatever) ? if use strlen() count bytes, count last bytes. waste count bytes. after thinking while, made this: class validator { static public function verify_str_length($str, $min, $max) { $i; $counter = $min; $msg = ""; // looling until null char found // for($i=$min-1;$i<$max;$i++) { if(!isset($str[$i])) { if($i == ($min -1)) { // if first iteration // find null char early. // $i starts minimum length allowed, string // length lower short $msg = 'too short string'; return -1; } return 0; } } if(isset($str[$i])) { // if reach max , keep without finding null char /

Issues with iterating age of item through dictionary in python 3 -

i relatively coding, , trying create piece of code calculate amount of descendants single cat can have. when cat supposed iterate fifth month; dissapears no reason, changing both dictionaries. code follows: def speciescalc(pt, tbf, abif, toe, bpy, bil, fsn, ifsnm, sn): sn = {} sn2 = {} if abif < toe: in range(0, int(abif) + 1): sn[str(i)] = 0 else: in range(0, int(toe) + 1): sn[str(i)] = 0 sn[str(tbf - 1)] = fsn ##debug print print(sn) in range(0,int(toe)): o in range(0, len(sn)): if o > 0: sn2[str(o)] = sn[str(o-1)] ##debug prints print(o-1) print(sn) print(sn2) else: sn2['0'] = 0 p in range(pt + tbf, len(sn), bpy): sn2['0'] += sn2[str(p)]*bil print(sn2['0']) sn = {} sn = sn2 in range(0, len(sn)): fsn += int(sn[str(i)]) print(str(sn[str(i)])) return (fsn) print(speciescalc(2, 4, 120, 18, 3, 6, 1, 0, 0))

html - Advertisement is flying down inside iframe - CSS mistake? -

i had been researching convert fixed width/height iframes of gaming portal responsive , found bunch of different suggestions people, out of made css addition targeted @ iframe class worked make responsive, when tested on ipad using safari browser ad appears in beginning of games starts flying down , therefore makes impossible game begin. could please me correct problem? here more details: inside article have iframe game embedded in following code: <center> <div class="game-responsive-container" style="padding-bottom: 66.81%;"> <iframe src="gameurl" frameborder="0" scrolling="no"></iframe> </div> </center> fyi1: class "game-responsive-container" target in css (shown below). fyi2: padding-bottom part dedicated per page because each game have different height. in css have following related question: .game-responsive-container { position: relative; height: 0; overflow: h

Minimal Haskell OpenGL Example causes OpenGL Error -

i toying opengl example , ran problem. minimized 1 of mainstream haskell/opengl examples . windows 10, haskell platform (32-bit 8.0.2-a. positive it's -a variant). import graphics.ui.glut main :: io () main = (_progname, _args) <- getargsandinitialize _window <- createwindow "hello world" displaycallback $= display mainloop display = let color3f r g b = color $ color3 r g (b :: glfloat) vertex3f x y z = vertex $ vertex3 x y (z :: glfloat) clear [colorbuffer] renderprimitive points $ -- color3f 1 0 0 -- vertex3f 0 0 0 return () -- << error on glend() of renderprimtive >> flush reporterrors facts: i've tried default glut32.dll comes haskell platform (ghc 8.0.2) , tried freeglut . using gdebugger, able determine glend command reports error first (called renderprimtive ). no body (vertices or color changes), render issues command makes opengl unhappy (, or empty command generates different error)

A little different than ordinary case of MySQL and xampp -

i've been struggling problem quite time, downloaded 'mysql server' , 'workbench' , installed them, later downloaded xampp , there problem xampp comes own mysql , not able trace installed version, want give xampp path installed mysql. tried installing xampp own mysql there conflict ports between 2 - sql(that came xampp) , mysql.

javascript - Reactjs react-google-maps undefined -

i working react-google-maps package https://github.com/tomchentw/react-google-maps , https://www.npmjs.com/package/react-google-maps . have error says: ./src/app.js line 31: 'google' not defined no-undef line 32: 'google' not defined no-undef line 37: 'google' not defined no-undef line 42: 'google' not defined no-undef line 44: 'google' not defined no-undef and heres line in error: state = { origin: new google.maps.latlng(41.8507300, -87.6512600), destination: new google.maps.latlng(41.8525800, -87.6514100), directions: null, } componentdidmount() { const directionsservice = new google.maps.directionsservice(); directionsservice.route({ origin: this.state.origin, destination: this.state.destination, travelmode: google.maps.travelmode.driving, }, (result, status) => { if (status === google.maps.directionsstatus.ok) { this.setstate({ dir

c++ - Why can't I instantiate a reference to a base class at the same time as a pointer to a derived class? -

the simplest example of question can seen in following code snippet: class handle : public ihandle_<handle>{ public: handle(std::unique_ptr<derived> aderived) : derived(std::move(aderived)), base(*aderived) {}; std::unique_ptr<derived> derived; base& base; }; here, can see handle class wrapper around derived . more importantly, wish expose base class of derived , base , way of reference. reason that, ultimately, wish handle this: class handle : public ihandle_<handle>{ private: std::unique_ptr<derived1> myd1; std::unique_ptr<derived2> myd2; public: handle(std::unique_ptr<derived1> ad1) : myd1(std::move(ad1)), base1(*ad1), base2(*ad1){}; handle(std::unique_ptr<derived2> ad2) : myd2(std::move(ad2)), base1(*ad2), base2(*ad2){}; base1& base1

javascript - How to access the correct `this` inside a callback? -

i have constructor function registers event handler: function myconstructor(data, transport) { this.data = data; transport.on('data', function () { alert(this.data); }); } // mock transport object var transport = { on: function(event, callback) { settimeout(callback, 1000); } }; // called var obj = new myconstructor('foo', transport); however, i'm not able access data property of created object inside callback. looks this not refer object created other one. i tried use object method instead of anonymous function: function myconstructor(data, transport) { this.data = data; transport.on('data', this.alert); } myconstructor.prototype.alert = function() { alert(this.name); }; but exhibits same problems. how can access correct object? what should know this this (aka "the context") special keyword inside each function , value depends on how function

In C, how to indicate EOF after writing data without close/shutdown a socket? -

i new c socket programming. learned after sending data through socket, 1 should either close or shutdown socket descriptor, triggers eof sent other end. without eof, read / recv keeps blocking. now wondering if possible @ keep socket open further data transfer. read, seems people when establish keep-alive http connection. not figure out how achieved. the following code shows scenario, stuck after client's write . #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #define thread_printf(...) printf("[pid %d] ", getpid()); printf(__va_args__); int create_socket() { int socket_fd; socket_fd = socket(af_inet, sock_stream, 0); if (socket_fd < 0) perror("error opening socket"); return socket_fd; } int listen_port(int portno) { int socket_fd; struc

object oriented python 3 input error -

i'm working python 3.4 on debian 8.5 linux. i'm working "learn python 3 hard way" , i'm working section running test (via nosetests). have code (which include in full) , it's giving me error on statement should valid, i'm assuming it's not liking how i've set statement up. it's on "class prompt" section: class prompt(object): prompt = input("> ") the idea code prompt 1 time and: call later on easier coding, nose keeps responding : typeerror: bad argument type built-in operation i'll include full error test well. i'm looking see if in fact, i'm calling prompt incorrectly , if so, i'd appreciate nudge in right direction, not full solution ( learn better way :) ) thanks! ====== begin engine.py ============== # babylon 5 scorched earth # more advanced example of proof-of-concept worked on # few weeks ago. # time engine 1 file, rooms can # self contained , need include 1 file # have

javascript - How to update a specific(nth) child of a key in firebase -

Image
i know firebase has basic query functionality orderby , limitto , startat , endat ...., etc. updating has methods update , set . in case have structure this: so, there list of keys on pin , how can update child pin of specific key javascript? for example, want update pin of second key. has 20 , , want set 30 . please, keep in mind list have more 2 keys, maybe later want update child pin of fourth generated key. how can this? relative ordering "second" or "fourth" pretty useless here. if want update pin of node key -krno...ho can with: firebase.database().ref("pin/`-krno...ho/pin").set(30); if want update pin of user named cindy, first need query determine key: firebase.database().ref("pin").orderbychild("name").equalto("cindy").once("value", function(snapshot) { snapshot.foreach(function(user) { user.ref.child("pin").set(30); }); }) the loop in second snippet needed,

java.util.scanner - Unable to take multiple String input using scanner in java -

i have been trying program in have concat 3 strings in java.i taking input user using scanner.it compiles perfect when run it,it gives me error: exception in thread "main" java.util.inputmismatchexception @ java.util.scanner.throwfor(scanner.java:864) @ java.util.scanner.next(scanner.java:1485) @ java.util.scanner.nextint(scanner.java:2117) @ java.util.scanner.nextint(scanner.java:2076) @ night.main(night.java:10) this code: import java.lang.*; import java.util.*; class demo { public static void main(string[] args) { string fn; string mn; string ln; string fmn, lmn; scanner sc = new scanner(system.in); fn = sc.nextline(); mn = sc.nextline(); ln = sc.nextline(); fmn = fn.concat(mn); lmn = fmn.concat(ln); system.out.println("the full name of candidate : " + lmn); } } i believe current code in demo class working fine. can check again?! exception night.main(night.java:10) . if st

reactjs - Razor Pages and Razor Views -

is idea mix razor pages razor views in same asp.net core 2.0 app? if understand correctly, benefit of using razor pages don't need controller actions. in app, have pages return react app. feel razor pages perfect because need in page link bundle.js file. having said that, have few pages need controller , send view model. so, idea have both pages , views or should stick 1 , not mix together? read razor pages in docs , rick anderson(member of asp.core team) said here that: you can mix controllers, views , razor pages. rp unit testable (using code-behind). it's question. see https://github.com/aspnet/mvc/issues/494#issuecomment-232534742 motivation. so can mix. tiny issue, in opinion, read docs that: note: layout in pages folder. pages other views (layouts, templates, partials) hierarchically, starting in same folder current page. means layout in pages folder can used razor page under pages folder. which means cannot use same l

numpy - using specific forms of gradients of two neural network to minimize a loss w.r.t its parameters -

suppose have loss function f(self.theta, self.sigma) self.theta , self.sigma both defined 2 neural network, example, in tensorflow, self.sigma = tf.contrib.layers.fully_connected( inputs=tf.expand_dims(self.state, 0), num_outputs=1, activation_fn=none, weights_initializer=tf.zeros_initializer) if have derived forms of gradients of f(self.theta, self.sigma) w.r.t self.theta , self.sigma , denoted theta_gradient , sigma_gradient respectively, how can minimize loss function f(self.theta, self.sigma) using these given forms of gradients minimize loss function. from this answer of similar question, seems can done using tf.apply_gradient when there set parameters neural network instead of two. have no idea how solve above problem. main difficulty here have 2 forms of gradients, theta_gradient theta , sigma_gradient sigma , how apply them optimize loss function unclear. based on that, first attempt following, self.optimizer = tf.train.adamoptimizer(le

ios - How to add constraints to TableView on TableViewController? -

Image
i have tabbar , searchcontroller , tableview ... to fix problem black screen, added following string tableviewcontroller places searchcontroller on itself: self.definespresentationcontext = true but, receive next problem - after move next controller , tableviewcontroller table placed below navigation bar. how can fix that? you can try in tableviewcontroller viewdidload method: yourtableview.contentinset = uiedgeinsets(top: 50, left: 0, bottom: 0, right: 0)

django - Configuring NGINX for correct URL forwarding to Graphite docker image -

i have web application running on debian through nginx , uwsgi. we've begun using graphite , statsd running in docker container collect stats on application (from https://github.com/hopsoft/docker-graphite-statsd ). docker container has own nginx serve graphite. running docker container forwarding port 8081 80 , able access graphite through http:// example.com:8081. i trying route web traffic graphite through our existing nginx server able use our established authentication method when accessing it. i able access graphite via example.com/graphite/ , have associated content referred under directory. currently example.com/graphite/ forwards http:// example.com:8091/graphite/. url not appear change. there, graphite loads up, page elements load :8091/, e.g. http:// example.com:8091/content/js/ext/resources/images/default/sizer/s-handle.gif, whereas referred via http:// example.com/graphite/content/js/ext/resources/images/default/sizer/s-handle.gif. when go domain.com/g

lambda - Retaining a pointer by extending the life of capture -

this question has answer here: why lambda init-capture not work unique_ptr? 1 answer is possible extend life of unique_ptr capturing in lambda , extending life of lambda? i tried out getting syntax errors a=move(a) expression. #include <cstdio> #include <functional> #include <memory> #include <iostream> using namespace std; struct { a() { cout << "a()" << endl; } ~a() { cout << "~a()" << endl; } }; int main() { std::function<void ()> f; { std::unique_ptr<a> a(new a()); f = [a=move(a)] () mutable { return; }; } return 0; } well problem code std::function . not move friendly needs callable copy constructible/assignable lambda not because of use of move type, unique_ptr in example. there many examples out there can provide move friendly version of std:

javascript - socket.io not working no error shows -

i'm working on chat application using node.js,socket.io , express. i'm using pm2 run server.js . on log says 0|server | 18-08 12:14:47.128: server listening on port 3000 there no error in console either. codes . please bear me i'm still newbie in node.js , socket.io. every highly appreciated. server.js process.env.node_tls_reject_unauthorized = "0"; var app = require('express')(); var https = require('https'); var fs = require('fs'); var ssl_server_key = '/data/web/chat/app/node/server_key.pem'; var ssl_server_crt = '/data/web/chat/app/node/server_crt.pem'; var server = https.createserver({ key: fs.readfilesync(ssl_server_key), cert: fs.readfilesync(ssl_server_crt), npnprotocols: ['http/2.0', 'spdy', 'http/1.1', 'http/1.0'] }, app); var socket = require('socket.io'); var port = process.env.port || 3000; var io = socket.listen(server); server.listen(p

python - Pandas backward fill increment by 12 months -

i have dataframe course names each year. need find duration in months starting year 2016. from io import stringio import pandas pd u_cols = ['page_id','web_id'] audit_trail = stringio(''' year_id | web_id 2012|efg 2013|abc 2014| xyz 2015| pqr 2016| mnp ''') df11 = pd.read_csv(audit_trail, sep="|", names = u_cols ) how add months in new column starting highest (i.e. bottom bfill?) the final data-frame this... u_cols = ['page_id','web_id' , 'months'] audit_trail = stringio(''' year_id | web_id | months 2012|efg | 60 2013|abc | 48 2014| xyz | 36 2015| pqr | 24 2016| mnp | 12 ''') df12 = pd.read_csv(audit_trail, sep="|", names = u_cols ) some of answers not consider there can multiple courses. updating sample data... from io import stringio import pandas pd u_cols = ['course_name','page_id','web_id'] audit_trail = stringio(''

php - Get average of values for a specific time frame and specific entry types -

i have table this: id | type | value | timestamp -------------------------------- 1 | aaa | 0.5 | day 1 hour 1 2 | bbb | 1.5 | day 1 hour 1 3 | ccc | 1.8 | day 1 hour 1 ..... 11 | aaa | 0.6 | day 1 hour 2 12 | bbb | 1.4 | day 1 hour 2 13 | ccc | 1.5 | day 1 hour 2 ..... id := int, pk, ai, , on type := string/varchar value := double timestamp := unix timestamp (int), changed date type what want average specific timeframes. example: i want aaa , bbb average of "value" day 1 till day 3. every day has 24 entries per type on several days. expected result be type | average | timestamp/date ------------------------------- aaa | 0.5242 | day 1 aaa | 0.5442 | day 2 aaa | 0.5913 | day 3 bbb | 1.4228 | day 1 bbb | 1.6924 | day 2 bbb | 1.3018 | day 3 i'm not sure if possible mysql. maybe it's more efficient php? does produce result require? # drop table if exists likethis; create table likethis (id int unsigned,

Python: Appending items to a list -

i want append few items within loop lists. doing is, lista = [] listb = [] listc = [] in range(0,100): lista.append(i) j in range(0,100): listb.append(j) and on. there smarter way that? the simple way achieve is: lista = range(100) listb = range(100) listc = range(100) or lista, listb, listc = [range(100) _ in range(3)] hope helps.

Google Cloud Speech service is down? -

the problem using v1 , latest @0.10.2. worked 6 months (even v1beta) until yesterday when randomly (and silently!) stops working. mean 1 call of streamingrecognize may go , recognition starts, second or third call of streamingrecognize don't receive input (and i'm getting you're streaming slow error). using same code! and in recognition starts, quality low. leading wrong results. the problem started occuring after releasing v1 beta, suppose, i'm not sure. environment details os: amazon linux 4.4.44-39.55.amzn1.x86_64 node.js version: v7.2.1 npm version: 3.10.10 using google-cloud/speech@0.10.2 the code: var speech = require('@google-cloud/speech')({ credentials: require(_base + '/google_cloud_credential.json') }); self.recognizestream = speech.streamingrecognize({ config: { encoding: 'mulaw', sampleratehertz: 8000, languagecode: "ru-ru", }, singleutterance: fals