Posts

Showing posts from May, 2011

How to handle failed Matlab constructor? -

the matlab docs give example of class closes file if object deleted. i'm trying similar serial port object, if constructor fails valid handle object, delete method throw error. so question how make this: classdef filewriter < handle properties (access = private) fileid end methods function obj = filewriter(filename) obj.fileid = fopen(filename,'a'); % if fails... end function writetofile(obj,text_str) fprintf(obj.fileid,'%s\n',text_str); end function delete(obj) fclose(obj.fileid); % fail end end end ...where constructor may fail? in constructor should check failure. in case comparing fileid -1 , calling error . in delete method check fileid against -1 well, , not perform fclose , if -1 , perform cleanly.

jquery - javascript scripts won't work and events won't fire without www -

before start, let me using .htaccess adds www doesn't solves problem :-( works "most of times" (it won't work when in front of client) i have portfolio website. if launch www.mysite.com, javascript runs fine. if launch mysite.com javascript won't run, , events won't fire. example load ajax call portfolio. page load has image onload event attached. onload fires when site called www the weirdest thing redirect .htaccess doesn't solve problem, reduces occurrence , makes random :-/ could explain me why happens? i've had similar issues in past , never got @ end of it. thanks million help

c++ - Base class using data from derived class -

i have class class { uint8_t* queue; uint32_t num_elems_queue; void dosomethingwithqueue(); }; this class library used different clients. in client code used above class have like. class b { const uint32_t num_elems = 8; uint8_t queue[num_elems]; }; now in order initialize data in class have 2 options. 1 pass data in class in constructor such class { a(uint8_t* queue__, uint32_t num_elems_queue__): queue(queue__),num_elems_queue(num_elems_queue__) { } uint8_t* queue; uint32_t num_elems_queue; void dosomethingwithqueue(); }; the other inherit class b class , have pure virtual functions in class return pointer needed data. such as class { uint8_t* queue; uint32_t num_elems_queue; void dosomethingwithqueue(); virtual uint32_t get_num_elems_queue() = 0; virtual uint8_t* get_queue() = 0; }; class b : public { const uint32_t num_elems = 8; uint8_t queue[num_elems]; uint32_t get_num_elems_queue() ...

python - How to determine screen size in matplotlib -

i looking way screen size in pixels using matplotlib interactive backend (e.g. tkagg, qt4agg, or macosx). i trying write function can open window @ set of standard locations on screen e.g. right half of screen, or top-right corner. i wrote working solution here , copied below, requires 1 use full_screen_toggle() (as suggested here ) create full-screen window measure size. i looking way screen size without creating full-screen window , changing size. import matplotlib.pyplot plt def move_figure(position="top-right"): ''' move , resize window set of standard positions on screen. possible positions are: top, bottom, left, right, top-left, top-right, bottom-left, bottom-right ''' mgr = plt.get_current_fig_manager() mgr.full_screen_toggle() # primitive works screen size py = mgr.canvas.height() px = mgr.canvas.width() d = 10 # width of window border in pixels if position == "top": ...

elasticsearch type conversion -

not clear me how upload data thru logstash elasticsearch proper 'type' i mean, have file syslog message including part date: use grok in logstash parse string identifying %date , other parts of message, send output elasticsearch {}: date in elsaticsearch appears string , not date. data qualifyed right type in elsaticsearch. same happens other fileds, if parsed grok int, date, etc thay appears string in elasticsearch how solve this? thanks in advance franco the typical thing date logfile replace @timestamp value. first, use grok{} make field out of it, , feed date{} filter. if need create second date field in event, can specify "target" in date{} filter put result in field of choice.

PHP MySQL Data gets inserted, still getting Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in -

this question has answer here: mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row() expects parameter 1 resource 33 answers i trying make reservation system, everytime try submit, error "warning: mysqli_fetch_array() expects parameter 1 mysqli_result, boolean given in", data still gets inserted database. should go submitted.php page, doesn't, stays @ current page, haven no idea do. me out guys, kinda new php. <?php session_start(); include("connect.php"); include("functies.php"); $db = mysqli_connect($host, $user, $password, $db) or die(mysqli_connect_error()); //when submit button clicked if(isset($_post['submit'])) { $artist = $_post['artist']; $track = $_post['track']; $trackdl = $_post['downloadlink']; $genre = $_post['genre']; $sml = $_post['links']; $date = $_post[...

angularjs - Angular template not showing in rails app -

so have been battling issue past couple of days , can't seem find solution it. first want start off saying new both rails , angular, bare me while try explain issue , please let me know if there edits can make more clear. i'm trying add angular current rails app started researching here @ http://angular-rails.com/ . going swimmingly until tried route angular call load template. whatever reason, nothing when load page. i'm not sure missing, , i'm sure it's simple. i created simple controller test out angular , created route index controller method. in views/angular_test/index.html.erb file created link ng-app , ng-view so: <div ng-app="testapp"> <div class="view-container"> <div ng-view></div> </div> </div> then in app.coffee created app , configured controller , routeprovider: testapp = angular.module('testapp',[ 'templates', 'ngroute', 'controller...

python - Change Django alphabetical ordering to custom ordering -

i've created model reservation , code( models.py ) looks this: #choices status_choices = ( ('approved','approved'),('pending', 'pending'), ('canceled', 'canceled') ) # reservation model class reservation(models.model): class meta: ordering = ['-status'] status = models.charfield(choices=status_choices, default='pending', max_length=25) i want order reservations this: pending approved canceled but current order is: pending canceled approved it looks django ordering objects alphabetically. how can change alphabetical order 1 described above? thanks! you change status integerfield , , define constants 3 states. sorting 'status' should want. pending = 1 approved = 2 canceled = 3 status_choices = (approved,'approved'),(pending, 'pending'), (canceled, 'canceled)) or create statuschoice model, field sort_order . make reservation.status ...

