Posts

Showing posts from May, 2014

javascript canvas bottom and top collision detection -

so have been looking around , trying tutorials can't seem collision detection systems work. if able explain doing wrong or syntax errors great. player right touch object works player left touch object works 1--not working jump on objects 2-- not working hit top of objects i'm new in javascript first serious project while if http://codepen.io/guntarwii/pen/ebmnwb function startgame() { gamearea.start(); } var gamearea = { canvas: document.createelement("canvas"), start: function () { this.canvas.width = 720; this.canvas.height = 500; this.context = this.canvas.getcontext("2d"); document.body.insertbefore(this.canvas, document.body.childnodes[0]); this.interval = setinterval(updategamearea, 20); // console.log(gamearea.context) document.addeventlistener("keydown", optiones.moveme); ...

python - Modifying a clipboard content to be treated as HTML -

when “copy image” on web (by highlighting image , ctrl+c) , passed text view of html wysiwyg editor (not source code editor) picture displayed. though paste in text editor ( source code editor), content of clipboard understood editor html code. for example, if paste “<img src="someurl" /> in text editor, added in source code “<p>&lt;img src="someurl" /&gt;</p>” clipboard isn’t understood editor html code. so how should modify content of clipboard html wysiwyg editor understand html code though pasting in text view (not source code editor)? what want in more details: when have url of image stored in clipboard, want able add image html wysiwyg editor without having switch source code editor. transform content of clipboard (by adding code before , after url) understood html code (just example mentioned above) html wysiwyg editor. edit: better target answer here try achieve. when use sharex upload picture, sharex store auto...

arrays - C++11 list initialization weird behaviour on Visual Studio 2013 -

i'm trying pass array function , prevent writing "std::unique_ptr" each time , make inline construction possible, introduce typedef (itemlist) alias array. #include <iostream> #include <memory> class base { public: base() { std::cout << "base ctor" << std::endl; }; virtual ~base() { std::cout << "base dtor" << std::endl; }; }; typedef std::unique_ptr<base> itemlist[]; template<typename t> class derived : public base { t val; public: derived(t i) { val = i; std::cout << "derived ctor" << val << std::endl; }; ~derived() { std::cout << "derived dtor" << val << std::endl; }; }; void dummyfunc(itemlist) { } void testfunc() { dummyfunc(itemlist{ std::make_unique<derived<int>>(2), std::make_unique<derived<float>...

html - Setting height attribute on div with JQuery yields inconsistent behavior -

i have simple 3 column (divs) page center content column bounded 2 sidebars. sidebars remain relatively static content column being dynamic page-to-page. goal ensure sidebars retain same height content column , after mashing in css, figured simple jquery solution far cleaner. enter following code: $(document).ready(function () { setdivattributes(); }); function setdivattributes() { $("#sidebar-left").height($("#content").height()); $("#sidebar-right").height($("#content").height()); } this works perfect, when runs , therein lies problem. can't simple bit of code run reliably. works fine in jsfiddle when run in various browsers, inconsistent behavior. load perfect. need refresh once, multiple times , have restart whatever browser altogether. figured maybe code running before content div had finished loading every solution i've encountered fails solve problem. i suspect there simple solution has evaded me far. ...

javascript - Getting NaN as a result for my JS function. Could anyone explain why? -

i'm new javascript, please bear me. wrote function returns difference between highest , lowest number in array: // function 1 function range (arr) { var max = math.max.apply(null, arr); var min = math.min.apply(null, arr); var max_diff = max - min; return max_diff; } console.log(range([6,2,3,4,9,6,1,0,5])); // 9 however, before came solution, tried approach: // function 2 function range (arr) { var max = function (arr) { return math.max.apply(null, arr); } var min = function (arr) { return math.min.apply(null, arr); } var max_diff = max - min; return max_diff; } console.log(range([6,2,3,4,9,6,1,0,5])); // nan this function returns "nan". read on nan, it's still not clear me why "nan" result. the other strange thing is: if put function 2 before function 1, second function returns correct result (9). whaaaat? you subtracting 2 functions, max , min . functions first coer...

Implementing fast numerical calculations in R -

