Posts

Showing posts from March, 2011

c# - if (!localplayer) not doing anything -

Image
i'm making multiplayer dodgeball game , every time start host , client, 1 of players can move. i want players move independently. here (updated) code: using system.collections; using system.collections.generic; using unityengine; using unityengine.networking; public class script4network : networkbehaviour { // use initialization void start() { if (!islocalplayer) { gameobject.getcomponent<firstpersoncontroller>().enabled = false; gameobject.getcomponent<throwing>().enabled = false; gameobject.getcomponent<headbob>().enabled = false; // gameobject.getcomponent<camera>().enabled = false; } } void update() { } } this isn't answer because i've been out of unity long, know: void update() { if (!islocalplayer) { return; } } does nothing @ all. it's same thing as: void update() { if (!islocalplayer) { return; } return; } because every funct

utf 8 - Elixir: Counting Frequency of Words in Text File in Hangul Alphabet -

but working data written in hangul. have word frequency script have used english txt files, script fails when pass utf-8 txt file containing hangul characters. specifically, seems read characters blank spaces. results, stored in .csv file: , 290668 1, 2 2, 5 3d, 1 4, 1 55, 1 6, 1 6mm, 2 709, 2 710, 1 d, 1 j, 87 k, 1 m, 14 p, 19 pd100, 1 y, 1 considering text in file contains none of these characters, seems problem. how make code read hangul? current code: defmodule wordfrequency def wordcount(readfile) readfile |> words |> count |> tocsv end defp words(file) file |> file.stream! |> stream.map(&string.trim_trailing(&1)) |> stream.map(&string.split(&1,~r{[^a-za-z0-9_]})) |> enum.to_list |> list.flatten |> enum.map(&string.downcase(&1)) end defp count(words) when is_list(words) enum.reduce(words, %{}, &update_count/2) end defp update_count(word, acc) m

Downloading Java JDK on Linux via wget is shown license page instead -

when try download java oracle instead end downloading page telling me need agree otn license terms. sorry! in order download products oracle technology network must agree otn license terms. be sure that... your browser has "cookies" , javascript enabled. you clicked on "accept license" product wish download. you attempt download within 30 minutes of accepting license. how can download , install java? updated jdk 8u131 rpm: wget -c --header "cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u131-b11/d54c1d3a095b4ff2b6607d096fa80163/jdk-8u131-linux-x64.rpm tar gz: wget -c --header "cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u131-b11/d54c1d3a095b4ff2b6607d096fa80163/jdk-8u131-linux-x64.tar.gz rpm using curl: curl -v -j -k -l -h "cookie: oraclelicense=accept-securebackup-cookie"

javascript - React - How to return and string of HTML -

