Posts

Showing posts from July, 2014

html - How can I eliminate the bad anti-aliasing or blending on the left side of my SVG layers? -

Image
sorry garish colors, shows bad blending combination. on left side of inner circle, there dark line blue meets red. on right half of inner circle, there not. happening in chrome, ff, , ie11. any idea why? <svg viewbox="0 0 500 500" width="500" height="500"> <circle fill="red" cx="250" cy="215" r="165"/> <circle fill="#2994ff" cx="250" cy="215" r="100"/> </svg> picture version: what think seeing not real. optical illusion caused contrast change between 2 colours. dark light , light dark. the layout of subpixels on monitor may contributing - i'm not sure on that. if create magnified version of 2 edges next 1 another, should see strong dark , light borders not there.

javascript - D3 Update Graph -

really stucked on issue days. trying update d3 graph show how long takes run function on calculator. info get, show time taken , display on graph drew. issue here can't graph update. codes graph: var margin = {top: 20, right: 20, bottom: 30, left: 50}, width = 400 - margin.left - margin.right, height = 300 - margin.top - margin.bottom; var x = d3.scale.linear() .range([0, width]) var y = d3.scale.linear() .range([height, 0]); var xaxis = d3.svg.axis() .scale(x) .orient("bottom"); var yaxis = d3.svg.axis() .scale(y) .orient("left"); var line = d3.svg.line() .x(function(d) { return x(d.date); }) .y(function(d) { return y(d.close); }); var svg = d3.select("body").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append(

c# - DataContext in Style is not available on the DataTrigger -

i have userdefined control call segmentview (derived contentcontrol). additionally have segmentmodel implements inotifypropertychanged. segmentmodel has property called statuscontroller , there statuscontrollerviewmodel. for of views create view models automatically in xaml , attach models. viewmodel automatically set datacontext of view. it works well, except following. modeltoviewmodelconverter creates viewmodel, attaches model , sets viewmodel datacontext of control. how works several other things. additionally in style, have datatrigger changes opacity of dockpanel. datacontext of dockpanel indeed set instance of statuscontrollerviewmodel, but, binding in datatrigger not found. btw: statuscontroller property of larger model, not shown here brevity. should correct shown datacontext set correctly, statuscontrollerviewmodel. binding tells different story. seems doesn't "see" datacontext of dockpanel, sees datacontext of levels above. the model property of sta

mysql - SQL Query Joins not working properly -

Image
for project needed create db small olympics. er diagram shown... link better picture: https://i.imgur.com/xgfurwo.png?1 i need create query includes competitors competing in more 1 event (that's 2 competitors) , list name, event, venue, , result. the query below works should producing 70 (# of competitors) records count @ 2 competitors competing in 2 events... select c.firstname, c.lastname, count(r.competitorid) competitor c left outer join ( registration r left outer join event e on r.eventid = e.eventid ) on r.competitorid = c.competitorid group c.firstname, c.lastname order c.firstname; ----------------------------------------- norris holmwood 1 octavio martinez 1 orfeo silva 2 etc... after including event name in query produces 72 results competitors competing in 2 events listed twice count() 1 everything. select c.firstname, c.lastname, e.eventname, count(r.competitorid) competitor c left outer join ( registration r left outer

javascript - jQuery if/else statement to change css on click -

$('#submitbtn').on("click", function() { $('.message-box').val(); var message = $(".message-box").val(); $('#visible-comment').html(message); $('.message-box').hide(); return false; }); i want above code in if/else condition if value of .message-box empty string change border color of .message-box red. could please guide me in right direction? i've tried following, changes border red, doesn't fire rest of code. $('#submitbtn').on("click", function() { if ($(".message-box").val("")) { $(".message-box").css("border","2px solid red"); } else { $('.message-box').val(); var message = $(".message-box").val(); $('#visible-comment').html(message); $('.message-box').hide(); return false; } }); sample here : https://jsfiddle.net/wf69c7uu/2/ the idea check conditi

ios - Find path for local video in Xcode Project -