i trying extensive computation in r. eighteen hours have passed rstudio seems continue work. i'm not sure if have written script in different way make faster. trying implement crank–nicolson type method on 50000 350 matrix shown below: #defining discretization of cells dt<-1 t<-50000 dz<-0.0075 z<-350*dz #velocity & diffusion v<-2/(24*60*60) d<-0.02475/(24*60*60) #make big matrix (all filled zeros) m <- as.data.frame(matrix(0, t/dt+1, z/dz+2)) #extra columns/rows boundary conditions #fill first , last columns constant boundary values m[,1]<-400 m[,length(m)]<-0 #implement calculation for(j in 2:(length(m[1,])-1)){ for(i in 2:length(m[[1]])){ m[i,][2:length(m)-1][[j]]<-m[i-1,][[j]]+ d*dt*(m[i-1,][[j+1]]-2*m[i-1,][[j]]+m[i-1,][[j-1]])/(dz^2)- v*dt*(m[i-1,][[j+1]]-m[i-1,][[j-1]])/(2*dz) }} is there way know how long take r implement it? there better way of constructing numerical calculation? @ point, feel excel ha...

CakePHP URL - specify a named filed as "null" -

i working on app connects 3rd party cakephp api system. here sample output of url: https://<server>/api/events.json output: {"events":[{"event":{"id":"11902","monitorid":"5","name":"new event","cause":"continuous","starttime":"2016-08-15 17:10:00","endtime":null,"width":"2304","height":"1296","length":"319.81","frames":"1600","alarmframes":"0","totscore":"0","avgscore":"0","maxscore":"0","archived":"0","videoed":"0","uploaded":"0","emailed":"0","messaged":"0","executed":"0","notes":""},"thumbdata":""},{"event":{"i...

How to plot row data from a matlab table -

if have results @ 2 rows methode1 m2 m3 m4 data1 .456 .567 .987 .654 data2 .768 .654 .546 .231 and want draw each line separately 2 lines on same scale from way present data i'm assuming you're dealing matlab table this: >> methode1 = [.456; .768]; m2 = [.567; .654]; m3 = [.987; .546]; m4 = [.654; .231]; >> t = table(methode1, m2, m3, m4, 'rownames', {'data1', 'data2'}) t = methode1 m2 m3 m4 ________ _____ _____ _____ data1 0.456 0.567 0.987 0.654 data2 0.768 0.654 0.546 0.231 and actual question you're not sure how plot because t('data1', :) produces table opposed numbers, , therefore plot(t('data1', :)) doesn't work, rather because you're not aware of plot command (if aren't aware of plot command, read online, you'll find lots of ...

How to use singletons in Swift for data sharing? -

i'm working on app requires information shared between multiple views. simplicity's sake, prefer use singleton said purpose. my questions are... where should singleton class defined , initialized available view controllers , other class files? how should other classes reference said singleton? import statements or special initializations within specific class necessary? i'd mention i'm intrigued 1 line singleton found @ http://krakendev.io/blog/the-right-way-to-write-a-singleton such method preferable. btw: i'm developing using swift in xcode 6.2 thanks. if define singleton, it's available everywhere in target. put wherever want, own .swift file. , use it, you'd following, no special import statements needed: let kraken = theoneandonlykraken.sharedinstance btw, if you're using xcode 6.2, predates swift 1.2 introduced xcode 6.3, you're limited of less elegant struct solutions in article reference. for record, using...

html - Jquery only add without removing class -