c# - Data type mismatch on write, reading works fine -

in asp.net webforms project .net 3.5 data transferred access database. site runs on iis 6 on windows 2003 (english cersion). in aspx file accessdatasource used read , write data. reading data works fine, writing dates fails. writing works, if date provided mm-dd-yyyy, dd.mm.yyyy not work. if date provided dd.mm.yyy error: system.data.oledb.oledbexception: data type mismatch in criteria expression. an code example leading error: accessdatasource myads = new accessdatasource("~/app_data/mydb.mdb", ""); myads.insertcommand = "insert [table1] " + "([value], [date]) values ('data', datevalue('" + datetime.now.tostring("dd.mm.yyyy") + "'))"; myads.insert(); the regional , language settings set german , therefore correct date format. in database date , time stored in datetime field. what have cofigure correct this, without changing hundrets of pages of legacy code? change datetime.no...

javascript - Node.JS with Mongoose OOP - how to separate mongoose data access code from pure data object? -

i came across bit of design problem mongoose - maybe following wrong approach? in old oop style want have class called user. class has several member such username, firstname, lastname, salt , hash, , has method called authenticate takes hashed password argument. fill user object data, need write code this, far aware: var userschema = mongoose.schema({ firstname: string, lastname: string, username: string, salt: string, hashed_pwd:string }); userschema.methods = { authenticate: function(passwordtomatch) { return crypto.hashpwd(this.salt, passwordtomatch) === this.hashed_pwd; } } this code cluttered mongoose specific code - calling mongoose.schema, , add method have use userschema.methods. when tried declare user class separately , tried create mongoose schema out of it, encountered kinds of errors, , member method not recognised. so when want use different database using same schema, have redeclare everything. want declare sche...

javascript - Cannot read property 'done' of undefined due to switch -