i need play locally stored videos in ios app. the videos located in directory: app/resources/videos/ when try path with: nsbundle.mainbundle().pathforresource("myfile", oftype: "mp4", indirectory: "app/resources/videos/") i nil. advice? problem solved: error didn't add target-membership videos.

java - Redirect interface method calls -

i have interface1 , 2 implementations of it, classa , classb . want redirect method calls classa classb. i'm doing this: class classa implements interface1{ method1(){ b.method1(); } method2(){ b.method2(); } method3(){ b.method3(); } //and on... } is there more easy way this? have considered using abstract class instead of interface? can put common implementations in abstract class, , in classa , classb implement methods 2 classes differ. abstract class abstract { void method1() { //do stuff... } abstract void method2(); } class classa extends abstract { @override void method2() { // something... } } class classb extends abstract { @override void method2() { // else... } }

css - Fixed position div causes page to be truncated in less common mobile browsers -

Image
i know there many similar issues, different have encountered before, thought describe bug here, , offer solution - , ask if else has better solution or can shed light on cause of weird issue. the bug: in page has div in position:fixed style, in less common mobile browsers, e.g. star safari, du browser, tint browser - page loads expected, , div fixed expected, if page height greater 1500px, bottom of page truncated - complete white curtain. can still scroll bottom, it's white, 0 content. this bug not happen in more common browsers chrome, firefox, opera, safari etc.. here's screen shot phone (htc m8 - tint browser) - reproduced bug on samsung s5. there many reasons might want fixed div, in case menu button can follow viewport, visitor doesn't have scroll top menu. i have posted semi-solution bellow, not mark correct week, else can offer better solution. tim the reason call "semi-solution" 2 reasons: 1) not keep div fixed, elegantly m

WebView based Android YouTube Player -

Image
i need add video playback capabilities android app. i've started integrating android youtube player sdk . works sdk has limitation won't work in case: users need run version 4.2.16 of mobile youtube app (or higher) use api. same time ios there no native sdk provided google there great alternative webview based player works great, without limitations , need. here have 2 questions: is possible force native android youtube sdk gracefully fallback webview based experience if no youtube app installed? is there webview base android youtube player sdk? update: wasn't able locate existing implementation (official or 3d party) reimplemented whatever implemented @ ios version of player helper . webview uses ifame , js youtube api instantiate player , control it. unfortunately wasn't able start full screen using control yet

Google Image Search API (Deprecated) -

as stated on website google has stopped maintaining image search api , deprecated. 2011, of policy api working 3 more years before shut down. way more 3 years , api working. have information if api continue work , shutting down anytime soon? also api have limit request per day or that. have read restriction 64 max results per request. the google image search api has been officially deprecated of may 26, 2011. continue work per our deprecation policy, number of requests may make per day may limited. encourage use custom search api , supports image search. https://developers.google.com/image-search/v1/devguide

php - Cron sessionclean errors: find: `/proc/xxxxx/fd': No such file or directory -

after php upgrade started following cron errors several times day: find: `/proc/xxxxx/fd': no such file or directory it comes php sessionclean cron job: [ -x /usr/lib/php5/sessionclean ] && /usr/lib/php5/sessionclean any ideas? there debian bug reported (and fixed ) this. it mentions release stable: in next security upload, e.g. 2 weeks after 5.6.23 released, unless else critical shows up. 5.6.23 out, expect within next 2 weeks. the fix there add if [ -d "/proc/$pid/fd" ]; before the find "/proc/$pid/fd" command.

security - How do I create an automation program that can run NMAP on my network weekly? -

so know nothing programming whatsoever. i'm still open minded , want know steps create automation program run nmap on machine weekly , having send results e-mail without me touching software. is easy enough me research programming codes , create automation program, or complex? run cron job on linux machine. # crontab -l this start editor, add there mailto="you@example.com" 10 15 * * 0 nmap (command parameters there) your nmap run every sunday @ 15:10.

python - Prompting the user for correct input - tic tac toe game -