i need jquery.i need menu button change "menu button" "x"(which cancel button).but problem jquery adds class in console , in inspector,and doesnt change menu icon.. says class added... here code: $('.tablet-icon').click(function() { if ($('.tablet-icon').hasclass('form-active')) { $('.tablet-icon').removeclass('form-active'); console.log('is-removed'); return false; } else { $('.tablet-icon').addclass('form-acive'); console.log('is-added'); return false; } }); .tablet-icon { position: absolute; padding: 0; margin: 0; right: 0; left: 85%; top: 22px; width: 40px; } .tablet-icon:before { width: 100%; font-size: 1.6em; display: block; font-family: "eleganticons"; font-weight: bold; text-align: center; content: "\61"; } .tablet-icon:before::after { clear: both; content: "...

javascript - How do I filter multiple list items using checkboxes? -

how create 2 checkboxes, displaying (i.e.) 1. food , 2. musician… where 1) if both checkboxes checked, food , musicians displayed; 2) if food checked , musician unchecked, element still visible, because contains food, dispite contains musician; 3) if musician checked , food unchecked, still visible, because contains musician, dispite contains food; 4) if both food , musician unchecked, li item disappears. my html is: <html> <head> </head> <body> <ul class="filtersection"> <li> <input checked="true" type="checkbox" value="food"/> <label>food</label> </li> <li> <input checked="true" type="checkbox" value="musician"/> <label>musician</label> </li> </ul> <ul id="itemstofilter"> <li data-type="food">food</li> <li data-type="musician">musician</li> <l...

Python 2.7.12- How to have the same length for a new string as well as letters? -

i've started learning python 2.7.12 , in first homework given string called str2, , i'm supposed create string same length previous one. in addition,i need check third letter (if it's upper need convert lower , opposite, if it's not letter, need change '%'). other characters of first string should copied second one. we given basic commends , nothing else can't solve it. please me! :) it sounds want copy of word need change 3rd character. that's problem because strings immutable in python can't change character. trick copy string can change. tmp = list(str2) then, need figure out how information character check it. turns out there several useful methods on string objects: >>> dir('some string') ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__get...

c++ - Can't retarget project in VS2015 -

Image
so i've decided learn c++. started downloading vs 2015 can't seem 'hello world' app work. on console application project named consoleapplication5 have code: #include <iostream> int main() { std::cout << "hello world!"; return 0; } and following error when pressing f5: "the windows sdk version 8.1 not found. install required version of windows sdk or change sdk version in project property pages or right-clicking solution , selecting "retarget solution"." the problem is, when try retarget solution, seems useless since nothing: any thoughts that? i using visual studio community 2015 v14.0.2543.01 update 3 - on windows 10 pro tl;dr - download , install sdk , retarget solution after that. you need have proper sdk installed. solution targeted use sdk 8.1. vs message suggests either install or, if want use another, installed sdk, retarget solution it . if don't have sdk installed, retargeting won...

python - Translating entire files with gdsCAD -

i using gdscad merge 3 gds files together. my imports : import os.path gdscad import * i have imported 3 files using gdsimport() function: file1 = gdsimport('gdsfile1.gds') file2 = gdsimport('gdsfile2.gds') file3 = gdsimport('gdsfile3.gds') my problem want translate , entire file new new location. not 1 shape in file. core.translate() function works groups , single elements. tried adding entire file group following: group1 = core.element(file1) but not work. any advice or different approach can maybe try? thanks

android - Changing the tab indicator colour without changing the accent colour -

Image
i have basic viewpager tabs shown below. nothing special it. contains tab indicator shows tab active (on web tab in image). default coloured theme's coloraccent . how can change tab indicator different colour without altering theme's accent colour? i have tried altering style.xml without success. <resources> <style name="apptheme" parent="theme.appcompat.light.darkactionbar"> <item name="colorprimary">@color/colorprimary</item> <item name="colorprimarydark">@color/colorprimarydark</item> <item name="coloraccent">@color/coloraccent</item> vvvvv <item name="android:tabwidgetstyle">@style/alternateaccentcustomization</item> ^^^^^ </style> <style name="apptheme.noactionbar"> <item name="windowactionbar">false</item> <item name="windownotitle">true</item>...

java - Retrofit 2.0 parsing complex api -