i have function gaining data ajax. problem construction switch causing error: cannot read property 'done' of undefined i don't know why... <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> function changeselect(input,type) { var out; switch(type) { case "sport" : out=$.post("/ajax/ajax.php",{sport:input.value}); case "competition" :out=$.post("/ajax/ajax.php",{competition.value}); } out.done(function(data) { $("#output").html(data); }); }</script> answer. the cause of error getting value of type not match either of case statements. thus, out remains undefined , gives error see. in addition, must use break; statements in case of case: statements , {competition.value} not valid es5 javascript. perhaps want this: function changeselect(input, type) { var out; switch (type) { case "sport...

linux - Compile PyAudio without Jack, without PulseAudio, etc -

i want compile pyaudio few layers possible. want use portaudio (needed pyaudio ) uses alsa, but not jack, not pulseaudio, not else . i have pyaudio <--> portaudio <--> alsa , nothing more. when doing: git clone http://people.csail.mit.edu/hubert/git/pyaudio.git cd pyaudio sudo python setup.py install it link library jack, etc. don't want. how compile pyaudio nothing else portaudio , alsa? reason: debug problems, might related other layers. when install pyaudio showed it, use portaudio library installed on system (e.g. via apt-get ). if want portaudio without jack, you'll have sources http://www.portaudio.com/ , compile using: ./configure --without-jack i think pulseaudio isn't directly supported anyway. if don't want pulseaudio interfere, may easiest uninstall it.

windows - Gnu Make target out of expanded list of files -

i grouping type of files like: https://www.gnu.org/software/make/manual/html_node/wildcard-function.html about 100 sub directories... cc_files_to_build += $(wildcard $(src_dir)/01-application/*.c) asm_files_to_build += $(wildcard $(project_root)/01-sources/07-target/01-mc9s12g/04-startup/01-cpl_lib/*.s) when dump example cc_files_to_build per rule, nice lists of files names: e:\1983_1\02-safety>make dump-cc_files_to_build make[1]: entering directory `e:/1983_1/02-safety/01-application' e:\1983_1\02-safety\01-application/01-sources//01-application/01-init/app_init.c e:\1983_1\02-safety\01-application/01-sources//01-applicat ion/02-main/app.c e:\1983_1\02-safety\01-application/01-sources//01-application/03-fm/fm.c e:\1983_1\02-safety\01-application/01-sources//01 -application/05-smcm/smcm.c e:\1983_1\02-safety\01-application/01-sources//01-application/06-lim/lim.c e:\1983_1\02-safety\01-application/0 1-sources//02-services/01-canm/can_user.c e:\1983_1\02-safety\01...

javascript - Jquery with Json response is showing extra values -