i'm working on program simulates tic-tac-toe game between 2 players. program want far, except part ask players input. want program check whether (3 x 3) grid contains mark (for example, 'x' or 'o'), , keep prompting same player correct input before switching turns. here have far: board = [ 0, 1, 2, 3, 4, 5, 6, 7, 8 ] def main(): print_instructions() start = str(input("your game begin. press 'q' if want quit, or 'k' proceed: ")) while start != "q": get_input1() get_input2() def display_board(board): print(board[0], "|" , board[1] , "|" , board[2]) print("----------") print(board[3] , "|" , board[4] , "|" , board[5]) print("----------") print(board[6] , "|" , board[7] , "|" , board[8]) def print_instructions(): print("please use following cell numbers mak

lua - BackBtn does not cancel timer from previous scene -

i can't find correct code cancel timers previous scenes. have tried these combinations in various positions: if "tap" == true timer.cancel() end timer.cancel(event.source) timer.cancel = true timer.stop if "tap" == true timer.cancel = true timer.stop() end ...and on. can point me correct code , place it? thanks. these scenes in question: -- info.lua local composer = require "composer" local scene = composer.newscene() function scene:create(event) local scenegroup = self.view local widget = require "widget" local scene1btn local function onscene1btnrelease() composer.gotoscene("scene1", "fade", 40) return true end scene1btn = widget.newbutton{ defaultfile = "images/reviewtwo.png", width= 480, height= 320, onrelease = onscene1btnrelease

string - php Greater Than Comparison Not Working -

i'm looking highlight rows when child 12 years , older rows highlighting. in nutshell, here data. i'm getting birth date here: // getting birth date string $birthdatein=strtotime($birthdate); $newdate=date('y-m-d',$birthdatein); i'm getting age of child of today here: // getting date difference between birthdate , today $birthdatein = new datetime(''.$newdate.''); $todaydatein = new datetime('today'); $age = $birthdatein->diff($todaydatein); i'm looping through mysql query results, , displaying age in format: echo "<td>" . $age->format('%y years %m months') ."</td>"; then, code sets age of child in 2020 (this works): //get age dec 2020 $setdec2020 = new datetime('2020-12-31'); $ageondec2020=$birthdatein->diff($setdec2020); now, here problem. i'm using code

asp.net - How to read Elastic Beanstalk Environment Properties in .net? -