i using retrofit consume weather api, before had deal own backend tweak parse data nicely. time getting json looks : { "city": { "id": 838920, "name": "ledine", "coord": { "lon": 20.34833, "lat": 44.802502 }, "country": "rs", "population": 0, "sys": { "population": 0 } }, "cod": "200", "message": 0.2644, "cnt": 35, "list": [ { "dt": 1478271600, "main": { "temp": 281.58, "temp_min": 280.9, "temp_max": 281.58, "pressure": 1024.56, "sea_level": 1035.66, "grnd_level": 1024.56, "humidity": 90, "temp_kf": 0.68 }, "weather": [ { "id"...

object - How to successfully attach audio unit extensions to a host in Xcode without crashing the host? -

i'm trying start writing v3 audio unit extension macos, can't audio unit attach without crashing host. i downloaded apple's sample code https://developer.apple.com/library/content/samplecode/audiounitv3example i switched signing on team, built osxauv3host, built osxfilterdemoappextension target , tried both freshly built osxauv3host , garageband target app. the extension visible within both apps, when select it, host application crashes unexpectedly "libc++abi.dylib: terminating uncaught exception of type nsexception" the crash reporter log here: http://pastebin.com/hnp8c8uh my code similar , exact same thing. doing wrong or there larger issue how audio units handled in macos?

opencv - Fast method to retrieve contour mask from a binary mask in Python -

i want make realtime application, involves finding edges of binary mask. need fast, without gpu if possible, runs below 0.0005 secs per image, size (1000,1000). using following example of binary image ,with size (1000,1000). (code replicate:) import numpy np im=np.zeros((1000,1000),dtype=np.uint8) im[400:600,400:600]=255 image the first logical way things fast use opencv library: import cv2 timeit.timeit(lambda:cv2.laplacian(im,cv2.cv_8u),number=100)/100 0.0011617112159729003 which expected resulted in: laplacian i found way time consuming. after tried findcontours: def usingcontours(im): points=np.transpose(cv2.findcontours(im,cv2.retr_tree,cv2.chain_approx_none)[1][0]) tmp=np.zeros_like(im) tmp[tuple(points)]=255 return tmp timeit.timeit(lambda:usingcontours(im),number=100)/100 0.0009052801132202148 which gave same result above. better, still not like. moved on usage of numpy, approximate laplacian using gradient, last resort, although knew wor...

javascript - $apply already in progress without using $apply anywhere -

i have following javascript code: $scope.fav_details = function(id1,id2,bio) { document.getelementbyid(id2).style.display="none"; document.getelementbyid(id1).style.display="block"; $scope.getlegislatordetails(bio); document.getelementbyid(bio).click(); } the line throwing following error click event above. dont understand did not apply $apply anywhere in code still getting error. can me. getlegislatordetails function in above code has api call , stores data in scope variable. have following angular js error: angular.js:13642 error: [$rootscope:inprog] http://errors.angularjs.org/1.5.6/$rootscope/inprog?p0=%24apply @ error (native) @ https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:6:412 @ n (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:137:381) @ m.$apply (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:145:312) @ htmlbuttonelement.<anonymous> (https...

ruby on rails - RoR: Selecting Certain Posts Based on a Column Value -

i have been trying teach myself ror. have been working through tutorials on past few weeks, trying add of own functionality app go. feature trying implement seems quite simple, doubt solution safe , elegant be. so far, users can submit post site. model consists of image, title, category, , description. users can comment on given post (the comments contained in table). trying add dropdown menu on navigation bar allows users browse specific categories. in other words, index should display posts within category user has selected. while solution works, unhappy it. here code navigation bar: %button#menu1.btn.btn-primary.dropdown-toggle{"data-toggle" => "dropdown", :type => "button"} explore %span.caret %ul.dropdown-menu{"aria-labelledby" => "menu1", :role => "menu"} %li{:role => "presentation"} %a = link_to "all", posts_path(categories: "all") %li{...

multithreading - Use of lock keywork c# -

i working on c# coding exercise code: class program { static object sync = new object(); static void saferun() { lock (sync) { thread.sleep(1000); } } static void main(string[] args) { lock (sync) { saferun(); } console.write("safe"); } } } what printed? nothing, deadlock occurs. it not compile. "safe" print. i thought deadlock occur, when run code "safe" printed. so, can explain me why 3 correct , why 1 not correct? thank you! for deadlock occur need @ least 2 threads want access resources locked between them. example: you have 2 running thread , 2 list<t> . thread a locked list a . thread a want take value list b thread b locked list b . thread b want take value list a now both threads try resources locked between them.

javascript - Adding html to the DOM using jQuery -

i need attach string html dom using jquery: i have html string: var html = "<div id="inspectormenu" style="display: none;">"+ "<label id="showinspectorname" style="padding: 13px 09px; color:white"></label>"+ "<ul id="" class="nav pull-left">"+ "<li style="display: inline-block;text-align: center; max-height:35px;"><a class="navbar-brand" ui-sref="sites.list" style="padding: 11px 09px;" title="אתרים"><i class="glyphicon glyphicon-tree-conifer"></i></a></li>"+ "<li style="display: inline-block;text-align: center;max-height:35px;"><a class="navbar-brand" ui-sref="sitesdamages.siteslist" style="padding: 11px 09px;" title="אירועים"><i class="gl...

reactjs - GraphQL and Meteor.js data tracking -

i wondering if there's way use benefits of meteor.js tracker graphql data layer react view. auto-updating view, updating props when content changes in database. know there mutations, in fetching again data once has been called? it depends on context of application, needs refetch query after mutation affect change on ui. you need ask questions : do need real time data synchronization on several users screen do need performant web application when real time data tracking not worry. if performance constraint i'd suggest go 100% graphql solution, if need user collaboration easiest way go meteor tracked data, costs lot in memory.

While and if statement in php with mysql -

i have been stuck problem awhile now. i'm sure answer on find able on google have been unable find words search last resort here. in advanced! i have php code: if(mysqli_num_rows($query) > 0) { while($row = mysqli_fetch_array($query)) { if ($row['status'] == "opened") { $test = "1"; } else { $test = "0"; } } } echo $test; the problem occurs when there multiple entries in database , 1 of entries not have status = "opened" therefore $test returns "0". trying accomplish if of entries have status = "opened", $test return "1". once again in advance help! it might better directly select data need database instead of filtering out php. select id, message, etc tickets status = 'opened' // if fetches data, have open tickets , have directly access data of open tickets. select count(*) total tickets status = 'opened' /...

html - Flexbox bug in Internet Explorer <= Edge -

my problem regarding flexbox layout. check demo modern browsers , internet explorer. code snippet: .features-section { display: flex; flex-direction: row; justify-content: space-between; width: 100%; -webkit-flex-flow: row wrap; } .features-section .custom-col-6 { padding: 1em; margin: 0; align-self: center; width: 50%; box-sizing: border-box; } .features-section .not-for-mobile { display: block; } .features-section .not-for-desktop { display: none; } .features-section .feature-image { height: 490px; background-position: center center; background-repeat: no-repeat; background-size: cover; } .features-section .feature-image-1 { background-image: url(https://images.unsplash.com/photo-1430806746135-4c9775bfea07?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&s=f98a2e705cc92fdba353e0d973176aff); } .features-section .feature-image-2 { background-image: url(https://images.unsplash.com/phot...

sprite kit - How can I get my SKNodes in different file from the gamescene swift -

i couldn't find on having sknodes in seperate files gamescene.swift. tried writing in new class swift file did not seem work. had make function did not know how call in gamescene. let testlabel = sklabelnode(fontnamed: "applesdgothicneo-medium") testlabel.text = "test" testlabel.position = cgpoint(x: self.frame.midx, y: 300) testlabel.fontsize = 90 testlabel.color = skcolor.blue testlabel.horizontalalignmentmode = sklabelhorizontalalignmentmode.center i'm trying make in swift file , use testlabel in gamescene. thanks in advance. rather creating new file, consider creating property label inside gamescene.swift file. lets add label scene calling self.testlabel . class gamescene: skscene { lazy var testlabel: sklabelnode! = { let testlabel = sklabelnode(fontnamed: "applesdgothicneo-medium") testlabel.text = "test" testlabel.position = cgpoint(x: self.frame.midx, y: 300) ...

c++ - Android source code compilation error: impossible constraint in 'asm' -

for project must use inline assembly instructions such rdtsc calculate execution time of android 4.3 c++ instruction in stack . found similar problem in stackoverflow such 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 non of them solve problem have. i used following code: {unsigned a, d;asm volatile("rdtsc" : "=a" (a), "=d" (d)); t0 = ((unsigned long)a) | (((unsigned long)d) << 32);} //the c++ statement measure execution time {unsigned a, d;asm volatile("rdtsc" : "=a" (a), "=d" (d)); t1 = ((unsigned long)a) | (((unsigned long)d) << 32);} time = (t1-t0)/2-20; but i'm getting error message: error: impossible constraint in 'asm' my build environment are: ubuntu 14.04.5 lts android 4.3 gcc 4.8.5 g++ 4.8.5 target: x86_64-linux-gnu i have tried above code in standalone c program (in same environment) , working fine no problem once embed above code in android source code, error message. ...

reactjs - react-router - separate files -

so have following app.js import react 'react' import { render } 'react-dom' import { browserrouter, match, miss, link } 'react-router' //import jobs './modules/jobs' //import job './modules/job' const app = () => ( <browserrouter> <div> <ul> <li><link to="/">main</link></li> <li><link to="/jobs">jobs</link></li> </ul> <hr/> <match pattern="/" component={main} /> <match pattern="/jobs" component={jobs} /> </div> </browserrouter> ) const jobs = ({ pathname }) => ( <div> <h2>jobs</h2> <ul> <li><link to={`${pathname}/job1`}>job1</link></li> <li><link to={`${pathname}/job2`}>job2</link></li> <li><link to={`${pathname}/job3`}>jo...

json - array indexing in N1QL -

i ran query: select z data x unnest x.m2 y unnest y.country z; on json document: { "data": { "country": [ { "name": "canada" }, { "name": "greece" } ] } } and got result: [ { "z": { "name": "canada" } }, { "z": { "name": "greece" } } ] i want select first country name (canada) , tried doing this: select z[0] data x unnest x.m2 y unnest y.country z; but return empty results. idea how it? ignoring m2, do: select z data x unnest x.data y unnest y.country z limit 1;

ssl - Xamarin Android HttpClient Error when use from a Class -

i have following code errors out when going site has ssl. (error: securechannelfailure (the authentication or decryption has failed.) ssl cert valid. when httpclient code called directly there not issue. wrong code? uri uri =new uri("https://jsonplaceholder.typicode.com/posts/1"); using (httpclient httpclient = new httpclientclass()) { var tt = await httpclient.getasync(uri); string tx = await tt.content.readasstringasync(); log.info(tag, tx); } public class httpclientclass : httpclient { private httpclient _httpclient = null; private httpclienthandler messagehandler = new xamarin.android.net.androidclienthandler(); public httpclientclass() { _httpclient = new httpclient(messagehandler); } } code no problem uri uri =new uri("https://jsonplaceholder.typicode.com/posts/1"); using (httpclient httpclient = new httpclient()) { var tt = await httpclient.getasync(uri); ...

c++ - Random points generation in openGL -

i want draw 100 points on screen using opengl. means there 100 gl_points randomly located on screen each time run program. there 1 point remains on screen , position given. however, random points appeared short period of time , disappear. don't know did miss make work. below code #include <stdlib.h> #include <gl/freeglut.h> #include <math.h> glfloat cameraposition[] = { 0.0, 0.2, 1.0 }; /* random star position */ glfloat starx, stary, starz; glint starnum = 0; void myidle(void){ starnum += 1; /* generate random number between 1 , 4. */ starx = 1.0 + static_cast <float> (rand()) / (static_cast <float> (rand_max / 3.0)); stary = 1.0 + static_cast <float> (rand()) / (static_cast <float> (rand_max / 3.0)); starz = 1.0 + static_cast <float> (rand()) / (static_cast <float> (rand_max / 3.0)); /* force opengl redraw change */ glutpostredisplay(); } // draw single point void stars(glfloat x, glfloat y, gl...

Javascript: Cant get a round number -

i tried cant seem final result round number 2 decimal digits. it's standard deviation thank in advance, here code. function round(number) { var final = math.round(number * 100) / 100; return final; } function stdev(arr) { var avg = average(arr); var squarediff = arr.map(function(arr) { var diff = arr - avg; var sqrdiff = diff * diff; return sqrdiff; }); var avgsquarediff = average(squarediff); var stddev = math.sqrt(avgsquarediff); return stddev; function average(data) { var sum = data.reduce(function(sum, arr) { return sum + arr; }, 0); return round(sum / data.length); } } you round value when return in average . however, in stdev , calculate square root of rounded value. that operation return number lots of decimals, , return directly without rounding again. most need function round(number) { var final = math.round(number * 100) / 100; return final; } function average(data) { var sum = data.reduce(fu...

algorithm - Why doesn't the knight cover all the table? -

i want knight start @ (1,1) , try move on table. code: canmove :: (int -> int) -> (int -> int) -> [(int,int)] -> bool canmove (x) (y) list | (x (fst lastmove),y (snd lastmove)) `elem` list = false | newx> 8 || newy> 8 || newx<=0 || newy<=0 = false | otherwise = true lastmove = last list newx = x (fst lastmove) newy = y (snd lastmove) move :: [(int, int)] -> [( int, int)] move list | length list == 64 = list | canmove (+1) (+2) list = move (list ++ [(x+1,y+2)]) | canmove (+2) (+1) list = move (list ++ [(x+2,y+1)]) | canmove (subtract 1) (+2) list = move (list ++ [(x-1,y+2)]) | canmove (subtract 2) (+1) list = move (list ++ [(x-2,y+1)]) | canmove (subtract 1) (subtract 2) list = move (list ++ [(x-1,y-2)]) | canmove (subtract 2) (subtract 1) list = move (list ++ [(x-2,y-1)]) | canmove (+1) (subtract 2) list = move (list ++ [(x+1,y-2)]) | canmove (+2) (subtract 1) list ...

java - Are my loops preventing me from getting the expected output? -

Image
my goal determine, pair of integers, whether second integer multiple of first. code follows: import java.util.scanner; public class multiples { public static void main(string [] args) { boolean run = true; while(run) { scanner input = new scanner(system.in); system.out.print("enter 1 number:"); int num1 = input.nextint(); system.out.print("enter second number:"); int num2 = input.nextint(); boolean result = ismultiple(num1, num2); if(result) { system.out.println(num2 + " multiple of " + num1); } else { system.out.println(num2 + " not multiple of " + num1); } system.out.print("do want enter pair(y/n)?"); run = yesorno(input.next()); } } public static boole...

c# - Unity 5.4.2 - Scale and position instantiated UI elements -

so i've been working on project class i'm in , have run pickle can't seem resolve. have asked instructor , confused was. right i've been trying set simple ui displaying list of buttons select level load. @ runtime code creates appropriate buttons , such, , places them within scrollview's content object. simple enough, right? well, as can see position , right wrong, 800 units . the canvas set screen space - overlay , canvas scaler set scale screen size , i'm guessing problem. had problem of position , scale being more off (depending on screen size), "fixed" manually setting transform's position , localscale. i have had no luck finding solution this, googling, i'd appreciative if me , explain me problem is. here code executes each of levels. it's of course messy because i've been trying as figure out problem is. level thislevel = levelmanager.levellist [i]; gameobject levelbutton = (gameobject)instantiate ...

apache spark - Load XML string from Column in PySpark -

i have json file in 1 of columns xml string. i tried extracting field , writing file in first step , reading file in next step. each row has xml header tag. resulting file not valid xml file. how can use pyspark xml parser ('com.databricks.spark.xml') read string , parse out values? the following doesn't work: tr = spark.read.json( "my-file-path") trans_xml = sqlcontext.read.format('com.databricks.spark.xml').options(rowtag='book').load(tr.select("trans_xml")) thanks, ram. try hive xpath udfs ( languagemanual xpathudf ): >>> pyspark.sql.functions import expr >>> df.select(expr("xpath({0}, '{1}')".format(column_name, xpath_expression))) or python udf: >>> pyspark.sql.types import * >>> pyspark.sql.functions import udf >>> import xml.etree.elementtree et >>> schema = ... # define schema >>> def parse(s): ... root = et.fromstring...

python - Find Compound Words in List of Words using Trie -

given list of words, trying figure out how find words in list made of other words in list. example, if list ["race", "racecar", "car"] , want return ["racecar"] . here general thought process. understand using trie sort of problem. each word, can find of prefixes (that words in list) using trie. each prefix, can check see if word's suffix made of 1 or more words in trie. however, having hard time implementing this. have been able implement trie , and function prefixes of word. stuck on implementing compound word detection. you present trie nodes defaultdict objects have been extended contain boolean flag marking if prefix word. have 2 pass processing on first round add words trie , on second round check each word if it's combination or not: from collections import defaultdict class node(defaultdict): def __init__(self): super().__init__(node) self.terminal = false class trie(): def __init__(self...

php - List data from many to many table -

i'm trying list data "date" table sorted category , i'm stuck. more helpful. how can "select date" list url? sql structure: category -cat_id (int)=>pk -name date -id (int)=>pk -url video_cat -id (int) => fk date.id -cat_id (int) => fk category.cat_id php: <?php $sql = "select * category"; $result = mysql_query($sql); if (mysql_num_rows($result) > 0) { while ($row = mysql_fetch_assoc($result)) { if (!empty($_post['category']) , $_post['category'] == $row["cat_id"]) $select = "selected='selected'"; else $select = ''; echo '<option value="' . $row["cat_id"] . '" ' . $select . ' >' . $row["name"] . '</option>'; } } ?> <?php if (!empty($_post['category'])) { $category_id = $_post['category']; $sql = "...

authentication - How to crawl Factiva data with python Scrapy? -

Image
i'm working on data factiva, in python 3.5.2. , have use school login see data. i have followed post try create login spider however, got error : this code: # test login spider import scrapy scrapy.selector import htmlxpathselector scrapy.http import request login_url = "https://login.proxy.lib.sfu.ca/login?qurl=https%3a%2f%2fglobal.factiva.com%2fen%2fsess%2flogin.asp%3fxsid%3ds002sbj1svr2svo5des5depotavndaoodzymhn0yqyvmq382rbrqufbqufbqufbqufbqufbqufbqufbqufbqufbqufbqufbqqaa" user_name = b"[my_user_name]" pswd = b"[my_password]" response_page = "https://global-factiva-com.proxy.lib.sfu.ca/hp/printsavews.aspx?pp=save&hc=all" class myspider(scrapy.spider): name = 'myspider' def start_requests(self): return [scrapy.formrequest(login_url, formdata={'user': user_name, 'pass': pswd}, callback=self.logged_in)] def logged_in...

swift - NSDecimalNumber.adding from NSManagedObjects hitting unrecognized selector issue -

first, let me thank in community in advance in getting me out of jam. my app hits runtime error, , i've isolated line causing error. when attempt add 2 nsdecimalnumber variables use .adding method, receive "unrecognized selector sent instance" error: terminating app due uncaught exception 'nsinvalidargumentexception', reason: '-[__nscfnumber decimalnumberbyadding:]: unrecognized selector sent instance 0x608002c361a0' i've created dummy nsdecimalnumber variables try , debug issue, , seem work fine when adding. however, when working nsmanagedobject variables ( result , newtransaction ) have nsdecimalnumber variables, run error. below code causing these issues: //testing dummy variables let a1 = nsdecimalnumber(decimal: 5.2) let a2 = nsdecimalnumber(decimal: 10.8) print ("a1: \(a1), a2: \(a2)") //a1: 5.2, a2: 10.8 let a3 = a1.adding(a2) print ("a3: \(a3)") //a3: 16 //great, above...

android - How to make views visible per button click -

i developing app calculation. consists of horizontal linearlayout , each layout has 2 edit text , and spinner. want make in such way user can add layouts button click when needs add more details. in xml set android:visibility="gone" , in java set onclick method make "gone" linear layout view.visible . worked makes linear layouts appear once click + button. want them appear 1 after other (one appear , others remain "gone" until click button again) you can use layout inflater. create resource file in add layout , widgets required e.g item_resource.xml <?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > <linearlayout android:id="@+id/linear" android:layout_width="wrap_content...