i guess i'm old fashioned , build strings of html , data. expecting react handle nicely when return string. there , obvious approach? , <br> doesn't seem work place. there substitute? (below: cut , paste .html file , it'll run.) <!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <div id="root"></div> <script type="text/babel"> var sportspeople = [ {thegame: 'football', name: 'tom brady' }, {thegame: 'basketball', name: 'le bron james' } ] class banner extends react.component { constructor(props) { super(props); }; render() { return ( <div>big banner on top</div>); } } class anotherline extends react.component { constructor(props) { super(props); }; render() { let htmlstuff = ""; let workt

java - How find common number from two textview -

i have 2 textview , 2 buttons. textview tv1,tv2; button yes,no; now tv1.settext("1 2 3 4 5"); tv2.settext("3 4 5 6 7"); and yes.setonclicklistener(new view.onclicklistener() { @override public void onclick(view view) { //here want show common number (3,4,5) } }); no.setonclicklistener(new view.onclicklistener() { @override public void onclick(view view) { //here want show number no matched in both textview } }); now question when click on yes show (3,4,5 because common) tv1 , when click on no show (1,2,6,7) tv1. i can set text if have more numbers. you may put number array or list easy find common number. public list<integer> findcommonelement(int[] a, int[] b) { list<integer> commonelements = new arraylist<integer>(); for(int = 0; < a.length ;i++) { for(int j = 0; j< b.len

c++ - Forward iterator/random acces iterator and `operator*` over temporary iterators -

is this: auto& ref1 = *it++; ref1 = expression; // (1) one of required semantics of forward iterator? , random access iterator? auto& ref1 = it[3]; ref1 = expression; // (2) according cppreference , forward iterator required to: // return reference, equals (const) value_type & *it++ === value_type& and random access iterator: it[n] === *(it + n) which same situation, means in both situations dereferencing temporary (the iterator). in case, iterator stores copy index allows access container doesn't provide direct access stored elements, through index. that works fine: *it++ = value; since temporary copy of it has sentence scope. but in case: type& val = *it++; val = 3; we undefined behaviour, since copy destroyed in second line. in situation, have qmodelindex wrapper data/save from/to qabstractitemmodel . model gives copies of qvariant s stored on model. my wrapper class (the value_type operator= overloaded) saves instance

python - send_from_directory with dynamic path -

i'm trying use send_from_directory return file.this code works fine. @app.route("/img/<filename>") @login_required def send_img(filename): path = '../py/img_detected/invador' return send_from_directory(path,filename) but if change path dynamic path like @app.route("/img/<dir><filename>") @login_required def send_img(dir,filename): path = '../py/img_detected/%s'%dir return send_from_directory(path,filename) it cannot work. furthermore, tried change path = '../py/img_detected/invador' dir='invador' path = '../py/img_detected/%s'%dir it cannot work either. can tell me reason of problem? , can if want function more flexible? the error message : 127.0.0.1 - - [07/apr/2017 04:56:41] "get /invador_img http/1.1" 200 - 127.0.0.1 - - [07/apr/2017 04:56:41] "get /img/invador2017-04-07-01-37.png http/1.1" 404 - sorry mistake, check code again , find mi

php - How can I run a script that open terminal and execute .sh file from Website -

i wish run these code 1 click event in website though button. using php execute shell script. inside shell script have coding, , realize line of code wont work. how can open terminal remotely using website ?(currently using php) lxterminal -e -hold seeking expert ! ^^

php - Yii2 class Yii/web/UrlManager causes error -

i have urlmanager in web.php 'urlmanager' => [ //'class' => 'yii/web/urlmanager', 'enableprettyurl' => true, 'showscriptname' => false, 'enablestrictparsing' => false, 'rules' => [ '<controller:\w+>/<id:\d+>' => '<controller>/view', '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>', '<controller:\w+>/<action:\w+>' => '<controller>/<action>', ], ], i wanna know, why if uncomment 'class' => 'yii/web/urlmanager', cause error when run website. thank much your class path url manager is not correct. yii work namespace , use namespace use backslash \ instead of front slash / . code should in following format: 'c

jquery - Why does my sign up button redirect to index.php? -

i'm confused, can't explain problem well. when click on sign button, redirects index.php . it's supposed check errors, not redirect or that. i've tried deleting bugs code, changing id's, changing css properties. adding , deleting jquery. have no idea how fix problem. edit in success function, have tried remove window.open() , still redirects index.php on click of #check_signup . i'm going keep line there show original code suppose like. code isn't suppose redirecting because code hasn't reached success text yet. what's suppose happen code checks errors through ajax through check_signup.php . page returns word "success" if code executed properly. code in script.js check word "success" before redirecting index.php. i tried removing id #check_signup , page didn't redirect. when try make page alert on click of #check_signup , doesn't work. page redirecting before click element registered. this code: script.

python - Get content of a string variable using getattr -

i know how retrieve content of string variable can use value argument name in function. here code: import pandas import jinja2 odatelist = ['2017-03-22','2017-03-23','2017-03-24'] odata = pandas.dataframe() odata['date'] = odatelist mytemplate = 'today {{ date }}' otemplate = jinja2.template(mytemplate) orow in odata.index: ocolumn in odata.columns: mytemplateupdated = otemplate.render(date=odata.loc[orow, ocolumn]) print(mytemplateupdated) it works , returns: today 2017-03-22 today 2017-03-23 today 2017-03-24 i dynamically retrieve argument name date= dataframe column name ocolumn (which 'date'). thought using getattr(ocolumn, 'something') did not figure out how so. i have tried str(ocolumn) , returns error: syntaxerror: keyword can't expression thank you if want dynamically set argument name being sent function, you'll need use kwargs. render(**{argument_name: argument

Loading dll using Python Ctypes -

i've looked @ example given here ctypes - beginner , followed same steps different bit of c code. i've built .dll , .lib using c code given here: http://wolfprojects.altervista.org/articles/dll-in-c-for-python/ //test.c __declspec(dllexport) int sum(int a, int b) { return + b; } in wrapper.py have this: import ctypes testlib = ctypes.cdll("c:\\users\\xyz\\documents\\python\\test.dll") when run script error: self._handle = _dlopen(self._name, mode) oserror: [winerror 193] %1 not valid win32 application if use testlib = ctypes.libraryloader("c:\\users\\xyz\\documents\\python\\test.dll") then don't error on running script. if try this: testlib.sum(3,4) i error: dll = self._dlltype(name) typeerror: 'str' object not callable the dll , .py in same folder. can me understand what's going on here. i've spent hours trying figure out, have hit wall. thanks. make sure compiler , version

rest assured - Intercepting an assignment in Java -

i'm using rest-assured library testng receiving response in response object below. response response; @test public void sometest() { restassured.baseuri = "some_valid_baseuri"; restassured.basepath = "some_valid_endpoint"; response = restassured.given().contenttype(contenttype.json).when().get(); } i have several test methods above-mentioned method in test class. there way intercept response assignment can, somewhere else (e.g. in method annotated @aftermethod ), know method being used response get method? ps: did not find in-built way in rest-assured library this. the answer in is possible extract method name response object? serves purpose question. sorry generic question line here though!

How to convert spark RDD to mahout DRM? -

i fetching data alluxio in mahout using sc.textfile(), spark rdd. program further uses spark rdd mahout drm, therefore needed convert rdd drm. current code remains stable. an apache mahout drm can created apache spark rdd in following steps: convert each row of rdd mahout vector zip rdd index (and swap tuple of form (long, vector) wrap rdd drm. consider following example code: val rdda = sc.parallelize(array((1.0, 2.0, 3.0), ( 2.0, 3.0, 4.0), ( 4.0, 5.0, 6.0))) val drmrdda: drmrdd[long] = rdda.map(a => new densevector(a)) .zipwithindex() .map(t => (t._2, t._1)) val drma = drmwrap(rdd= drmrdda) source /more info/ shameless self promotion (toward bottom): my blog

pip install numpy fails (python 2.7 on Artik 710 board (Fedora)) -

i'm installing numpy through pip on samsung artik 710 (fedora , python 2.7). pip version 9.0.1. i have inputted following: pip install numpy however following error message: collecting numpy using cached numpy-1.12.1.zip installing collected packages: numpy running setup.py install numpy ... error complete output command /usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-xyasfu/numpy/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-shmawz-record/install-record.txt --single-version-externally-managed --compile: running numpy source directory. note: if need reliable uninstall behavior, install pip instead of using `setup.py install`: - `pip install .` (from git repo or downloaded source release) - `pip install num

c# - custom filter in kendo grid datasource -

in kendo grid loading data .grid<portals.areas.reports.models.transactionreportitem>() like this. again provided in datasource .datasource(datasource => datasource .ajax() .pagesize(100) .read(read => read.action("gettransactions","transactions"))) my problem when provided external filter, because of datasource displaying data instead of filter data. question how can apply external filter condition in data source or possible stop calling datasource ? using server side grid control . on read action add this: .read(read => read.action("gettransactions","transactions").data(getdatafilters)) .data() call function give every time read action occurs. <scrip> function getdatafilters() { // add values filters variables. var filterfield1 =

unity3d - Unity 3D: Transition of Animation -

i new unity3d , working on following tutorial: https://www.youtube.com/watch?v=gxpi1czz5na it worked fine. i wanted add functionality if skeleton hits sword, real he's taking damage. sort of poorman's way of having sword collide objects. but i've found doesn't work correctly. seem either have choice cause 'hit' put infinite loop, or ignore hit together. here code: using system.collections; using system.collections.generic; using unityengine; public class chase : monobehaviour { public transform player; static animator anim; // use initialization void start () { anim = getcomponent<animator> (); } // update called once per frame void update () { //debug.log (anim.tostring ()); //debug.log ("start update"); vector3 direction = player.position - this.transform.position; //debug.log ("distance: " + direction.magnitude.tostring ()); float angle = ve

python - Trying to get download URL for pySmartDL -

i trying make browser in pygtk using webkit. trying use pysmartdl download manager since defualt bit tedious. have sample code: import os pysmartdl import smartdl url = " http://mirror.ufs.ac.za/7zip/9.20/7za920.zip " dest = "c:\downloads\" # or '~/downloads/' on linux obj = smartdl(url, dest) obj.start() path = obj.get_dest() i want know how download url when "download-requested" signal emitted.

python - UnicodeDecodeError: 'ascii' codec can't decode byte in Textranking code -

this question has answer here: how fix: “unicodedecodeerror: 'ascii' codec can't decode byte” 11 answers when execute below code import networkx nx import numpy np nltk.tokenize.punkt import punktsentencetokenizer sklearn.feature_extraction.text import tfidftransformer, countvectorizer def textrank(document): sentence_tokenizer = punktsentencetokenizer() sentences = sentence_tokenizer.tokenize(document) bow_matrix = countvectorizer().fit_transform(sentences) normalized = tfidftransformer().fit_transform(bow_matrix) similarity_graph = normalized * normalized.t nx_graph = nx.from_scipy_sparse_matrix(similarity_graph) scores = nx.pagerank(nx_graph) return sorted(((scores[i],s) i,s in enumerate(sentences)), reverse=true) fp = open("qc") txt = fp.read() sents = textrank(txt) print sents i following error

How to disable logging for illegal host headers request in nginx -

in nginx.conf, add following code deny illegal request: server { ... ## deny illegal host headers if ($host !~* ^(www.mydomain.com|xxx.xxx.xxx.xxx)$) { return 444; } ... } but request info written in access log, monitor request think because many , 2 unsafe site , head request. so how stop logging these illegal request info access log? thanks. you should use separate server blocks server { listen 80; # valid host names server_name www.example.com; server_name xx.xx.xx.xx; # site goes here } # requests other hostnames caught server block server { listen 80 default_server; access_log off; return 444; } that simple , efficient

angularjs - ng-repeat is not working inside the table row -

i want fetch data inside table not getting data. code here-- <div ng-controller="tenders"> <table ng-init="getviewprojectdetail('<?php echo $project_id ; ?>')"> <thead> <tr class="active"> <th colspan="4"> project detail: </th> </tr> </thead> <tbody> <tr> <th><b>project name :</b></th> <td ng-repeat="a in viewprojects"> {{a.id}} </td> {{viewprojects | json}} </tr> </tbody> </tab

python - RabbitMQ: Pika: Add timeout while consuming -

how can add timeout in rabbitmq consumer using pika library every new message in queue waits timeperiod processed consumer? using blocking connection use add_timeout callback mentioned in docs

Java Grid Class -

Image
i trying make java grid w/ intended output as: but output off 1 in looks this: . suggestions? public class grid { private int rows = 0; private int columns = 0; private string [] [] grid; public grid(int rows, int columns){ this.rows = rows; this.columns = columns; grid = new string [rows] [columns]; initializegrid(); } public void initializegrid(){ (int = 0; < rows; i++){ (int j = 0; j < columns; j++) { grid [i] [j] = "| "; } } } public void printgrid(){ system.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); (int = 0; < rows; ++i){ system.out.println("|"); (int j = 0; j < columns; ++j){ system.out.print(grid[i][j] + "

python - Select first object of group by in postgresql/sqlalchemy -

i have request in sqlachemy sqlite return object of group , value (avg) : result = session.query( obj, func.avg(obj.value).label("value_avg") ).group_by( func.strftime('%s', obj.date) ).all() but need use postgresql more restrictive (strict sql) , need same thing need replace query(obj) in group func.avg() or else. know if exist func can able return first obj of each group. if not possible maybe can implement comparator obj , instance call func.min(obj) : result = session.query( func.min(obj), func.avg(obj.value).label("value_avg") ).group_by( func.date_part('second', obj.date) ).all() and maybe implement cmp , eq in obj model ? (what best practice) edit : i got workaround i'm not sure it's practice. first group , next join : sq = session.query( func.min(obj.date).label("date"), func.avg(obj.value).label("value_avg") ).group_by( func.ca

Oracle sql WITH clause and EXTRACT function -

i trying understand difference between 2 queries below. second 1 throws syntax error. can please? 1. select extract(year (sysdate - to_date('2002-12-25')) year month) y dual; 2. with age(d) ( select (sysdate - to_date('2002-12-25')) dual ) select extract(year (age.d) year month) y age; error: ora-30083: syntax error found in interval value expression 30083. 00000 - "syntax error found in interval value expression" *cause: syntax error found during parsing interval value your question simplified bit to, why work: select (sysdate - date '2002-12-25') year month dual; (sysda ------ +14-03 but plugging same number produced sysdate - date '2002-12-25' same call not, or without parentheses in various combinations: select (5217.4197) year month dual; ora-30083: syntax error found in interval value expression the problem 2 numbers different internally. @hinoff suggested, can use dump() function examine t

distributed computing - Similarities on the Cloud and Blockchain -

not sure if asking in correct site. i have come across number of terms such blockchain service ( baas ), blockchain platforms / stack etc. , have come across number of articles defining blockchain sort of cloud 2.0 implying of course similarities between two. having thought thought ask: what similarities between blockchain , cloud architecture itself? in way can blockchain compared cloud architecture?

.net - How to pass System.Type in ObjectDataProvider.MethodParameters? -

i want bind function parameter textblock in xaml. function parameter has type system.type . how notate complex object methodparameter in xaml? <window.resources> <objectdataprovider x:key="mykey" objecttype="{x:type mytype}" methodname="mymethod"> <objectdataprovider.methodparameters> <system:int32>123</system:int32> <!-- e.g. primitive type parameter --> <mynamespace:mycustomtype>what comes here?</mynamespace:mycustomtype> </objectdataprovider.methodparameters> </objectdataprovider> </window.resources> [...] <textblock text="{binding source={staticresource mykey}}" /> use x:type : <objectdataprovider x:key="mykey" objecttype="{x:type mytype}" methodname="mymethod"> <objectdataprovider.methodparameters> <system:int32>123</system:int32> <

c++ - Errors when compiling a project with Cygwin -

i'm trying compile project ( https://github.com/alfchen/qoetrafficanalyzer ) in windows 7 using cygwin. in linux have no problem, need in windows. installed winpcap following steps included here: help installing libpcap on cygwin . however, i'm still having problems. know project uses arpa/inet.h , under windows have use winsock2.h, changing not solve anything. right i'm having following error. hope can me. $ make g++ -c tcpflowstat.cpp -wno-deprecated -i include/ -o tcpflowstat.o tcpflowstat.cpp: en la función miembro static ‘static int tcpflowstat::isnewflow(std::string, std::string, tcphdr*)’: tcpflowstat.cpp:33:17: error: ‘struct tcphdr’ has no member named ‘syn’ if (tcphdr->syn==1 && tcphdr->ack!=1) return 1; ^ tcpflowstat.cpp:33:35: error: ‘struct tcphdr’ has no member named ‘ack’ if (tcphdr->syn==1 && tcphdr->ack!=1) return 1; ^ tcpflowstat.cpp: en la función miembro ‘int