Image
how can read environment properties aws elastic beanstalk application found here: configuration > software configuration > environment properties none of following approaches work: configurationmanager.appsettings["myserviceurl"] configurationmanager.appsettings["aws:elasticbeanstalk:application:environment.myserviceurl"] environment.getenvironmentvariable("myserviceurl") environment.getenvironmentvariable("aws:elasticbeanstalk:application:environment.myserviceurl") the 'fully qualified' name attempt comes aws eb documentation . any ideas? in .ebextensions/myoptions.config file: option_settings: - option_name: myserviceurl value: change me this add "myserviceurl" option in eb environment properties section (as you're seeing already). when deployed, add following web.config file: <appsettings> <add key="myserviceurl" value="change me" /> </appse

c++ - usr/bin/ld: cannot find -lexpat -

i trying compile software scons error saying, usr/bin/ld: cannot find -lexpat can please tell me how can fix it? thank much. here's full error message: scons: reading sconscript files ... we're on 64-bit machine use 32-bit libs & executables on 64 bit system osname = linux-x86_64-32 no installation being done scons: done reading sconscript files. scons: building targets ... g++ -o src/examples/.linux-x86_64-32/dana -m32 src/examples/.linux-x86_64-32/dana.o -lsrc/libsrc/.linux-x86_64-32 -lsrc/libsrc -lsrc/libsrc++/.linux-x86_64-32 -lsrc/libsrc++ -levioxx -levio -lpthread -lexpat -lz -ldl -lm /usr/bin/ld: cannot find -lexpat collect2: error: ld returned 1 exit status scons: *** [src/examples/.linux-x86_64-32/dana] error 1 scons: building terminated because of errors.

synchronization - Android Wearable: how to get a current variable using DataApi? -

this event-based code wearable.dataapi.addlistener(googleapiclient, new dataapi.datalistener() { @override public void ondatachanged(dataeventbuffer dataevents) { log.i(tag, "on data changed " + dataevents.tostring()); (dataevent event : dataevents) { dataitem item = event.getdataitem(); string path = item.geturi().getpath(); if (path.equals(path_map)) { datamap datamap = datamapitem.fromdataitem(item).getdatamap(); string datavalue = datamap.getstring(key_data); } } } }).setresultcallback(new resultcallbacks<status>() { @override public void onsuccess(@nonnull status status) { log.i(tag, "success"); } @override public void onfailure(@nonnull status status) { log.i(tag, "failure"); } }); how read d

d - Templated Multi-Dimensional Arrays -

i'm trying experiment templates , tried implement templated arrays, can declared like: array!(float, 3, 2, 1) myarray; i've browsed through several implementations of problem in c++ can't seem convert d have little experience language (with d). anyways these stuff tried, unfortunately none of them worked: 1. compile-time functions - generate code of format "datatype[d0][d1]...[dn] identifier" import std.conv; static string generatearray(d...)(string type, string identifier, d dimensions) { string result = type; for(int = 0; < dimensions.length; i++) { result ~= "[" ~ to!(string)(dimensions[i]) ~ "]"; } result ~= " " ~ identifier ~ ";"; return result; } int main(string[] args) { enum deb = generatearray("float", "data", 3, 2, 1); pragma(msg, deb); return 0; } which can wrap simple array class class array(t, d...) { mixin(generate

javascript - Create/manage multidimensional array using jQuery -

i building chat application using socket.io. i need create array manage users connected each chat room. to start need store chat room name, , in chat room each user , status. chat1 nickname: user1 status: admin nickname: user2 status: none nickname: user3 status: none i need sort nicknames in alphabetical order when created or when user added or deleted. possible? what you've described isn't multidimensional array, it's array of objects or maps. assuming objects: chat1 = [ { nickname: 'ethelred', status: 'admin'}, { nickname: 'alfred', status: 'none' }, { nickname: 'canute', status: 'none' } ] // that's needed simple sort: chat1.sort((a,b) => a.nickname > b.nickname) this sort , give [{nickname: 'alfred', status: 'none' }, {nickname: 'canute', status: 'none' }, { nickname: 'eth

php - Combine two arrays into keys and values in a resulting array? -

this question has answer here: php values of 1 array key of array 3 answers i have 2 arrays, 1 keys , other values: key_array = ['key1','key2','key3'] values_array = ['val1','val2','val3'] how iterate through them (their size vary) obtain this: array('key1' => 'val1', 'key2' => 'val2', 'key3' => 'val3') use array_combine() : $a = array('green', 'red', 'yellow'); $b = array('avocado', 'apple', 'banana'); $c = array_combine($a, $b); print_r($c); ?> array ( [green] => avocado [red] => apple [yellow] => banana )

node.js - How to create anonymized email adress -

i need implement anonymized email adress feature in website, airbnb , homeaway do. they create anonymous address each conversation between renter , landlord. for example, homeaway has 09834b6-5apf-4731-3932-8ef5232dsd742a@messages.homeaway.com and airbnb has 541kfgry7hnh343gnjvv23423t08k4g@reply.airbnb.com (the ids leading @ have been altered). airbnb reference: http://blog.airbnb.com/introducing-anonymized-email-addresses-airbnb/ i'm using node.js , sendgrid sending emails. process behind should using? the homeaway esample looks uuid string. check on how generate uuid strings. how store uuid alphanumeric in nodejs

Why swapping is not a good idea in zookeeper and kafka? -

i have read instructions on do not use swap both on zookeeper , kafka. know kafka depends on pagecaching keep parts of sequential logs cached in-memory written disk. but can not understand how swapping can harm zk , kafka. swapping may cause performance stability problems; in example, don't want linux kernel "mistakenly/accidentally" swap kafka or zookeeper processes. also, swapping may particularly bad jvm processes such kafka , zookeeper, quoting: [the] jvm won't full gc cycle until has run out of allowed heap, of heap occupied not-yet-collected garbage. since these pages aren't being touched (because garbage , unreferenced), os happily swaps them out. when gc runs, have ridiculous swap storm, pulling in these pages discover in fact filled garbage , should discarded; can make gc cycle take many minutes! hence recommendation disable swapping setting vm.swappiness 0 , though operating systems rhel 6.5 should 1 (because semantics of

c++11 - Assembler Messages: no such instruction when Compiling C++ -

i attempting compile c++ code using gcc/5.3 on scientific linux release 6.7. keep getting following errors whenever run makefile though: /tmp/ccjzqied.s: assembler messages: /tmp/ccjzqied.s:768: error: no such instruction: `shlx %rax,%rdx,%rdx' /tmp/ccjzqied.s:1067: error: no such instruction: `shlx %rax,%rdx,%rdx' /tmp/ccjzqied.s: assembler messages: /tmp/ccjzqied.s:6229: error: no such instruction: `mulx %r10,%rcx,%rbx' /tmp/ccjzqied.s:6248: error: no such instruction: `mulx %r13,%rcx,%rbx' /tmp/ccjzqied.s:7109: error: no such instruction: `mulx %r10,%rcx,%rbx' /tmp/ccjzqied.s:7128: error: no such instruction: `mulx %r13,%rcx,%rbx' i've attmpted follow advice question no change output: compile errors assembler messages my compiler options currently: cxxflags = -g -wall -o0 -pg -std=c++11 does have idea causing this? this means gcc outputting instruction assembler doesn't support. either that's coming inline asm in sou

javascript - How to check whether object is empty in handlebars if statement? -

in handlebars need check if object empty , if isn't need run loop grab content object. below code , link codepen. imagine quite simple nothing seems work. have thought handlebars #if statement see empty object undefined or 0 , condition unfulfilled. <div class="temp"></div> <script id="temp" type="x-handlebars-template"> {{#if tabs}} <p>true</p> {{/if}} </script> var template = handlebars.compile($("#temp").html()); var tabs = {}; var context = { tabs: tabs } $('.temp').html(template(context)); http://codepen.io/matt3224/pen/gakykv?editors=101 you can use built in handlebars each helper accomplish you're looking for, , can conditionally render empty object: var template = handlebars.compile($("#temp").html()); var tabs = {}, test = {a: "resources", b: "contact"}; var context = { tabs: tabs, test: test

javascript - How to know if the 7th radio button is selected without knowing name or id -

i have product page dynamically creates item options. know if 7th option selected, wont know "name" or "id" of radio button because generated automatically. function teasamplecheck() { if(document.form1.radio1[7].checked == true) { alert("you have selected sample"); } else { // nothing } } } }); <!--start: radio-format--> <div class="radio-format" itemprop="offers" itemscope itemtype="http://schema.org/offer"> <input type="radio" name="[oname]" id="radio-[value]" value="[value]" onclick="teasamplecheck();validatevalues(document.add,1);updateprice();" [selected]> [feature] <div class="clear"></div> </div> <!--end: radio-format--> so how @ set of radio buttons , know 7th 1 selected? the use of jquery .eq() may way. function teasamplecheck() { if( $("

jquery - List of valid Backbone.js DOM events -

Image
i'm reading backbone.js code example , thought of event listener breakpoints(image include) in chrome dev tools. right event listener values in chrome dev tools ones can write in events property of code? for example: events: { 'dblclick label': 'edit', 'keypress .edit': 'updateonenter', 'blur .edit': 'close', 'domactivate .someclass': 'activatedom', // saw in dom mutation 'webgl error fired .anotherclass': 'firewebglerror' // saw in webgl } if not, can find list of valid events can put? backbone uses jquery event delegation when jquery available, else 1 of few similar libraries (which haven't used) can used in place of jquery. should supporting events browser & dom manipulation library of choice supports. if chrome supports specific event, should able listen it, , code work in chrome not in other browsers expected. as far know, backbone doesn't limit dom e

mysql - c# MySqlCommand.Parameters.AddWithValue, parameters to express a table, resulted command have a single quote added -

my problem 2 undesired single quote appear in command when use addwithvalue. how call function: string sqltablename = "the_table_i_want"; datatable mydatatable = sqlcom.selectlastvalueintab(sqltablename); my function; public static datatable selectlastvalueintab(string tablename) { using (mysqlconnection con = new mysqlconnection(connstr)) { using (mysqlcommand mycommand = new mysqlcommand("select * @tabname order id desc limit 1", con)) { mycommand.parameters.addwithvalue("@tabname", tablename); try { con.open(); mysqldatareader testreader = mycommand.executereader(); the resulted command : "select * 'the_table_i_want' order id desc limit 1" and suppose : "select * the_table_i_want order id desc limit 1" it cause program crash beacause have: a syntax error near ''the_t

angular - Angular2 Observable Filter -

i'd filter observable, getting unexpected results. i using following import statements: import {observable} 'rxjs/observable'; import 'rxjs/add/observable/of'; this example returns nothing: observable.of([0, 1, 2, 3, 4, 5]) .filter((x: any) => x % 2 === 0) .subscribe(data => console.log(data)); this example returns entire result set [0,1,2,3,4,5]: observable.of([0, 1, 2, 3, 4, 5]) .filter((x: number[], idx) => x[idx] % 2 === 0) .subscribe(data => console.log(data)); does see syntax errors and/or missing? thank you! you need use from if want pass values iterable (array in current case) import 'rxjs/add/observable/from'; observable.from([0, 1, 2, 3, 4, 5]) .filter((x: any) => x % 2 === 0) .subscribe(data => console.log(data)); or if want stick of pass values arguments observable.of(0, 1, 2, 3, 4, 5) .filter((x: any) => x % 2 === 0) .subscribe(data => console.log(data));

phpstorm - PSR2 code style and PHP Code Sniffer doesn't agreed? -

Image
i have setup editor code style setup editor > code style > php predefined style >psr1/psr2 . have php code sniffer , php mess detector installed , configured well. time format code using ctrl+alt+l following issue: why that? original code looks (i think not helpful anyway here it's): public function mytestfunction() { $is_valid = true; if ($this->manual_value && !$this->_inputvalidator->isvalidstring( $this->manual_value, 1, 2, regex::string ) ) { $is_valid = false; } return $is_valid; } psr2 doesn't multi-line if condition needs indented, phpstorm putting in 1 indent because lines inside if condition , 1 additional indent because lines inside multi-line function call. psr2 does multi-line function calls must indented, says must indented once . documented here: https://github.com/php-fig/fig-standards/blob/master/accepted/psr-2-coding-style-

Swift JSON Parsing - Unable to access field/returns nil -

i'm using google's geolocator api map stuff automatically. returns json string in request, i'm having lot of difficulty parsing it. i've tried things freddy , swiftyjson can't either extract field want. here's sample of code: func sendjsonrequest(connectionstring: string, httpmethod : httpmethod = httpmethod.get, jsonheaders : [string : string] = [ : ], jsonstring: string = "") -> nsdata? { // create request & response let request = nsmutableurlrequest(url: nsurl(string: connectionstring)!, cachepolicy: nsurlrequestcachepolicy.reloadignoringlocalcachedata, timeoutinterval: 5) // create json data , configure request let jsonstring = jsonstring; request.httpbody = jsonstring.datausingencoding(nsutf8stringencoding, allowlossyconversion: true) // handle both , post request.httpmethod = httpmethod.rawvalue // we'

Opening Multiple files from a directory C++ -

i trying open files directory everytime display files have these 3 dots @ top. example directory open called "my documents" output 3 dots follows . .. names.txt jobs.txt names.txt , jobs.txt output want achieve, out. my code int getdoc(string doc, vector<string> &documents){ dir *dp; struct dirent *dirp; if ((dp = opendir(doc.c_str())) == null){ cout << "error(" << errno << ") opening" << doc << endl; return errno; } while ((dirp = readdir(dp)) != null){ documents.push_back(string(dirp->d_name)); } closedir(dp); return 0; } by way use dirent.h the 3 dots 2 directories. first 1 named '.' refers current directory. if try open it, lead same directory. example, directory c:\users\daniel equal c:\users\daniel\. second directory '..'. refers parent directory. c:\users directory equivalent c:\users\daniel\.. those 2 direct

Writing Output of Python Program to .txt File -

i've written program reads csv file , outputs contents insert statements. wrote execute program should take output of csv parser program , write .txt file instead of writing entire output writes first statement. here code executor: import sys open('insert.txt', 'wb') f: subprocess.check_call(["python", "csvparsermultiple.py"], stdout=f) and code parser: import csv, os path = 'c:/users/user/desktop/test/' file in os.listdir(path): if file.endswith('.csv'): # print ('parsing file: ' + os.path.basename(path + file)) openfile = open(path + file) csvfile = csv.reader(openfile) getheader = next(csvfile) columnheaders = map((lambda x: "'" + x + "'"), getheader[:-1]) insert = 'insert testing (' + "'id', 'vehicleid', " + ', '.join(columnheaders) + ') values ' row in csvfile:

c - Detection of data type through scanf + usage of it in further functions -

so i'm relatively new c , trying out beginner programs. 1 of program reads user input stdin (through usage of scanf). i'm gonna explain step step sake of easier comprehension of intentions (although part of code functional/operational , not require specific help. if wish, may skip straight question below) so have program reads input scanf() , decides if it's number or string. #include <stdio.h> int isnumber(const char *input){ /* while not end of string */ while (*input != '\0'){ /* if not detect number, return 0 */ if (*input < '0' || '9' < *input) return 0; input++; } return 1; } int main(void){ char uinput[30]; /*ask user input */ printf("please enter number or word \n"); scanf("%29s", uinput); if (isnumber(uinput)){ printf("we found number %s \n", uinput); } else { printf("we found word %s \n", uinput); } return 0; } so yeah, in program works far. everything's cl

android - ItemTouchHelper callback -

i have problems understanding callback method of itemtouchhelper called when swipe carditem, dont finish swipe , instead turn normal state. what have currently: @override public void onswiped(final recyclerview.viewholder viewholder, int direction) { mcarditemadapter.deletecard(viewholder.getadapterposition(), mrecyclerview); } which removes item adapter. and: @override public void onchilddraw(canvas c, recyclerview recyclerview, viewholder viewholder, float dx, float dy, int actionstate, boolean iscurrentlyactive) { log.d("dx =",""+dx); // can modified if(dx < -300) { view v = viewholder.itemview; relativelayout mlayout = (relativelayout) v.findviewbyid(r.id.card_item_layout_relative_layout); mlayout.setbackgroundresource(r.color.red); } super.onchilddraw(c, recyclerview, viewholder, dx, dy, actionstate, iscurrentlyactive); } what want achieve ? when swipe, background tur

python - cv2.floodFill() hanging with certain inputs -

Image
i have loop run through image , flood fill every 20 pixels: h, w = image.shape[:2] mask = np.zeros((h+2, w+2), np.uint8) mask[:] |= 0 flags = 4 flags |= cv2.floodfill_fixed_range x in range(20,image.shape[1]-20): y in range(20,image.shape[0]-20): if x%20 == 0 , y%20 == 0: print x, y flooded = image.copy() print 'starting flood fill' minval = min(image.item(x,y,0),image.item(x,y,1),image.item(x,y,2)) maxval = max(image.item(x,y,0),image.item(x,y,1),image.item(x,y,2)) size = cv2.floodfill(flooded,mask,(x,y),(0,)*3, (40,)*3, (40,)*3, flags)[0] though @ points cv2.floodfill() never completes. if lower lo , hi bounds able process further still stuck. has else had problem? with image hangs @ pixel (40,400): you should re-initialize mask inside loops each time floodfill modifying it. can improve performance dropping % operators. , fix bug, image.item(x,y, , should image.item(y,x,

html - Position element to the bottom of a height: 100% div -

i "pin" button bottom of sidebar-div has height of 100%, should fill whole left side of page. i tried way: .sidebar { height: 100%; position: relative; background-color: #cccccc; } .btn { position: absolute; bottom:0px; top: auto; } <div class="sidebar"> <button class="btn">button</button> </div> it might because of height in percent, works pixel-height, there must way of getting done percent, sidebar must span entire page height. to fix this, give html , body height of 100% follows. right don't have defined height set (so 0px high), button technically @ bottom. live example: html, body { height: 100%; } .sidebar { height: 100%; position: relative; background-color: #cccccc; } .btn { position: absolute; bottom:0; } <div class="sidebar"> <button class="btn">button</button> </div>

javascript - Can knex.js be used without migrations/seeding? Is there something wrong with this knex.js code? -

the cannonical way of using knex.js, seems, create migrations define schema, , insert said schema in normal node.js code. is there way not use migrations? can use knex.schema.createtable(...) function normal node.js code? there documentation on sort of thing? edit: wrote question because thought couldn't execute knex.schema.createtable(...) functions within normal code base. seems can't use knex @ within code. if use migrations generate schema sqlite3 database, works, never seem able insert or query data, within migrations or otherwise. my migrations file: exports.up = function(knex, promise) { return promise.all([ knex.schema.createtableifnotexists('test', function(table){ console.log("creating user table"); table.increments('id'); table.text('test'); }) ]); }; exports.down = function(knex, promise) { return promise.all([ knex.schema.droptableifexists('t

Safest way to remove argument order and provide default values at the same time in Python -

i trying write python 2.7 cod easier scale removing argument order while providing default values in case requirements change. here code: # class: class mailer(object): def __init__(self, **args): self.subject=args.get('subject', none) self.mailing_list=args.get('mailing_list', none) self.from_address=args.get('from_address', none) self.password=args.get('password', none) self.sector=args.get('sector', "there problem html") # call: mailer=mailer( subject="subject goes here", password="password", mailing_list=("email@email.com", "email@email.com","email@email.com"), mailing_list=("email@email.com", "email@email.com"), from_address="email@email.com", sector=sector() ) i'm still new language if there better way achieve this, i'd know. in advance. try way of initiali

python - Oauth2 No grant found for state in flask and oic.oauth2 package -

i trying implement oauth2 authentication using openid connect workflow cloudfoundry uaa backend authentication provider in python flask application using oic.oauth2. i encountering issue encounter "no grant found state" error when trying access token request though can curl , obtain access token via post curl -k 'https://172.17.0.114:8443/oauth/token' -i -x post -h 'accept: application/json' -h 'content-type: application/x-www-form-urlencoded' -d 'client_id=ga4gh_server&client_secret=ga4gh_server&grant_type=authorization_code&response_type=id_token&code=1n3ilw&state=cybafdwl79yu19lcedodalmd&token_format=opaque&redirect_uri=https%3a%2f%2f172.17.0.107%2fga4gh%2foauth2callback' http/1.1 200 ok server: apache-coyote/1.1 cache-control: no-cache, no-store, max-age=0, must-revalidate pragma: no-cache expires: 0 strict-transport-security: max-age=31536000 ; includesubdomains x-xss-protection: 1; mode=block x-frame-op

hadoop - It is possible to have different storage capacity for different data nodes in cluster? -

it possible add nodes of different capacity our hadoop cluster. example: data node 1 - 1 tb disk space, 20 gb memory data node 2 - 5 tb disk space, 30 gb memory data node 3 - 60 tb disk space, 50 gb memory. it possible. need different size of physical hard disk. you can not define size of hard disk use of data nodes in conf. file. if want disk spaces of different size use in data nodes can achieve having hard disk of different capacities. however block size remain same data nodes because block size defined whole cluster same not individual node.

html - css disproportionate image scaling -

i apologize noob question in advance. what disproportionate scaling of image. if have image of 800x600px, want displayed 100x100px. before worked set width , height on img tag, however, 1 of properties ignored , blog entry looks lame. help? try setting background-size set cover , should perserve scale, cover whole area , crop areas overflow: background-image: url('image.png'); background-repeat: no-repeat; background-size: cover; width: 100px; height: 100px;

linux - changing format of date shell -

i want change date format of last reboot time. how can this? idea ? cut other things last reboot command. last seems : output : 1 nov 2015 but want : dd/mm/yyyy : 01/11/2015 since cut output have convert different format, try below find expected format. export date="1 nov 2015" date -d"$date" +%d/%m/%y 01/11/2015