Posts

Showing posts from June, 2012

serialization - Serializing Joda DateTime using groovy.json -

i have simple pojo class fueling want serialize json using built in groovy json library. application halts when trying serialize. class fueling { int id; int mileage; double amount; double cost; datetime datetime; string userid; } the following tests renders java.lang.stackoverflowerror: @test void parsejoda(){ def fueling = new fueling(amount: 1.0, cost: 2.3, mileage: 123, datetime: datetime.now(datetimezone.utc)); def jsonf = jsonoutput.tojson(fueling); } how can make serialization work? edit: json data persisting , not display purpuses, actual serialization result format not important long able deserialized again given don't care format, 1 simple workaround use maps groovy json api input/output , add in little code translate domain objects , maps. serializing you can use map returned getproperties as-is 2 modifications: converting datetime instance it's long millisecond representation , removing class entry (which lead memory errors

c# - CheckChanged will not fire -

i trying learn c# , asp.net, , i'm having trouble figuring out checkbox events. phone class: public checkbox chkbox { get; set; } chkbox = new checkbox(); chkbox.checkedchanged += chkbox_checkedchanged; void chkbox_checkedchanged(object sender, eventargs e) { throw new notimplementedexception(); } default.aspx.cs foreach (phone p in building.phones) { tablecell cell_switch = new tablecell(); cell_switch.controls.add(p.chkbox); row.cells.add(cell_switch); } all of checkboxes show in table no issues, when check box cannot code break on checkchanged event. i'm sure i'm misunderstanding fundamental here, appreciated! notice code changes made default.aspx.cs public class building { public list<phone> phones { get; set; } public building() { phones = new list<phone>() { new phone(), new phone() }; } } public c

scala breeze matrix of random normal values -

i want same result obtained in python with x=np.random.normal(0, 1, (n_samples, n_features)) i have tried: import breeze.linalg._ object helloworld { def main(args: array[string]) { println("start") val n_samples = 5 val n_features = 3 val normal01 = breeze.stats.distributions.gaussian(0, 1) val samples = normal01.sample(n_features*n_features) val x = densematrix(n_samples, n_features, samples) // return error //print(x) } } where error? replace matrix creation line with: val x = new densematrix[double](n_samples, n_features, samples.toarray) and fix typo on previous line. for reason constructor doesn't seem in companion object, have use "new" keyword (this bug in breeze, file issue). also, need coerce "samples" regular scala array.

Android Search Function With Custom ListView Using BaseAdapter And Edit Text -

hi i've been searching google few hours looking ways implement search filter / function custom listview my main xml file consists of edit text , list view item , single row xml consists of 2x textview , 1x image view my problem cannot seem search work references, ideas or otherwise appreciated nb app still under development please excuse incomplete stubs here's code: public class kantodex extends activity { listview l; edittext inputsearch; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.kantodex); l = (listview) findviewbyid(r.id.listview1); l.setadapter(new adapterhand(this)); inputsearch = (edittext) findviewbyid(r.id.edittext); inputsearch.addtextchangedlistener(new textwatcher() { @override public void ontextchanged(charsequence cs,

javascript - Advice on building a server connected android app -

i'm creating personal project, android application, user sign ins via server essentially. users able share important "updates" in both data stream users can have access to, , potentially down line data stream specific local users. unfortunately have no idea of how implement server application. i'm confident i'll able create solution though, need pointed in right direction. there existing servers/api's access allow me handle "connected" tasks? if make server myself application should start? if have absolutely no experience server side coding, should start php , mysql create simple api app. getting started download xampp bundle has need. sql , php easy beginners. on client(android) side use volley simple understand. however if want started node.js, server can in few minutes express.js

python - Issues Installing Pygame -

i`m having issues installing pygame. running 64 bit windows 8 system, 32 bit version of python 3.4. here how have been trying install far: i have visited http://pygame.org/download.shtml , downloaded file called pygame-1.9.2a0.win32-py3.2.msi. i have executed file , selected 'install users'. at point asks me select python location should install pygame. select 'will installed on local hard drive' dropdown. text box asks me input alternate python location. set c:\pythonx. set python location - c:\python34. i finish installer , go shell. input import pygame command line. gives following error: traceback (most recent call last): file "", line 1, in import pygame file "c:\python34\lib\site-packages\pygame__init__.py", line 95, in pygame.base import * importerror: dll load failed: specified module not found. if in python34 file after install, find pygame folder in location c:\python34\lib\site-packages\pygame.

c - KR exercise 4.7 Ungets function test -

i need write function ungets(s) push entire string onto input. don`t know if implementation of ungets right. have no idea how test it, appreciated. #include <stdio.h> #include <string.h> /* implementation */ #define bufsize 100 static char buf[bufsize]; static int bufp = 0; /* next free position in buf */ int getch(void) /* (possibly pushed back) character */ { return (bufp > 0) ? buf[--bufp] : getchar(); } void ungetch(int c) /* push character on input */ { if (bufp >= bufsize) printf("ungetch: many characters\n"); else buf[bufp++] = c; } void ungets(char *s) { int c; (c = 0; c < strlen(s); c++) ungetch(c); } your getch() , ungetch() code approximately correct (i've not tested them, right). if going report error, better report error on stderr , using similar to: fprintf(stderr, "ungetch: many characters (could not push %c)\n", c); yo

android - How to fix fatal error as a result of adding a header file -

i trying compile device driver target platform snapdragon msm8974. added more code tested module; , added more header files. 1 of header files not in include directory, searched in environment , found number of options chose ~/android/android-ndk-r10d/platforms/android-19/arch-arm/usr/include/stdint.h but keep getting following error, , not know how go fixing it. advice on can differently appreciated. here error: include/linux/stdint.h:32:24: fatal error: sys/_types.h: no such file or directory compilation terminated. here include statements in file: #include <inttypes.h> #include <linux/module.h> #include <linux/fs.h> #include <stdlib.h>

Laravel 5 file delete issue -

i have file in public/images/demo.jpg unable delete file::delete(public/images/demo.jpg) in windows. how solve issue. try correct path: file::delete(public_path('images/demo.jpg'));

ios - Fetching data from Parse.com into custom cell (swift) -

i attempting fetch data parse.com custom cell full of strings , images. believe either retrieving pffile incorrectly parse.com or retrieving pffile correctly converting file uiimage improperly. error receiving going on within loaddata() function. reads follows: could not find overload 'init' accepts supplied arguments information //used set custom cell class information { var partyname = "" var promotername = "" var partycost = "" var flyerimage: uiimage var promoterimage: uiimage init(partyname: string, promotername: string, partycost: string, flyerimage: uiimage, promoterimage: uiimage) { self.partyname = partyname self.promotername = promotername self.partycost = partycost self.flyerimage = flyerimage self.promoterimage = promoterimage } } parse fetch function func loaddata() { var finddataparse:pfquery = pfquery(classname: "flyerdatafetch")

javascript - Android How to detect double tap? -

i'm trying refresh canvas on doubletap in android. use gesturedetector in custom view . final gesturedetector mdetector = new gesturedetector( getcontext(), new gesturedetector.ongesturelistener() { @override public boolean ondoubletap(motionevent e) { invalidate(); return true; } } but i'm getting error the method ondoubletap(motionevent) of type new gesturedetector.ongesturelistener(){} must override or implement supertype method with remove '@override' annotation solution. remove override , warning the method ondoubletap(motionevent) type new gesturedetector.ongesturelistener() {} never used locally. then tried test whether works , made function change textview string whenever doubletap . nothing happens. i looked @ gesturedetector reference explanations, don't have doubletap there, uses. should do? try this final gesturedetector mdetector = new gesturedetector(getcontext(), ne

xml - Errors in rendering a RSS page -

i'm trying render rss page site. rss it'self works fine , it's validated. it's built php script made. however, when implement css , xsl, , call page, message: this page contains following errors: error on line 4 @ column 1: document empty below rendering of page first error. document created result of xsl transformation. line , column numbers given transformed result. but line 4 not empty @ all, nor rest of document. please, here there xsl file: <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/xsl/transform"> <xsl:template match="/feed"> <html> <head> <link href="xsl.css" rel="stylesheet" type="text/css" /> <style type="text/css"> body { font-size:0.83em; } </style> </head> <bod

php - Mysql joins 3 tables with multiple fields -

i trying join employee table "employees", timeclock transaction table "transactions" , table "hta" time field. want timeclock table add time employee worked between set of days. want other table "hta" add time each employee between set of days , employee table employees name. make things simple right working 1 day. therefore there 1 entry per employee. no 1 has clocked in multiple times day. in hta table there multiple entries per person day. here code select time_format( sec_to_time( sum( time_to_sec( `t`.`hours_today` ) ) ) , "%h:%i:%s" ) `hours_today` , time_format( sec_to_time( sum( time_to_sec( `h`.`run_time` ) ) ) , "%h:%i:%s" ) `run_time` , `t`.`employee_id` , `e`.`employee_id` , `e`.`displayname` `transactions` t left join `hta` h on `t`.`employee_id` = `h`.`employee_id` , `t`.`date` = `h`.`date` left join `employees` e on `t`.`employee_id` = `e`.`employee_id` `t`.`date` >= "2015-08-14&q

java - Receiving incorrect values from a JTable -

i trying retrieve , use values jtable after row has been selected using code: @override public void valuechanged(listselectionevent e){ tablemodel tablemodel = this.mainframe.getviewerstablemodel(); this.mainframe.setviewerbuttonsenabled( !((boolean)(tablemodel.getvalueat(e.getlastindex(), 1))) ); } in scenario, table has 1 row value of true, , of false. the strange thing first time select row, value given correct , whether row holding true, or 1 false, subsequent selections result in getting true, no matter row pick. well, fixed it. instead of getting required boolean in event handler class, made method in mainframe class retrieves boolean table. issue resolved. thank helped.

Outlook VBA insert URL not working -

i can insert manually picture outlook 2010 new email using "insert picture" , “insert link file” feature. in file field enter link: http://www.example.com/image.php?s1=song1.net & c1=composer the link returns image , can see in body of email. i need enter url using vba. wrote code below , not work. when tried run came following message: run-time error ‘4198’: command failed. highlights line includes link. my code: sub inserthtmlfile() dim insp inspector set insp = activeinspector if insp.iswordmail dim worddoc word.document set worddoc = insp.wordeditor worddoc.application.selection.insertfile "http://www.example.com/image.php?s1=song1.net & c1=composer ", , false, false, false end if end sub i appreciate if can show me how can use vba insert image did manually. unfortunately outlook not have macro recorder show me instructions how it. try use %20 replace/encode spaces in url string. also i'd suggest recording vba macro in

ios - Use UIKit conditionally in file used by Watch app -

i have created model class use in ios app , watch app - included in both targets. have use uipasteboard in class available in uikit , not available watchos. while can import uikit file without issue, when go use uipasteboard not compile because watch extension not know it. how can use uipasteboard in class available watch app? i wondered if run code when device isn't apple watch using #available , didn't resolve issue. if #available(ios 7.0, *) { uipasteboard.generalpasteboard()... //error: use of unresolved identifier 'uipasteboard' } else { //don't use uipasteboard } use existing preprocessor directive defined in swift: #if os(ios) //uikit code here #elseif os(watchos) //watch code here #endif see documentation preprocessor directives here .

java - Method overriding and inheritance -

public class circle { public static final double pi = 3.141592654; protected double radius; public circle(double radius) { this.radius = radius; } @override public string tostring() { return "class = " + getclass().getsimplename() + " (radius = " + radius + ")"; } } public class planecircle extends circle { private double centerx, centery; public planecircle(double radius, double centerx, double centery) { super(radius); this.centerx = centerx; this.centery = centery; } @override public string tostring() { return super.tostring(); } } suppose above 2 classes in different files. when create instance of planecircle (in java file) following 2 lines... planecircle planecircle1 = new planecircle(3, 6, 7); system.out.println(planecircle1.tostring()); what in console output is class = planecircle (radius = 3.0) the tostring() method in pla

tkinter - Setting a row limit for python code within for loop? -

question: how alter tkinter.label 's row once number of rows have been reached within for loop? code: import tkinter import sys fractions import gcd def func(event): x = int(e1.get()) # max number result = [] in range(1, x): # loops each value in range of x b in range(a, x): c in range(b, x): if a**2 + b**2 == c**2 , gcd(a, b) == 1: # if primitive pyth triple, append result result += ['[',a,',',b,',',c,']'] # add group of triples list l = tkinter.message(root, text=result).grid(ipadx=5, ipady=5, sticky='w''e') # display each group of triples root l0 = tkinter.label(root, text="non-primitive , primitive triples").grid(ipadx=5, ipady=5, sticky='w''e') root.bind('<return>', close) # hit enter exit, temp debugging, reassign button later def close(event): # close program, define parameter event allow

parsing - Searching in an indexed string -

the plot there rather complicatedly formatted string, there's no such readable regex parses it. , aim specific substring example, , it's original position. substring reached after parsing bit, trimming, removing beginning , searching n-th element example. want demonstrate complexity example, otherwise it's pretty general. for demonstration, see rudimentary example. way isn't important, reach pretty complicated parse model. obviously, there can more rule , can write simplier model well. firstblock{index1, index2} secondblock thirdblock { firstblock {index1,index2} secondblock} {firstblock secondblock thirdblock fourthblock} i've tried make random be. parsing model like: string text = "{ firstblock {index1,index2} secondblock}"; text = text.trim(); if (text.first() == '{') { text = text.substring(1, text.length - 2); } text = text.trim(); string firstblock = text.split(new char[] { ' ', '{' })[0]; text = tex

bash - magic bytes (or removing latest newlines from being piped) -

as messing multipart messages encountered strange behavior evaluating content length of multipart message bodies. long story short. can broke down newlines being piped. $ a="x"; b="y" $ echo -e "${a}" | wc -c 2 # strange, shouldn't single byte? $ echo -e "${b}" | wc -c 2 # @ point 1 guess sum **4**, not $ echo -e "${a}${b}" | wc -c 3 $ echo -e "${a}${b}" | hexdump -c 00000000 78 79 0a |xy.| 00000003 is there possibility avoid magic/invisible byte being piped or - if not possible - @ least removed? thanks in advance. the magic character you're referring to, newline character \n . newline tells terminal emulator you're running — guessed — print newline! echo default appends newline end of string, string doesn't end on same line prompt. echo can passed -n , prevents appending newline end of string. use printf command not append newline default. i suggest printf on echo , there man

reflection - Swift - Possible to programmatically know if function is a @IBAction or framework name? -

is possible programmatically know if method @ibaction method? - or possible framework name of method being called? function goes far , doesn't show method attributes. do need @ reflection information, or there quick win? thanks! you can: command + click on method, etc. , take it's parent declaration. and option + click give declaration, description, availability, declared in, , reference.

php - Laravel Validation: How to access rules of an attribute in customized validation -

in below rules, have custom validation customrule: *date* $rules = [ 'my_date' => 'required|date_format: y-m-d|customrule: somedate', ]; inside custom validation rules extension, need access date_format attribute of rule: validator::extend('customrule', function($attribute, $value, $parameters) { $format = $attribute->getrules()['date_format']; // need return $format == 'y-m-d'; }); how can rule value of attribute on extended validator? you can't access other rules . validators independent units - data should use is: value of field being validated values passed validation rule parameters values of other attributes of object being validated it seems need custom validator wrap date_format , customrule doing: validator::extend('custom_date_format', function($attribute, $value, $parameters) { $format = $parameters[0]; $somedate = $parameters[1]; $validator = validator::make(['v

html - Tumblr: Content Overlaps Fixed Header? -

i able code fixed header tumblr blog: http://artsypancake.tumblr.com/ the header works fine on home page , overlaps of posts, intended effect. however, content on custom pages runs on header when scroll down. example: http://artsypancake.tumblr.com/aboutme confusing occurs custom pages i've made. also, i've tried increasing z-index header, doesn't make difference on custom page posts. here's css header: #topbar { z-index: 999; position: fixed; top: 0; left: 0; width: 100%; height: 27px; text-align: center; background-color: {color:top bar background}; border-bottom: 3px solid {color:top bar border}; } #topbar { position: relative; font-family: text me one; color: {color:top bar text}; background-color: {color: top bar text background}; letter-spacing: 1px; font-size: 9px; text-transform: uppercase; margin: 5px; padding: 5px; top: 7px; -webkit-transition: 0.2s ease-in-out; -moz-transition: 0.2s ease-in-out; -o-transition: 0.2s ease-in-out; -ms-transition: 0

c - seeing random numbers in my loop after the array length has been reached? -

i creating simple array in c , outputting result console see content of array is. i using code below , whole program test. it asks size array want, put in 6 example, , put in 6 numbers. now when declare array @ start set maximum numbers can 10, thought meant can add 10 numbers in array. but when put in 6 numbers , loop see in array this: 5 1 2 4 3 6 4203737 0 4225576 0 process exited after 7.421 seconds return value 0 press key continue . . . the numbers asking 420 , 0 etc. why there they make total index 10, want 6 or whatever number set index length? int main(int argc, char *argv[]) { int array[10]; int position, c, n, value; printf("enter number of elements in array\n"); scanf("%d", &n); printf("enter %d elements\n", n); (c = 0; c < n; c++) scanf("%d", &array[c]); //printing array know in int = 0; int sizeofarray = sizeof(array) / sizeof(array[0]); //determine length of array for(i;

javascript - Changing props of child component with onchange in React -

i trying change props of chart component select. url value not change data_stat2.json in chart , if can see change in url variable via console . should change in select trigger new render change this.props.url in chart? var app = react.createclass({ render: function() { var url ="data_stat1.json" function logchange(val) { url = 'data_' + val + '.json'; console.log(url)}; return ( <grid style={{padding: 10}}> <row> <col md={8}> <select name="stats" value="stat1" options={[ { value: "stat1", label: "stat1" }, { value: "stat2", label: "stat2" } ]} multi = {false} clearable = {false} searchable={false} onchange = {logchange} /> </col> </row> <row> <chart url = {url} /> &l

ios - How to modify the color of hairline of uinavigationbar -

i've known way hairline view, uiimageview, question: how hide ios7 uinavigationbar 1px bottom line but, modify view's background color bad experience, code this: [[self findhairlineimageviewunder:self.navigationcontroller.navigationbar] setbackgroundcolor:[uicolor colorwithhexstring:@"ff0000"]]; the findhairlineimageviewunder method answer link above this works, not always, put in viewdidload , viewwillapear , viewdidlayoutsubviews , go original color @ scene, after push , pop. so, i'd ask if there perfect way change color of hairline of uinavigationbar, thanks. now found addd subview hairline's superview did trick , works fine uiview* sv= [[uiview alloc] initwithframe:[self findhairlineimageviewunder:self.navigationcontroller.navigationbar].frame]; sv.backgroundcolor=[uicolor colorwithhexstring:@"ff0000"]; [[self findhairlineimageviewunder:self.navigationcontroller.navigationbar].superview addsubview:sv];

Arrange filter values in tableau -

i have filter values (dimension) in tableau - want arrange in ascending order. the values in quick filter ordered alphabetically: 03 05-jun-2015 06 10-jul-2015 08 12-jun-2015 13 16-jul-2015 15 19-jun-2015 20 24-jul-2015 22 26-jul-2015 27 31-jul-2015 29 03-jul-2015 in list above, values ordered alphabetically, not chronologically. want them in order: 03 05-jun-2015 08 12-jun-2015 15 19-jun-2015 06 10-jul-2015 13 16-jul-2015 20 24-jul-2015 22 26-jul-2015 27 31-jul-2015 29 03-jul-2015 is there way make above filter values display in desired order? one approach apply manual sort order sort panel (which can bring right clicking on dimension wish sort, either on data pane set default sort order, or on shelf set sort order 1 worksheet) if don't want manual sort order, can apply dynamic sort based on values in data same panel, or use database default sort order (usually alphabetic order). in last case, want use standard sorted convention field values -- iso 900

Procedure is exited upon marshalling a C struct received via WM_COPYDATA into a C# struct -

here problem. trying marshal c struct c# struct. c struct sent c application c# application via wm_copydata message. sending , acknowledging message not problem , works fine. i run c application in debug, attach debugger c# application , send message. received , identified correctly when try marshal data, marshal.ptrtostructure function seems exit switch statement before executing rest of (see marked line in code). the procedure managecomplexmessage therefore not executed , data remains raw , unusable. this copydatastruct use in c# : private struct copydatastruct { public intptr dwdata; public int cbdata; public intptr lpdata; } this struct use in c# store data sent through wm_copydata : private struct complexdata { [marshalas(unmanagedtype.byvalarray, sizeconst = 75)] public int[] integers; [marshalas(unmanagedtype.byvalarray, sizeconst = 75)] public double[] doubles; [marshalas(unmanagedtype.byvalarray, arraysubtype = unmanagedtype

vba - Excel not transferring data properly from one sheet to another -

Image
recently i've been working on spreadsheet allows users input data on invoice template page, , save information on sheet. invoice template looks this: i put in random inputs each cell. data here b17:h37 needs moved sheet named invoice data when "save" forum button pressed user. data supposed inputted d:g on invoice data page, result such: a:c filled in different values outside b17:h37 (as shown in code below), but "name" data (column b) invoice box copied invoice data sheet while "hours", "cost", , "total" neglected. here's code have far (from tutorial found online): sub save_invoice() dim rng range dim long dim long dim rng_dest range application.screenupdating = false 'check if invoice # found on sheet "invoice data" = 1 until sheets("invoice data").range("a" & i).value = "" if sheets("invoice data").range("a" & i).value = she

java - Unable To Create CardView Fragment -

Image
i have no idea on wrong code. my application using navigation drawer. there 4 different fragments , 1 of cardview fragment have converted earlier activity fragment. the cardview fragment being underlined red shows error not able compiled. kindly refer attached pictures. if accept proposed solutions android studio,it solve cardviewfragment , new problem occur @ other 3 fragments. and both main activity , cardview fragment. mainactivity.java package info.androidhive.materialdesign.activity; import android.os.bundle; import android.support.v4.app.fragment; import android.support.v4.app.fragmentmanager; import android.support.v4.app.fragmenttransaction; import android.support.v4.widget.drawerlayout; import android.support.v7.app.appcompatactivity; import android.support.v7.widget.toolbar; import android.view.menu; import android.view.menuitem; import android.view.view; import android.widget.toast; import info.androidhive.materialdesign.r; public class mainactivity ex

How python calculate this modulo? -

how python calculate mathematically modulo? >>>-1%10 9 the wikipedia article on modulo operation provides following constraint a % q : a = nq + r substituting a = -1 , q = 10 , r = 9 , see n must equal -1. plugging in -1 n: -1 % 10 # python evaluates 9 -1 = n * 10 + r -1 = -1 * 10 + r 9 = r testing example (again plugging in -1 n): -7 % 17 # python evaluates 10 -7 = n * 17 + r -7 = -17 + r 10 = r a third example positive numerator , negative denominator: 7 % -17 # python evaluates -10 7 = n * (-17) + r 7 = -1 * (-17) + r 7 = 17 + r -10 = r it appears when a , q have different signs, start n = -1 , decrement n 1 until we've found n closest 0 such n*q < a . can test trying out a , q such |a| > |q| : -100 % 11 # python evaluates 10 -100 = n * 11 + r ... -1 # -11 > -100 ... -2 # -22 > -100 ... -3 ... ... -4 ... ... -5 ... ... -6 ... ... -7 ... ... -8 ... ... -9 # -99 > -100 -1

ios - Where should NSManagedObjectContext be created? -

i've been learning core data , how inserts large number of objects. after learning how , solving memory leak problem met, wrote q&a memory leak large core data batch insert in swift . after changing nsmanagedobjectcontext class property local variable , saving inserts in batches rather 1 @ time, worked lot better. memory problem cleared , speed improved. the code posted in answer was let batchsize = 1000 // sort of loop each batch of data insert while (therearestillmoreobjectstoadd) { // managed object context let managedobjectcontext = (uiapplication.sharedapplication().delegate as! appdelegate).managedobjectcontext managedobjectcontext.undomanager = nil // if don't need undo // next 1000 or data items want insert let array = nextbatch(batchsize) // own implementation // insert in batch item in array { // parse array item or whatever need entity attributes new object going insert // ... // insert new obje

Language translator for yii -

i wants add language translator yii web application. completed coding. there language translator available minor changing in application. because project in final stage. you can use tstranslation extension use database storing translated messages , have many features: translate dynamic content, , translation using syntax yii::t() have language managing widget (add/remove language, set/change default language, translate messages directly widget via google translate, etc) have language changing widget many options. and more other feauters after including extension project can add such languages want , add translations widget, without changes in code. you can try demo of extension here thanks.

Forcing zero instead of NA in R -

i have function called newbamad , dataframe x . function matches letters in ref , alt columns , grabs respective numbers ref , alt values in x . need know how make function give 0 in ref or alt column instead of na. how replace na 0 here? x <- as.matrix(read.csv(text="start,a,t,g,c,ref,alt,type chr20:5363934,95,29,14,59,c,t,snp chr5:8529759,,,,,g,c,snp chr14:9620689,65,49,41,96,t,g,snp chr18:547375,94,1,51,67,g,c,snp chr8:5952145,27,80,25,96,t,t,snp chr14:8694382,68,94,26,30,a,a,snp chr16:2530921,49,15,79,72,a,t,snp:2530921 chr16:2530921,49,15,79,72,a,g,snp:2530921 chr16:2530921,49,15,79,72,a,t,snp:2530921flat chr16:2530331,9,2,,,a,t,snp:2530331 chr16:2530331,9,2,,,a,g,snp:2530331 chr16:2530331,9,2,,,a,t,snp:2530331flat chr16:2533924,42,13,19,52,g,t,snp:flat chr16:2543344,4,13,13,42,g,t,snp:2543344flat chr16:2543344,42,23,13,42,g,a,snp:2543344 chr14:4214117,73,49,18,77,g,a,snp chr4:7799768,36,28,1,16,c,a,snp chr3:9141263,27,41,93,90,a,a,snp", stringsasfactors=fal