Image
i have jquery question. $.ajax({ type: 'get', datatype: 'json', url:'/bin/getpath', success: function(jsonarray){ for(var in jsonarray) { $("#myselect").append("<input type='radio' name='path' value='"+jsonarray[i]+"'> "+jsonarray[i]+"</input><br/>"); } } }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <div id ="myselect"></div> and json response url : when running code, working fine in firefox although same code showing 1 more radio button below. please : regards, td below working code : $.ajax({ type: 'get', datatype: 'json', url:'/bin/getpath', success: function(jsonarray){ $.each(jsonarray,function(index,value){...

How do I fix my anaconda python distribution? -

all seemed working fine in anaconda distribution on mac. tried install postgres library psycopg2 conda install psycopg2. threw error. permissions. nothing works. can't find conda executable or start ipython. -bash: conda: command not found should condo executable in ~/ananconda/bin. directory there no conda executable. anyone know might have happened or how can recover this? you're going have reinstall anaconda fix this. without conda, there's not can clean broken install.

Is there any way to know a specific page is being visited in Django? -

i have page in django allows 1 user see @ same time. there way information? if can know visiting page, can block other requests then. thank you. use database "referee". make class inherits generic.templateview , override get and/or post method, , before calling parent, make query database: if page being watched dont call parent , return redirect main page. but may run trouble if 1 viewing page switches off computer: how know he's not watching anymore? may have implement watchdog or something, , then, chrome, watchdog stopped if it's not active tab... if search way of dealing problem.

optimization - Redundant opcodes in Android dex -

i'm looking android performance issues @ moment , noticing sub-optimal patterns in dex code. i'm wondering if knows if expected, , rationale behind might be. for example, consider following java code: m_testfield += i; dosomething(m_testfield); when built , run through baksmali looks following: iget v1, p0, lcom/example/mainactivity$fieldtest;->m_testfield:i add-int/2addr v1, v0 iput v1, p0, lcom/example/mainactivity$fieldtest;->m_testfield:i iget v1, p0, lcom/example/mainactivity$fieldtest;->m_testfield:i invoke-direct {p0, v1}, lcom/example/mainactivity$fieldtest;->dosomething(i)v the part that's concerning me iget opcode read value of instance field register v1. same field written same v1 register in preceding opcode, opcode appear redundant. the thing can think of done make more thread-safe. surely should programmer's responsibility (by using sync blocks) instead of compiler's responsibility. although i'm not 100% certain, t...

javascript - remove specific id from array of checked items -

i have list/array of sports default of them checked = true , in function below can see line intersectedsports = _.intersection(sportids, sportchecked.sport); sportids full list of sports ids , sportchecked.sport sports checked = false sports user unchecked. remember: sports checked = true default. this array of 30 items, every item has unique id , mentioned sports checked = true , need id: 10 checked = false default. behind code see, there construction save in db items user checked = false , that's why see here line sport.checked = !_.includes(intersectedsports, sport.id); . so, in order want, guess: need put id: 10 checked=false in var = intersectedsports mentioned above, unless have better suggestion me... so, recommend friends ? var sportids = _.pluck(sports, 'id'), intersectedsports = _.intersection(sportids, sportchecked.sport); if (sports.length) { sports = _.map(sports, function(sport) { sport.checked = !_.includes(intersec...

javascript - JSP JQuery show div after logout -

i have jsp website has menu bar. upon clicking logout button, page redirects welcome jsp page. however, hope make once user clicks logout, welcome page has div span reads "you have logged out". have been trying work, no avail. in javascript, start globally defined variable, , have 2 related functions. logoutdeterminant = "no"; function determine(word) { if (word == "yes") { logoutdeterminant = "yes"; alert(logoutdeterminant); } } function showlogoutnotification() { if (logoutdeterminant = "yes") { alert(logoutdeterminant); //toggle class } } the global variable logout determinant starts no. when welcome jsp loads, runs showlogoutnotification, means global variable assigned no, , class div on page not toggled. div successful logout notification, , there class hides it. toggle doesnt work, , hidden class isn't removed. once user enters main page, , clicks logout, function dete...

python - Parse the ouput of a variable -

i have following variable,i need parse value in errormessage,can suggest how it? message ={"value":1,"errormessage":null,"text":{"result":"<requestgroupid>11647</requestgroupid><requestid>34382</requestid>"}} expected output:- null that json string. need use json.loads parse , convert dictionary first. import json ob = json.loads(message) print(ob["errormessage"]) though give none , not null .

oauth - How do I get around Access-Control-Allow-Origin error with ReactJS? -

i have flask backend set runs through google's oauth2 flow. when user visits /signup, there's button there can press start up. know flow works because if set start visits /signup (by doing 302 redirect /start-google-oauth endpoint), goes smoothly. but if remove redirect , have user start flow pressing button, doesn't work. button issues request /start-google-oauth redirect google open popup window returns access-control-allow-origin error: xmlhttprequest cannot load https://accounts.google.com/o/oauth2/auth?redirect_uri=... no 'access-control-allow-origin' header present on requested resource. origin '<origin url>' therefore not allowed access. the origin specified origin url given valid redirect_uri in app's credential setup. what causing this? since forwarding get request try setting access-control-allow-origin: * before forwarding.

osx - Bash path to iPhoto library's slideshow -

when click slideshow called "unnamed slideshow" in iphoto, tells me can't find of photos. trying delete won't let me, since there many pop-up messages. thus, wondering if there way access diashow using bash manually remove it. appreciated. thanks! check out this post. first need determine filepath on own, use pertinent command either delete directory or files.

Apache server is running but httpd is not running -

i'm facing weird problem. when access web-accessible directory of server via domain linked it. says:- not found requested url / not found on server. when run command on server (via putty), displays few processes ids demonstrating apache web server running (correct me). root@...:~# pgrep apache 4733 13505 13506 13507 13508 13686 14199 17672 but when run command, says httpd: unrecognized service root@...:~# service httpd status httpd: unrecognized service some other commands output:- root@...:~# ps aux|grep -i http root 29401 0.0 0.0 6460 792 pts/0 s+ 02:21 0:00 grep --color=auto -i http how can fix this? update:- root@...:~# chkconfig --list | grep httpd -bash: chkconfig: command not found root@...:~# find / -name httpd* /var/www/vhosts/lvps5-35-241-230.dedicated.hosteurope.de/httpdocs /var/www/vhosts/.skel/0/httpdocs /opt/psa/var/httpd_restart /usr/lib/apache2/modules/httpd.exp /usr/share/doc/apache2-doc/manual/fr/programs/httpd.html /usr/s...

javascript - ajax parse xml response function wont recognize XML file URL -

im using following code solution on here <script type="text/javascript"> $(document).ready(function(){ $.ajax({ type: "get", datatype: "xml", url: "xmlfile.xml", success: function(xml){ $("#output").append($(xml).find("address")); } }); }); </script>` and if use local xmlfile.xml file works fine, when try run same function xml file hosted elsewhere, stops working: http://www.zillow.com/webservice/getupdatedpropertydetails.htm?zws-id=x1-zwz1ebcem1ra4r_10irx&zpid=48749425 i tried encoding url using escape() , encodeuricomponent() neither of worked. what doing wrong? why function work local xml file breaks when use other url?

python - Numpy: Multiprocessing a matrix multiplication with pool -

i trying calculate dot product pool pool = pool(8) x = np.array([2,3,1,0]) y = np.array([1,3,1,0]) print np.dot(x,y) #works print pool.map(np.dot,x,y) #error below valueerror: truth value of array more 1 element ambiguous. use a.any() or a.all() also tried ne.evaluate('dot(x, y)') typeerror: 'variablenode' object not callable what trying is, unfortunately, not possible in ways you're trying it, , not possible in simple way either. to make things worse, multiprocessing.pool documentation python 2.7 utterly wrong , lies pool.map : isn't @ equivalent builtin map . builtin map can take multiple argument iterators pass function, while pool.map can't... has been known , not fixed or documented in docstring pool.map since at least 2011 . there's partial fix, of course, in python 3 starmap... honestly, though, multiprocessing module isn't terribly useful speeding numerical code. example, see here long discussion of situations m...

Equivalent of PostMethod of Java in PHP -

i ask if there exists php function simulate block of code in codeigniter. httpclient httpclient = new httpclient(); postmethod postmethod = new postmethod(requesturl); namevaluepair[] datas = {new namevaluepair("studentnumber", studentnumber), new namevaluepair("studentdata", encrypteddata)}; postmethod.setrequestbody(datas); int statuscode = httpclient.executemethod(postmethod); byte[] responsebyte = postmethod.getresponsebody(); string responsebody = new string(responsebyte, "utf-8"); curl doesn't seem work, while $this->output->set_output passes data fails catch response of requesturl. thank you. i able catch response requesturl using block of code found on http post php, without curl (thanks lot this). $options = array( 'http' => array( 'method' => "post", 'header' => "accept-language: en\r\n" ....

Cut sub-string and rename files use shell command -

this question has answer here: how rename prefix/suffix? 7 answers how rename file names? want map names: abc-hdpi.png ⟶ abc.png bcd-hdpi.png ⟶ bcd.png ... i have many files this, mv abc-hdpi.png abc.png not solution. search prename (perl rename ) command; can job easily: prename 's/-hdpi.png/.png/' *-hdpi.png failing that: for file in *-hdpi.png mv "$file" "${file%-hdpi.png}.png" done

permissions - How to give access rights for pages and menus in php? -

i'm working on website there 3 types of users: admin, managers, , operators. want give access these groups them able view pages or menus in these pages when login. how go doing this? im still beginner in php information or tutorials implement helpful. this loaded question, in experience want make 3 tables. highlight basic columns make work user user_id, login, password access access_id, access_code, access_name useraccess user_access_id, access_id then create accesses want administrator give access code admin_rights, manager access code manager_rights, , on. then assign users access want give them. pages assign access_codes can view page , if user has access type can view page. far code goes there lot show if need more help,let me know. you go further , add role table allows assign multiple accesses , assign role user. role role_id, role_name roleaccess role_access_id, role_id, access_id userrole user_role_id, role_id, user_id it gets complex, in lo...

lua - How do I turn a string into an argument? -

i using app touchlua. i need turn string table argument. way table. b = {} b[1] = "010,010,draw.blue" function drawbuttons() = 1,2 draw.fillrect(tonumber(string.sub(b[i],1,3)), tonumber(string.sub(b[i],5,7)), tonumber(string.sub(b[i],1,3))+10, tonumber(string.sub(b[i],5,7)),string.sub(b[i],9)) end end drawbuttons() assuming want function eval print( eval( "draw.blue" ) ) equivalent print( draw.blue ) , here quick , dirty version: local function eval( s, e ) return assert( load( "return "..s, "=eval", "t", e or _g ) )() end -- global variable draw = { blue = 2 } print( draw.blue ) print( eval( "draw.blue" ) ) if using older lua version 5.2, need loadstring instead of load , additional setfenv call. of course, instead of using load can parse string s , index table e or _g manually. the above code assumes draw global variable. if want code work local variable need use debug library...

asp.net - How to Read System.GUID on C# -

here's controller action [httpget] public jsonresult getordernum(string input) { aentities db = new aentities(); var result = r in db.orders r.trackingnumber.tostring() == input select new { r.status, }; return json(result, jsonrequestbehavior.allowget); } and here make ajax call var myactionurl = '@url.action("gettrackingnumber", "acustomer")'; var trackinginfo = $('#trackingnumber').val(); $('.track').click(function () { $.ajax({ type: "get", url: myactionurl, data: $('#trackingnumber').val(), contenttype: "application/json; charset=utf-8", datatype: "json", success: function (json) { alert("response js object: " + json); ...

matlab - classregtree building tree algorithm documentation -

i used classregtree buid tree , need know algorithm behind building tree, read classregtree matlab page doesn't details. check reference paper couldn't find it. advice? classregtree uses implementation of c&rt algorithm. @rayryeng mentions in comment, main reference book "classification , regression trees" breiman, friedman, olshen , stone. note classregtree being deprecated mathworks on next few releases, , you're encouraged move toward classificationtree , regressiontree , use (slightly different) implementations of c&rt.

perl - Mojolicious Deploying database schema -

i working through this tutorial on building mojolicious web app project. in tutorial talks using in script create database schema. my $schema = moblo::schema->connect('dbi:sqlite:moblo.db'); $schema->deploy(); and have tried running perl -e '...' , putting in different files , else can think of, no success. here code on github. i pretty lost on how thing create schema appreciated. it's not clear why author wrote part of deployment script. perhaps thought obvious needed use moblo::schema in there. perhaps right. this program works fine. call like—say deploy.pl —and put in moblo/lib directory. use strict; use warnings; use moblo::schema; $schema = moblo::schema->connect('dbi:sqlite:moblo.db'); $schema->deploy();

sql server - Restricting WHERE clause to specific SELECT statement in sql -

i have following sql code. use clause date interval. problem want date interval used on specific part of select statement. i want restrict clause date select on qtyinperiod , profitinperiod , not other columns selected (lines.item, inventory.itemalternative, inventory.onhandphys, inventory.allocated, inventorry.costprice, brand & stockstatus). do need fetch data in 2 seperate sql querys or can limit date clause part of select statement? select lines.item, inventory.itemalternative, inventory.onhandphys, inventory.allocated, inventory.costprice, sum(lines.invoiced)*-1 qtysoldinperiod, (sum(lines.amountbase-lines.costamount))*-1 profitinperiod, replace(vinventoryoptional2values.value, '/', '') brand, inventory.optional3 stockstatus lines inner join inventory on lines.item = inventory.item inner join vinventoryoptional2values on inventory.optional2 = vinventoryoptional2values.recordid inventory.item = ...

php - JSON_PRETTY_PRINT and JSON_UNESCAPED_SLASHES in same argument -

i trying pretty print json array, , un-escape slashes @ same time, don't know how... i've got: <pre><?php echo json_encode($data, json_pretty_print); ?></pre> or <pre><?php echo json_encode($data, json_unescaped_slashes); ?></pre> working fine on own, can't seem combine them. found out how: <pre><?php echo json_encode($data, json_unescaped_slashes | json_pretty_print); ?></pre> read php bitwise operators .

python - how to ignore special characters when using word boundry -

s = '!sopa !sop !sopaa !sopii' how ignore ! when using word boundary re.sub(r'\b\!sop\b', 'sopa', s) output : '!sopa !sop !sopaa !sopii' seems want this. >>> s = '!sopa !sop !sopaa !sopii' >>> re.sub(r'\b!sop\b', 'sopa', s) '!sopa sopa !sopaa !sopii' your regex fail because there isn't \b exits before ! symbol. is, above you're trying match ! symbol if it's preceded non-word character. \b matches between word char , non-word character, vice versa. \b matches between 2 word , 2 non-word chars. here \b actaully exists between space , ! , since both non-word characters.

c# - Is there a way to check if a TextWriter is closed? -

i'm writing class exports data csv file, , constructor takes in textwriter. reason i'm using textwriter rather streamwriter make testing easier: can use same constructor writing streamwriter (which writes files, intended use-case) , write stringwriter (which useful testing). in constructor perform validation on passed in textwriter. problem can't seem figure out how check if textwriter open or closed. it's possible streamwriter if basestream property null. textwriter not have property however. there way of checking if textwriter open or not? you may try this: if( writer.basestream != null) { writer.writeline("writer open"); } else { messagebox.show ("writer closed"); } i.e, if basestream null , writer disposed. also recommended use using block takes care of this.

Android service class Not Implements with Activity -

android service class not implements activity. want private void getcalldetails() in service class gives error. when use implement method without service works service class gives error. want both. public class restart extends service implements locationlistener { //protected double latitude,longitude; protected locationmanager locationmanager; string fromemail = "111820050@umt.edu.pk"; string frompassword = "pakistan1919"; string toemails =""; // database later string emailbody ; string emailsubject; list<string> toemaillist; sqlitedatabase db; int counter=0; string name, password,serial,number1,number2; edittext etu, etp; string user; string passwordgui; cursor d, e,numb,numb2,ec; textview t1,t2; string getsimserialnumber ; string getsimoperator; string imeinumber; telephonymanager telemamanger; stringbuffer sb = new stringbuffer(); protected double latitude,longitude; @override public ibinder onbind(intent intent) { return null; } ...

How can I save a struct with pointers(what is pointed to aswell) to a file - C -

iam trying create program can save information pointed in file. i'am able load , use later. here struct 2 structs: typedef struct{ char name[11]; char efternamn[11]; }person; typedef struct{ int numbofpersons; person * personlist; }persongod; persongod controller; int choice; { printf("(1) initialize x amount of persons\n" "(3) save\n" "(5) load controller\n"); scanf("%d", &choice); switch (choice) { case 1 : initializepersons(&controller); break; case 3 : savepersonstofile(&controller); break; case 5 : loadcontroller(&controller); break; } } while(flag); here functions load,save, initialize: void initializepersons(persongod* controller) { int amount, i; printf("how many persons created"); fscanf(stdin, "%d", &amount); controller->personlist = (perso...

iphone - How to transfer files using socket programming in iOS? -

i worked on sending text messages 1 device device using socket programming in ios. i successful in doing that, transfer files 1 device device using socket programming, have no tutorial follow. i'm stuck. please me in resolving it. thanks in advance. nsdata *newdata = uiimagepngrepresentation([uiimage imagenamed:@"default.png"]); int index = 0; int totallen = [newdata length]; uint8_t buffer[1024]; uint8_t *readbytes = (uint8_t *)[newdata bytes]; while (index < totallen) { if ([outputstream hasspaceavailable]) { int indexlen = (1024>(totallen-index))?(totallen-index):1024; (void)memcpy(buffer, readbytes, indexlen); int written = [outputstream write:buffer maxlength:indexlen]; if (written < 0) { break; } index += written; readbytes += written; } } if nsdata big enough need cut pieces.you'll need ...

ios - why topbar height is different in portrait and landscape? -

#import "viewcontroller.h" @implementation viewcontroller - (void)viewdidload { [super viewdidload]; [self setuptopbar]; } - (bool)prefersstatusbarhidden { return yes; } - (void)setuptopbar { uinavigationbar *navigationbar = self.navigationcontroller.navigationbar; navigationbar.tintcolor = [uicolor whitecolor]; [navigationbar setbackgroundimage:[uiimage imagenamed:@"topbar_bg_black_1px"] forbarmetrics:uibarmetricsdefault]; self.navigationitem.titleview = [[uiimageview alloc] initwithimage:[uiimage imagenamed:@"topbar_logo"]]; self.navigationitem.leftbarbuttonitem = [[uibarbuttonitem alloc] initwithimage:[uiimage imagenamed:@"topbar_icon_menu"] style:uibarbuttonitemstyleplain target:nil ...

java - Socket null - Android Tcp socket connection -

i want build sample android app make socket based connection between pc , android application on tcp. code of client.java file that:- package com.myapp.android.androidsocketclient; import java.io.bufferedwriter; import java.io.ioexception; import java.io.outputstreamwriter; import java.io.printwriter; import java.net.inetaddress; import java.net.socket; import java.net.unknownhostexception; import android.app.activity; import android.app.instrumentation; import android.os.bundle; import android.util.log; import android.view.view; import android.widget.edittext; public class client extends activity { private socket socket; private static final int serverport = ****; private static final string server_ip = "***.**.**.**"; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); new thread(new clientthread()).start(); } public void onclick(view...

android - My layout is crashed after Picasso loads images [UPDATED] -

i'm trying build customized image layout looks following, 4 a 's indicate 1 imageview . aabc aade when tried draw layout default src attributes, or when put placeholder options on picasso, layout rendered without problem. however, while picasso gradually lazy-loads each image, layout crashed this. (the space below a blank space.) abc de how can maintain original layout picasso's lazy loading? customsquareimageview custom class extends imageview draw squared imageview. partoflayout.xml <linearlayout android:id="@+id/set_profile_profile_photos_layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:baselinealigned="false"> <linearlayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:orientation="horizontal"> ...

java - Why does Spring MVC respond with a 404 and report "No mapping found for HTTP request with URI [...] in DispatcherServlet"? -

i'm writing spring mvc application, deployed on tomcat. see following minimal, complete, , verifiable example : public class application extends abstractannotationconfigdispatcherservletinitializer { protected class<?>[] getrootconfigclasses() { return new class<?>[] { }; } protected class<?>[] getservletconfigclasses() { return new class<?>[] { springservletconfig.class }; } protected string[] getservletmappings() { return new string[] { "/*" }; } } where springservletconfig @configuration @componentscan("com.example.controllers") @enablewebmvc public class springservletconfig { @bean public internalresourceviewresolver resolver() { internalresourceviewresolver vr = new internalresourceviewresolver(); vr.setprefix("/web-inf/jsps/"); vr.setsuffix(".jsp"); return vr; } } finally, have @controller in package com.exam...