Posts

Showing posts from March, 2010

What .Net object corresponds to an IronRuby hash -

i want call c# method ironruby script results in ruby hash. tried dictionary stays is. public dictionary<string, string> gethash() { dictionary<string, string> hash = new dictionary<string, string>(); hash.add("a", "1"); hash.add("b", "2"); return hash; } i'd able use in ironruby script hash myhash = scopeobj.gethash() myhash.each{ |k,v| print("#{k}=#{v}") } the results of are: [a, 1]= [b, 2]= it doesn't work since items in .net dictionary keyvaluepair instances. you can workaround pretty easily, single line of conversion code: d = scopeobj.get_hash h = hash[*d.collect { |x| [x.key,x.value] }.flatten] h.each { |k,v| puts k,v }

jquery - How to select two columns data from the table? -

i using datatable plugin . i select 2 columns of table , array further processing. from $.post() call json in following form: {"secho": 26, "itotalrecords": 26, "itotaldisplayrecords": 10, "aadata": [[ "20090301","60"], [ "20090302","253"], [ "20090303","108"], [ "20090304","166"], ... [snip] ... [ "20090327","209"], [ "20090328","452"], [ "20090329","450"], [ "20090330","143"] ], "aocolumns": [{"stitle": "the observed date"}, {"stitle": "number of objects"} ] } then show table as: $('#querytable').datatable(jsondata); where <table class="display" id="querytable"...

architecture - What's the difference between REST & RESTful -

what's difference between rest system , system restful? from few things i've read called rest services restful services. difference between two. representational state transfer (rest) style of software architecture. described in dissertation roy fielding, rest "architectural style" exploits existing technology , protocols of web. restful typically used refer web services implementing such architecture.

javascript - How to detect the installed Chrome version? -

i'm developing chrome extension , i'm wondering there way can detect version of chrome user using? get major version of chrome integer: function getchromeversion () { var raw = navigator.useragent.match(/chrom(e|ium)\/([0-9]+)\./); return raw ? parseint(raw[2], 10) : false; } i've updated original answer, not throw exception in other browsers, , not use deprecated features. you can set minimum_chrome_version in manifest not let users older versions install it.

debugging - Is there a step-through debugger for Haskell? -

is there step-through debugger or similar haskell? ghci has included debugger: http://www.haskell.org/ghc/docs/6.12.2/html/users_guide/ghci-debugger.html dons wrote nice introductory tutorial time ago: http://donsbot.wordpress.com/2007/11/14/no-more-exceptions-debugging-haskell-code-with-ghci/ there's hood, lets observe intermediate structures: http://hackage.haskell.org/package/hood some older projects, such hat, seem have fallen bitrot/off internet. note -- above packages text-based , platform independent.

php - SQLite update is replacing fields with null values -

okay ive been reading on , working sqlite (someone on here suggested actually). it works great need - in-memory database. problem having duplicate records in here wanted insert record if exists fill in missing fields. now first method tried setting id primary key , insert or replace into. issue previous contents being wiped out. so im doing update query. im them checking number of rows changed. if below 1 run insert query (if there better way share know has overhead). anyway issue (finally).. update query records being overwritten null values. ive condensed snippets of code below: $stmt1 = $db->prepare("update results set field1=?, field2=?, field3=? id=? "); $stmt1->execute(array( $elm['content1'], $elm['content2'], $elm['content3'], $elm['id'] )); $count = $stmt1->rowcount(); if ($count < 1) { $stmt2 = $db->prepare("insert results (id, field1, fie...

css - html lists with specific characters? -

is there way style unordered list using greater symbol or symbol choose? \> 1 \> 2 \> 3 ♦ 1 ♦ 2 ♦ 3 without use of url()? use li:before <style> ul { list-style: none; } li:before { content: '> '} </style> <ul> <li>xyz</li> </ul>

Extract text from PDF(I have link to PDF) in ruby -

i have link like http://www.downloads.com/help.pdf i want download this, , parse text content. how go this? plan tag-ize(if there word that) extracted text you can either use pdf-reader gem (the example/text.rb example simple , worked me): https://github.com/yob/pdf-reader or command-line utility pdftotext.

ios - i want to detect previous Touch as well as current touch in the pangesture targetAction Method -

i want in pan gesture application detect previous touch current touch in every time targetaction method call [location in view] , [previous location in view] save touch in instance variable every time action method gets called.

python - Posting messages in two RabbitMQ queue, instead of one (using py-amqp) -

i've got strange problem using py-amqp , flopsy module. have written publisher sends messages rabbitmq server, , wanted able send specified queue. on flopsy module not possible, tweaked adding parameter , line declare queue on _init__ method of publisher object def __init__(self, routing_key=default_routing_key, exchange=default_exchange, connection=none, delivery_mode=default_delivery_mode, queue=default_queue): self.connection = connection or connection() self.channel = self.connection.connection.channel() self.channel.queue_declare(queue) # added set queue self.exchange = exchange self.routing_key = routing_key self.delivery_mode = delivery_mode the channel object part of py-amqplib library the problem i've got it's that, if it's sending messages specified queue, it's sending messages default queue. in system expect send quite lot of messages, don't want stress...

asp.net mvc 3 - Outputting literal HTML between razor statements results in compilation error -

i have foo object, , want output: title, location so try...: @if (sometruestuff){ @foo.title, @foo.location } @if (sometruestuff){ @foo.title , @foo.location } both fail compile. however...: @if (sometruestuff){ @foo.title<span>,</span> @foo.location } ...works. is there trick missing? edit: happens inside codeblock, updated reflect this. you escape , using @: because razor parser considers part of server side code , if want output comma in html needs escaped: @if (sometruestuff){ @foo.title@:, @foo.location }

Array of C structs -

if create struct in c , want add them array not set fixed size, how array created? can 1 create tempstruct used on every iteration while getting user input , store in array, using same tempstruct struct in loop? how array created if size unknown depends on user input, , how structs added array? when size unknown @ compile time, you'll need allocate memory on heap, rather in data segment (where global variables stored) or on stack (where function parameters , local variables stored). in c, can calling functions malloc. mystructtype *myarray = (mystructtype *)malloc(numelements * sizeof(mystructtype) ... ... free(myarray) if you're actully using c++, it's better use new[] , delete[], e.g. mystructtype *myarray = new mystructtype[numelements] ... ... delete [] myarray note new[] must paired delete[]. if you're allocating single instance, use new , delete (without "[]"). delete[] , delete not equivalent. also, if you're using c++,...

Can I install IIS on Windows 7 home basic? -

i have genuine windows 7 home basic on dell laptop. iis isn't getting installed here. is version of windows 7 can support? if yes, please let me know how can installed on os? i think iis express should work. new version of iis development shipped mvc3. http://weblogs.asp.net/scottgu/archive/2010/06/28/introducing-iis-express.aspx

Update missed calls notification on android -

i need cancel missed calls notification number. i've seen notificationmgr class on com.android.phone i'm unable call trough reflection. there other way? the code below cancel missed call notification. to method work correctly, must gain modify_phone_state permission in androidmanifest.xml like <uses-permission android:name="android.permission.modify_phone_state"></uses-permission> in androidmanifest.xml string log_tag = "log"; try { class servicemanagerclass = class.forname("android.os.servicemanager"); method getservicemethod = servicemanagerclass.getmethod("getservice", string.class); object phoneservice = getservicemethod.invoke(null, "phone"); class itelephonyclass = class.forname("com.android.internal.telephony.itelephony"); class itelephonystubclass = null; for(class clazz : itelephonyclass.getdeclaredclasses()) { ...

java - JUnit Rule TemporaryFolder -

i'm creating temporaryfolder using @rule annotation in junit 4.7. i've tried create new folder child of temp folder using tempfolder.newfolder("somefolder") in @before (setup) method of test. seems though temporary folder gets initialized after setup method runs, meaning can't use temporary folder in setup method. correct (and predictable) behavior? this problem in junit 4.7. if upgrade newer junit (for example 4.8.1) @rule have been run when enter @before method:s. related bug report this: https://github.com/junit-team/junit4/issues/79

c# - What algorithm is used in this code? -

this code checks , unchecks child nodes of treeview control. algorithm used in code? private int _callcountup; private int _callcountdn; private void tvwpermissions_aftercheck(object sender, system.windows.forms.treevieweventargs e) { bool anychecked = false; if (_callcountdn == 0 && e.node.parent != null) { anychecked = false; foreach (treenode childnode in e.node.parent.nodes) { if (childnode.checked) { anychecked = true; break; } } _callcountup += 1; if (anychecked) e.node.parent.checked = true; _callcountup -= 1; } if (_callcountup == 0) { foreach (treenode childnode in e.node.nodes) { _callcountd...

Loading javascripts in ajax callbacks -

situation: send ajax request returns html containing elements needing event handlers set on them. code sets handlers these elements contained in separate javascript file. i have been using following code load required js files on callback scripting <head > tag. have not had problems far, wondering if safe , reliable approach (especially cross-browser). function ajax_callback(response) { document.getelementbyid('dom_id_to_update').innerhtml = response; import_js('/path/to/js/file/'); } function import_js(src) { var scriptelem = document.createelement('script'); scriptelem.setattribute('src',src); scriptelem.setattribute('type','text/javascript'); document.getelementsbytagname('head')[0].appendchild(scriptelem); } thanks, brian yup. can remove script element after adding (though may want keep around avoid re-loading later — e.g., looking @ script tags in head ); apparently act o...

Where to put the default destroy in the jQuery UI 1.8.1 widget's destroy function -

ok, i'm having slight bit of confusion writing own jquery ui widget plugins. problem lies in destroy function. in docs, says put default destroy first write other things particular widget after it. $.widget.prototype.destroy.apply(this, arguments); // default destroy // other stuff particular widget see http://jqueryui.com/docs/developer_guide however in example scripts (those being actual pluings jquery ui released code, opposite. $.widget.prototype.destroy.apply(this, arguments); is @ end of function. see http://dev.jqueryui.com/browser/trunk/ui/jquery.ui.progressbar.js (and of other built in widgets well) so it? way current widgets written, or explanation in code comment in developer_guide? i put @ end, in case crazy happens, make sure you've created gets destroyed, let base methods work. practical standpoint? it doesn't matter it's matter of taste, , in 2 examples linked, taste of developers writing them differed (or changed on t...

c++ - Is there any standard delete functor? -

i looking functor deletes argument: template<class t> struct delete_functor { void operator()(t* p) { delete p; } }; is there in std , tr1 or boost ? c++0x add std::default_delete standard library support std::unique_ptr . it has same functionality delete_functor , specialized call delete[] array type objects.

networking - disconnect dialup from php -

i have application client , asks me retry internet connection in order host acquire new ip. problem is, can't find way disconnect , connect again internet connection using php. ideas? you'd have have php installed on machine execute external program bounce modem. quick google search found this . or similar might come in handy. of course, apache account have have sufficient permissions able affect modem , execute program.

ruby on rails - I have an incorrect asset_host, but can't change it -

in console, development mode: actioncontroller::base.asset_host => 192.168.2.55 which happens previous dhcp address. i checked: rails_root/config/environments/development.rb rails_root/config/environment.rb ... , there nothing set here. if add config.action_controller.asset_host = "http://127.0.0.1" to development.rb, old dhcp address. i've tried clearing browser caches, name server caches, out of ideas. the culprit rails_root/config/facebooker.yml callback_url: http://192.168.2.55

java - Google App Engine - Uploading blobs and authentication -

(i tried asking on gae forums didn't answer trying here.) currently upload blobs, app engine's blob store service creates unique one- time url user can post blobs to. requirement want authenticated / authorized users post blobs in application. can achieve if page includes multipart form upload blobs in application. however, looking providing "rest api" users upload blobs. while true one-time nature of upload url mitigates chances of rogue use it's still possible. i wondering if there on app engine team here can consider feature developers can register upload listener. (or if there way, i'll ears). standard servlet filter potentially job. give opportunity authenticate / validate / decorate requests before request gets forwarded blob store service. thanks, keyur since, point out, it's possible upload blobs if have valid upload url, can issue valid upload urls authorized users. way unauthorized user upload url if authorized user gave them...

what is GWT as compared to jquery -

is gwt same jquery framework or different. i mean use jquery ajax things. there reason shift gwt take @ developing google web toolkit . quote: the gwt sdk provides set of core java apis , widgets. these allow write ajax applications in java , compile source highly optimized javascript runs across browsers, including mobile browsers android , iphone. constructing ajax applications in manner more productive higher level of abstraction on top of common concepts dom manipulation , xhr communication. you aren't limited pre-canned widgets either. can browser's dom , javascript can done in gwt, including interacting hand-written javascript. reading this, know write gwt applications in java. drastically different javascript (or jquery, matter). how work? write code in java , gwt compiler spits out optimized javascript told when wrote java code. jquery different, since framework/library build atop javascript , it...

Clojure: returning a vector from an anonymous function -

i wrote small anonymous function used map call. function returns vector containing column name , column value sql result set query. here function (input column name): (fn [name] [(keyword name) (.getobject resultset name)]) this works fine, when tried use "simplified" version of anonymous function, got error: #([(keyword %) (.getobject resultset %)]) java.lang.illegalargumentexception: wrong number of args (0) passed to: persistentvector here map call: (into {} (map (fn [name] [(keyword name) (.getobject resultset name)]) column-names)) is possible use simplified syntax function? if so, how? thanks. your problem simple syntax trying evaluate vector function call. you can insert "identity" function make work, simple function return vector unchanged: #(identity [(keyword %) (.getobject resultset %)])

python - How to draw a line of characters in a grid (nested lists) -

given w x h sized grid, produced in following way self.grid = [ ['-'] * self.w ] * self.h i wish "draw" "line" of characters between 2 points in said grid. following code i've come with def line( self, char, (x1, y1), (x2, y2) ): self.point( char, (x1, y1) ) x = x1 + cmp( x2, x1 ) y = y1 + cmp( y2, y1 ) while x != x2 or y != y2: self.point( char, (x, y) ) x = x + cmp( x2, x ) y = y + cmp( y2, y ) self.point( char, (x2, y2) ) where point() function fills in single point in grid char . this works charm straight lines , perfect diagonals. works "crooked" lines too, in sense doesn't throw errors, doesn't line between 2 points, more like... don't know, hockey stick. for example, given 10x7 grid , call line( 'x', (1,1), (5,9) ) i get ---------- -x-------- --x------- ---x------ ----x----- -----xxxxx ---------- what i'd more like ---------- -x-------- ---x...

Set bounds for markers generated by jQuery table loop? -

i have jquery code goes through table of location results , puts corresponding pins on map. having trouble figuring out how set bounds when goes through loop , generates markers on map zooms , pans fit markers in view. i've tried implementing code similar questions on site nothing seems working. please let me know code should using , heck should put in script: $(function() { var latlng = new google.maps.latlng(44, 44); var settings = { zoom: 15, center: latlng, disabledefaultui: false, maptypeid: google.maps.maptypeid.roadmap }; var map = new google.maps.map(document.getelementbyid("map_canvas"), settings); $('tr').each(function(i) { var the_marker = new google.maps.marker({ title: $(this).find('.views-field-title').text(), map: map, clickable: true, position: new google.maps.latlng( parsefloat($(this).find('.views-field-latitude...

c++ - Global variable has multiple copies on Windows and a single on Linux when compiled in both exec and shared libaray -

* question revised (see below) * i have cpp file defines static global variable e.g. static foo bar; this cpp file compiled executable , shared library. executable may load shared library @ run time. if on linux there seem 2 copies of variable. assume 1 comes executable , 1 shared library. other platforms (hp, windows) there seems 1 copy. what controls behavior on linux , can change it? example there compiler or linker flag force version of variable shared library same 1 executable? * revision of question * thanks answers far. on re-examining issue not problem stated above. static global variable above indeed have multiple copies on windows, no difference see on linux. however , have global variable (not static time) declared in cpp file , extern in header file. on windows variable has multiple copies, 1 in executable , 1 in each dll loaded up, , on linux has one. question difference. how can make linux have multiple copies? (the logic of program meant value of ...

ruby on rails 3 - ActiveRecord Associations: Any gotchas if has_many WITHOUT corresponding belongs_to? -

a phone has many messages. an email address has many messages. a message either belongs phone, email, or neither. belongs_to association optional. the following associations seem work fine these relationships: phone model has_many :messages email model has_many :messages message model not have belongs_to :phones, :email is okay or there proper way specify "can_belong_to" relationship? it correct unidirectional relation. using both called "curcular dependency" purists , may cause problems when using validates_associated . from other side using has_many :messages may not enough when want retrieve phone information 1 message. matter of convenience.

php - How to specify a base address when opening a link which uses relative addresses -

how can php 5.2.9 open link , specify base uri (?) link's relative addresses css file , other files work ? i tried: $link = mysql_result($array,0,2); // eg 'https://xyz.net/login' $directory = dirname($link); chdir($directory); readfile($link); unlink($link); but login page can't find css file @ relative address

java - Using color and color.darker in Android? -

okay, have integer variable in application. it's value of color, being set color picker in preferences. now, need use both color , darker version of color might be. now know in standard java there color.darker() method, there doesn't seem equivalent in android. know of equivalent or workarounds? the easiest, think, convert hsv, darkening there, , convert back: float[] hsv = new float[3]; int color = getcolor(); color.colortohsv(color, hsv); hsv[2] *= 0.8f; // value component color = color.hsvtocolor(hsv); to lighten, simple approach may multiply value component > 1.0. however, you'll have clamp result range [0.0, 1.0]. also, multiplying isn't going lighten black. therefore better solution is: reduce difference 1.0 of value component lighten: hsv[2] = 1.0f - 0.8f * (1.0f - hsv[2]); this entirely parallel approach darkening, using 1 origin instead of 0. works lighten color (even black) , doesn't need clamping. simplified to: hsv[2] = 0.2f...

repository - Working offline with SVN on local machine temporary -

i working on project on svn. not have access internet few days, , working on project. is there way make clone of repository on local machine, commit changes it, , when gain access internet "push" them onto shared repository? thinking in terms of mercurial here, worth migrating completely?! your problem sounds me the use case git-svn : set git repo: git svn clone http://svn.example.com/project/trunk while being online, commit changes svn before going offline, git svn rebase git repo in sync svn repo while being offline, commit git repo using git commit when getting online again, git svn dcommit push changes svn repo i'm using workflow daily! you 2 huge advantages doing so: your complete svn history backed in git repo , in every git repo gets cloned one while being offline, can view commit messages, checkout other branches, etc.

php - Local/Dev/Live deployment - best workflow -

situation we our little company 3 people, each has localhost webserver , projects (previous , current) on 1 pc network shared disk. have virtual server, of our clients' sites , our site. our standard workflow is: coder pc → programmer localhost → dev domain (client.company.com) ↓ live version (client.com) it happens, there 2 or 3 guys working on same projects @ same time - 1 on dev version, 2 on localhost. when finished, try synchronize files on dev version , ideally not mess ( thanks ilmv :] ) files, **knock knock* * doesn't happen often. and 1 of deploys dev version on live webserver. question we looking way simplify workflow while updating websites - ideally sort of diff uploader or vcs (git/svn/vcs/...), not sure begin or way ideal, therefore ask you, fellow stackoverflowers experience website / application deployment , recommended workflow. we need use mac in process, if won...

asp.net mvc - RESTful Controllers with Different Http Methods, But the Same Parameters -

let's have controller handles crud scenario 'home'. this: [httpget] public actionresult index(int? homeid) { home home = homerepo.gethome(homeid.value); return json(home, jsonrequestbehavior.allowget); } so far good. add post action adding new ones. [httppost] public actionresult index(home home) { //add new home db return json(new { success = true }); } awesome. when use same scheme handle puts (updating existing home)... [httpput] public actionresult index(home home) { //update existing home in db return json(new { success = true }); } we run problem. method signatures post , put identical, of course c# doesn't like. try few things, adding bogus parameters signature, or changing method names directly reflect crud. hacky or undesirable, though. what best practice going preserving restful, crud style controllers here? this best solution know of: ...

url rewriting - Rewrite only URLs that don't exist -

i'm looking way rewrite urls if path doesn't exist. isn't handle 404s, redirect page urls shared php file (ie: '/contact-us/' -> '/show_page.php?page=contact-us') . the basic redirect easy enough achieve, want able override default page adding /contact-us/index.php in site root. is achievable mod_rewrite or have else? just check value of request_filename variable: rewritecond %{request_filename} !-f rewritecond %{request_filename} !-d rewriterule ...

c# - Any in-built method to only know if two lists are different? -

i have compare 2 lists , only know if contain same values or not. not intend differences. what best way achieve in c#? i know can loop lists want know if theres in-built linq/extenstion method achieve provides better performance. did try except/intersect, don't know if suitable ones achieve this. update: lists won't have duplicates within them. how want handle duplicates? example, count { 2, 1, 1 } being same { 1, 2 }? (i'm assuming order irrelevant... otherwise use sequenceequal .) assuming care "sets" effectively, here 2 options: a quick , dirty way: if (!list1.except(list2).any() && !list2.except(list1).any()) a cleaner way: var set = new hashset<int>(list1); // adjust case accordingly if (set.setequals(list2)) { // lists equal } one thing consider: if you're interested in treating them sets, might want use set representation start with, instead of list...

indexing - first character count navigation with Oracle: count queries dont't use functional indices -

oracle 9i. have large table (~1m rows) containing our content carries title , author columns. we'd write views offer a-z navigation titles , authors content ( a:1300, b:45000,...) first preparation without indexing: select * content substr(upper(title),0,1) = 'm' performs little better than select * content upper(title) 'm%' explan those: table access content full cost=1624 both pretty fast without indices. slow part: select count(*) content substr(upper(title),0,1) = 'a'; explan: sort aggregate else above. now cumulation (this want, it's slow): select substr(upper(title),0,1) , count(*) content group substr(upper(title),0,1); explan: sort: group cost=8069 / table access on content full cost=1624 so started creating functional index: create index content_title_letter_idx on content(substr(upper(title),0,1)); this speeds single letter count query dramatically: select count(*) content substr(upper(title),0,1) = '...

Android Emulator vs phone opengl inconsistensies -

i'm having problem application looks right on emulator, on phone displays fragment of scene. images here (the emulator 1 on right. my renderer code seen here. (this class abstract implementing class doing draw polygons) public abstract class abstractrenderer implements renderer { float x = 0.5f; float y = 1f; float z = 3; boolean displaycoordinatesystem = true; public void onsurfacecreated(gl10 gl, eglconfig eglconfig) { gl.gldisable(gl10.gl_dither); gl.glhint(gl10.gl_perspective_correction_hint, gl10.gl_fastest); gl.glclearcolor(.5f, .5f, .5f, 1); gl.glshademodel(gl10.gl_smooth); gl.glenable(gl10.gl_depth_test); } public void onsurfacechanged(gl10 gl, int w, int h) { gl.glviewport(0, 0, w, h); float ratio = (float) w / h; gl.glmatrixmode(gl10.gl_projection); gl.glloadidentity(); gl.glfrustumf(-ratio, ratio, -1, 1, 0, 10); } public void ondrawframe(gl10 gl) { gl.gldisable(gl10.gl_dither); gl.glclear(gl10.gl_color_buffer...

latex - How to include multiple tables programmatically into a Sweave document using R -

i want have sweave document include variable number of tables in. thought example below work, doesn't. want loop on list foo , print each element it's own table. % \documentclass[a4paper]{article} \usepackage[ot1]{fontenc} \usepackage{longtable} \usepackage{geometry} \usepackage{sweave} \geometry{left=1.25in, right=1.25in, top=1in, bottom=1in} \listfiles \begin{document} <<label=start, echo=false, include=false>>= startt<-proc.time()[3] library(rodbc) library(psych) library(xtable) library(plyr) library(ggplot2) options(width=80) #produce example data, here i'm creating dummy dataframes , putting them in list foo<-list() foo[[1]]<-data.frame(grp=c(rep("aa",10), rep("aa",10), rep("aa",10)), x1=rnorm(30), x2=rnorm(30,5,2)) foo[[2]]<-data.frame(grp=c(rep("bb",10), rep("bb",10), rep("bb",10)), x1=rnorm(30), x2=rnorm(30,5,2)) foo[[3]]<-data.frame(grp=c(rep("cc",12), rep(...

sql - C# Access Database Question -

say have 2 tables now, priceplan , bill. both tables have column called 'price' , table 'bill' update value 'priceplan's price. how can or sql statement should using? in advance! you need have sort of way define relationship between 2 tables. for instance if tables have structure: priceplan --------- id price bill --------- priceplanid price this work sql server. see below access solution. then query should update bill : update b set b.price = pp.price bill b inner join priceplan pp on b.priceplanid = pp.id also, schema above example purposes. if yours should @ changing it. update i noticed access, sorry. strucure of query different. see below: update bill inner join priceplan on bill.priceplanid = priceplan.id set bill.price= [priceplan].[price];

php - Parse error: syntax error, unexpected T_FUNCTION line 10? -

what wrong code? ran code on test server , code worked when upload production server parse error: syntax error, unexpected t_function in /hermes/bosweb/web013/b130/ipg.acrsflcom/darayngedbeats/gentest.php on line 10 here code $old = "http://darayngedbeats1.s3.amazonaws.com /mp3/crazymonsta2.mp3?awsaccesskeyid=akiajxa36esclqhcb54q&expires=1297279906& signature=hd36zqe8yetiw6jpwkmcciptits%3d"; //enter key needs converted $search = array(":","?","=","&","%"); $replace = array("%3a","%3f","%3d","%26","%25"); function search_replace($s,$r,$sql) { $e = '/('.implode('|',array_map('preg_quote', $s)).')/'; $r = array_combine($s,$r); return preg_replace_callback($e, function($v) use ($s,$r) { return $r[$v[1]]; },$sql); } echo "<br><br>"; $new = search_replace($search,$replace,$old); echo $new; ?...

actionscript 3 - Garbage collection, camera and video object -

how clean after i've finished using camera object , video object? do write: _camerainstance = null; _videoinstance = null; you need remove event listeners have associated camera , video objects , detach camera video _videoinstance.attachcamera(null) .

ruby on rails - vestal_versions and htmldiff question of reversion -

i'm guessing there's easier way i'm doing code less unwieldy. i had trouble understanding how use revert_to method... wanted call 2 different versions @ same time, doesn't seem way vestal_versions works. this code works, i'm wondering if i'm making harder needs , i'd find out before delve deeper. @article = article.find(params[:id]) if params[:versions] v = params[:versions].split(',') @article.revert_to(v.first.to_i) @content1 = @article.content @article.revert_to(v.last.to_i) @content2 = @article.content end in case you're wondering, i'm using in conjunction htmldiff version changes. <div id="content"> <% if params[:versions] %> <%= article.diff(@content1, @content2) %> <% else %> <%= @article.content %> <% end %> </div> i think looking changes_between method vestal_versions provides. @article = article.find(params[:id]) if params[:versio...

.net - Is FileStream the safest way to copy a file vs. File.Copy? -

i copy file source destination directory. heard best filestream in case gets modified later / accessed later. i using c# 2.0 , .net 2.x. i don't need determine if file open or not or read/write or not. need copy is, have determined file has stopped growing (check every 4 seconds) 'good enough' in situation. so should use memorystream or filestream or file.copy(..) , how? use: file.copy(..) how: see documentation. also, recommend checking out path class.

unix - Command passed as argument to shell script -

i want pass command shell script. command grep command. while executing getting following errors, please help: myscript.sh "egrep 'error|fatal' \*20100428\*.log | grep -v astring" myscript.sh simple script: #!/bin/ksh cd log $1 the errors are: egrep: can't open | egrep: can't open grep egrep: can't open -v egrep: can't open astring error because egrap sees |, grep, -v , astring arguments. try this: eval $1

java - how to Update JTable -

good evening i have jtable built tablemodel how update elements of table, because when table = new jtable (new tableprog (elementtab)) create table above original table , ugly so example how update element of table in loop @ each iteration "elementtab" changes? thank much i recommend extend abstracttablemodel , implement void addrow(yourobject row) fits you. or if want update hole tables data, implement void addelements(yourcollection elements) , use void firetabledatachanged() -method. i.e. keep data in linkedlist , don't forget use void firetablerowsinserted(int firstrow, int lastrow) when add new row.

coldfusion - How do I unhide a CFDIV that has dynamic content with AJAX binding itself? -

i have following cfselect tags used populate text input: <cfselect id="this" name="this" bind="cfc:data.getthis()" bindonload="true" /> <cfselect id="that" name="that" bind="cfc:data.getthat({p1})" /> <cfselect id="theother" name="theother" bind="cfc:data.gettheother({p1}, {p2})" /> the text input value needs submitted in form: <cfform name="additem" method="post" action="somepage.cfm"> <cfinput type="text" id="item" name="item" bind="cfc:data.getresult({this}, {that}, {theother})" /><br /> <cfinput type="submit" name="addbutton" value="add item" /> </cfform> i want form , it's contents visible only when 3 selections have been made, , there value text i...

ruby on rails - Extra <to_s/> when using builder to generate XML -

i'm trying generate kml using builder. know options out there doing 2.2 specific things aren't supported kml gems i've looked @ , able accomplish leveraging xml framework. i tag @ end of file when rendering kml/xml. suspect i'm missing basic setting builder object or how i'm rendering output it. here's simple example demonstrates issue: def kml2dot2 @site = site.find(params[:id]) xml = builder::xmlmarkup.new(:indent => 2) xml.instruct! xml.kml("xmlns" => "http://www.opengis.net/kml/2.2") { xml.placemark xml.name @site.mapnamefull xml.point xml.coordinates @site.lat.to_s + "," + @site.lng.to_s + ",0" end end } render :text => xml, :type=>"text/kml" end produces: <?xml version="1.0" encoding="utf-8"?> <kml xmlns="http://www.opengis.net/kml/2.2"> <placemark> <name>seattle city hall<...

Grails exploded under tomcat -

is there way use grails in "exploded" mode on tomcat in order make individual changes in running application (like gif) without having regenerate entire war , upload ? something adding xml file in tomcat's conf/catalina/localhost points exploded grails application ? thanks in advance. not sure mean here, tomcat explode war when detects new one, in case modify files directly in exploded directory. wouldn't recommend though once upload new version of war of changes lost.

c# - Determine if (x,y,z) point is inside a shape defined by an array of points -

if have array of points (x,y,z) , given single point (x,y,z), code use determine if point resides within shape defined array? i drawing blank on one... i'm using c# edit thanks responses guys, comments have found link ( http://alienryderflex.com/polygon/ ) explains process quite well. thanks! fyi: bool pointinpolygon() { int i, j=polysides-1 ; boolean oddnodes=no ; (i=0; i<polysides; i++) { if (polyy[i]<y && polyy[j]>=y || polyy[j]<y && polyy[i]>=y) { if (polyx[i]+(y-polyy[i])/(polyy[j]-polyy[i])*(polyx[j]-polyx[i])<x) { oddnodes=!oddnodes; }} j=i; } return oddnodes; } it'll need work, thats guts of it. thanks again use point know outside shape, , check if line point given point passes through surfaces of shape. if passes through odd number of surfaces, given point inside shape.

xcode - Writing and reading text files on the iPhone -

as practice, trying write app similar built-in notes app. cannot figure out how save file , display in uitableview . right now, have uitextview user can type in. have save button. when user taps save button, want save it, , later have displayed in table view. lost if know of relevant tutorials etc. appreciated. as noted commenters in real world, you're going want @ core data or other data persistence strategy. if you're dead set on pursuing learning experience, should solve problem: - (void)writestringtofile:(nsstring*)astring { // build path, , create if needed. nsstring* filepath = [nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes) objectatindex:0]; nsstring* filename = @"mytextfile.txt"; nsstring* fileatpath = [filepath stringbyappendingpathcomponent:filename]; if (![[nsfilemanager defaultmanager] fileexistsatpath:fileatpath]) { [[nsfilemanager defaultmanager] createfileatpath:fileat...

asp.net mvc - Web.Config issue with Unit Testing -

i trying unit test lot of mvc controllers, unfortunately keeps failing because needs lot of settings web.config.. which copied on not read it, i'm needing membership , rolemanager can't add app.config either, i've been able connection strings , application settings work with.. any idea how web.config work mstest? mock http://www.asp.net/learn/mvc-videos/video-365.aspx

c# - Hilighting the current page in an asp.net 3.5 master page -

in project master page contains repeater that's used menu xml file data source repeater. <asp:repeater id="admin_menus" runat="server"> <headertemplate><div id="navmenu"><ul></headertemplate> <footertemplate>|</ul></div></footertemplate> <itemtemplate> |<li> <a href="<%# databinder.eval(container.dataitem, "url")%>" class="link6" id="<%# databinder.eval(container.dataitem, "id")%>"> <strong> <%# databinder.eval(container.dataitem, "title")%> </strong> </a> </li> </itemtemplate> </asp:repeater> urls in xml file <menuitems> <item id="1" url="employee.aspx" title="employee" description="employee" /> ...

sharepoint - Strange behavoir of RunWithElevatedPrivileges in Console Aplication with FBA -

i have named site collection fba on und use activedirectorymembershipprovider. we have farm administrator domain\administrator. not explicitly sitecollection administrator. i created sample console application run under domain\administrator account. in code that: using (spsite site = new spsite(serverurl)) { using (spweb web = site.openweb()) { console.writeline(web.currentuser.loginname); console.writeline(windowsidentity.getcurrent().name); string username = "domain\\testuser"; spuser spuser = web.ensureuser(username); spgroup group = web.sitegroups["groupname"]; group.adduser(spuser); group.update(); } } the console output domai...

java - Is Inheritance in Struts2 Model-Driven Action possible? -

i have model-driven struts2 action provides correct json response. when re-structure action empty json response back. has got inheritance working struts2 model-driven actions? ive tried explicitly setting include properties in struts config: <result name="json" type="json"> <param name="includeproperties"> jsonresponse </param> </result> code actions below - not actual code in use - have edited , stripped down clarity. thanks in advance. action providing correct response: public class bike extends actionsupport implements modeldriven, preparable { @autowired private service bikeservice; private jsonresponse jsonresponse; private com.ets.model.vehicle bike; private int id; public bike() { jsonresponse = new jsonresponse("bike"); } @override public void prepare() throws exception { if (id == 0) { bike = new com.ets.model.bike(); ...

c# - xval get message from resource file -

i'm working on cms system uses resource file information , errormessages from. client side validation working without problems, it's not getting errormessage resource file. while debugging figured out xval seems errormessages javascript file messages set hard-coded. there way override this? below code should make relation resourcefile en specify error when field left empty. [property] [required(errormessageresourcetype = typeof(cmsmessages), errormessageresourcename = "entervalidmoney")] public virtual double shippingcost { get; set; } xval comes bunch of message js files (in optional/internationalization folder) there appears no documentation on how use them! it looks need include <script src="..."> block after min library inluded.

viewengine - Which View Engine are you using with ASP.NET MVC?, and Why? -

i'm thinking of experimenting alternative view engines asp.net mvc, , know other people using. please let me know 1) view engine use, , 2) why. the standard 'web-forms' view engine of course valid answer, please if have decided use reason, not 'becuase can't bothered change it' ;) thank you! most of time, use 'standard' view engine - however, since mvc extensible, happens need inherit it, override little bit of functionality, , plug in. in addition, having looking @ spark view engine, particular style of making view code didn't gel me, that's no fault of theirs - different strokes different folks.

HTML + jQuery dropdown: When any other part of the page is clicked, FadeOut? -

this simple question, i'm designing html dropdown. $('#bible-trans').click(function() { $('#bible-translation-list').fadetoggle('fast'); }); where #bible-trans main dropdown button, content of dropdown #bible-translation-list . when hit main dropdown, content toggles. simple. what i'd if user hits anywhere else on page dropdown fades out. $("*").not('#bible-trans').click(function() { $('#bible-translation-list').fadeout(); }); this have right now, i'm pretty sure it's incorrect—well because doesn't work— when click toggle #bible-trans , toggles , fades away immediately. using not() selector correctly? edit: think has lot fact #bible-trans child of * (obviously). way can work through that? heres 1 way possible of doing it http://jsfiddle.net/76guj/29/ $(function(){ $(document).click(function() { if($("#anotherdiv").is(":visible")){ $(...

c# - Sending emails in asp.net with specific name instead of sender email -

i need send email in asp.net need sender appears "mysitename" without info@mysitename.comi need send email in asp.net need sender appears "mysitename" without info@mysitename.com like this: using(mailmessage message = new mailmesage( new mailaddress("you@domain.com", "your name"), new mailaddress("recipient@otherdomain.com", "their name") )) { message.subject = ...; message.body = ...; new smtpclient().send(message); } you need enter smtpclient 's connection settings in web.config

How to get the amplitude when blowing into MIC on android device -

how amplitude when blowing mic in android device. mediarecorder recorder = new mediarecorder(); recorder.setaudiosource(mediarecorder.audiosource.mic); timer timer = new timer(); timer.scheduleatfixedrate(new recordertask(recorder), 0, 1000); private class recordertask extends timertask { private mediarecorder recorder; public recordertask(mediarecorder recorder) { this.recorder = recorder; } public void run() { log.v("", "amplitude is" + recorder.getmaxamplitude()); } } i getting error: error/androidruntime(20927): caused by: java.lang.runtimeexception: setaudiosource failed. error/androidruntime(20927): @ android.media.mediarecorder.setaudiosource(native method) public boolean isblowing() { boolean recorder=true; int minsize = audiorecord.getminbuffersize(8000,audioformat.channel_configuration_mono, audioformat.encoding_pcm_16bit); audiorecord ar = new audiorecord(mediarecorder.audiosource.mic, 8...

sqlite3 - Guide for http://www.ch-werner.de/javasqlite java wrapper library for SQlite? -

i'm working on large computer science school project using java , sqlite. after finding out zentus.org wrapper errors on databases on delete , on update clauses set, have changed other wrapper found @ http://www.ch-werner.de/javasqlite . however, find documentation lacking when trying overview on how works , how use it, , function descriptions very short, , have scan through every function , guess how work , do. wasn't able find guides on google on how use it. my question: know link guide or tutorial ch-werner.de/javasqlite wrapper, or else can give me basic code example, or give quick overview of querying database , used functions, , how use them? i @ jdbc tutorial

access a file in python that is created from SunGridEngine -

i have python script, submits job sge (sun grid engine). when job done want access output file, generated sge job. see "ls" in directory file existing , job done, python needs 20-30 seconds access file... is there way detect new created files faster ?? my problem differ between "need time access file" or "file not existing" i tried: os.path.exist(path) os.access(path,os.r_ok) does not solve problem =( created sleep timer checks every second access.. after time (~15s), access granted , file usable!

webautomation - How can I display an HtmlPage object (from HtmlUnit) to be opened in a real browser? -

i using htmlunit (browser automation/testing tool) go through series of links or perform set of actions on page. @ point after want see resulting page in browser (internet explorer or firefox etc.) how can this. ? thank friends... you can use htmlpage.save(file) (which automatically saves images) before executing real browser

zend framework - ZFDataGrid table width -

Image
i'm using zfdatagrid display table within zend app. how fix width of table? can't find setting in grid.ini. public function displaytemptableaction() { $config = new zend_config_ini(application_path.'/grids/grid.ini', 'production'); $db = zend_registry::get("db"); $grid = bvb_grid::factory('table',$config,$id=''); $grid->setsource(new bvb_grid_source_zend_table(new model_dbtable_tmpteamraceresult())); //crud configuration $form = new bvb_grid_form(); $form->setadd(false)->setedit(true)->setdelete(true); $grid->setform($form); $grid->setpagination(0); $grid->setexport(array('xml','pdf')); $this->view->grid = $grid->deploy(); } it seems table width controlled via css file in folder './public/styles' td div input[type='text'] { width: 98% !important; border: 1px solid #ddd; } another nice api rubbish do...

android - Clicking Widget mistakenly causes main Activity to launch -

widget launches applications main activity unexpectedly. should not have main activity when have app hosts widget? not clear why launches, not behavior want. want no activities launch unless requested intent so? try adding android:launchmode="singleinstance" main activity's definition in manifest suggested here . <activity android:name=".youractivity" android:launchmode="singleinstance" ...

OpenGL depth buffer on Android -

i'm learning opengl es programming on android (2.1). started obligatory rotating cube. it's rotating fine can't depth buffer work. polygons displayed in order gl commands render them. during initialization of gl: gl.glclearcolor(.5f, .5f, .5f, 1); gl.glshademodel(gl10.gl_smooth); gl.glcleardepthf(1f); gl.glenable(gl10.gl_depth_test); gl.gldepthfunc(gl10.gl_lequal); gl.glhint(gl10.gl_perspective_correction_hint, gl10.gl_nicest); on surface-change this: gl.glviewport(0, 0, width, height); gl.glmatrixmode(gl10.gl_projection); gl.glloadidentity(); glu.gluperspective(gl, 45.0f, (float) width / (float) height, 0.1f, 100f); when enable backface culling looks correct. backface culling speed-optimization should work depth buffer or not? missing here? found myself. wasn't gl code, android code: view.seteglconfigchooser(false); the "false" in line explicitly says no z-buffer should allocated. after switching "true" worked perfectly. ...

html - CSS Centering a webpage problem -

i've trouble centering webpage using css: css code below: #wrapper { margin-left:auto; margin-right:auto; width: 100px; } #welcome { position:absolute; top:202px; width:560px; height:224px; z-index:2; } #newssection { position:absolute; left:576px; top:209px; width:380px; height:600px; z-index:2; } html: <body> <div id="wrapper"> <div id="welcome"> //content here </div> <div id="newssection"> //content here </div> </div> </body> i can center webpage except #newssection div. the reason why put "left:576px" under #newssection div because want place right next #welcome div.(side side) however, when shrink browser size, #newssection div move left bit , overlap #welcome div. if remove "left:57px", #newssection div appear right on top of #welcome div... please help. thanks this because youre using abs...

emacs c c++ reference document -

i using emacs c , c++ ide. i want configure emacs can read c , c++ apis (reference library) inside emacs. please let em know how it. bt i use following line in .emacs file automatically show man page c function under cursor when push f1 (of course assumes have development man pages installed): (global-set-key [f1] (lambda () (interactive) (manual-entry (current-word)))) for example on ubuntu linux system, manpages-dev , libstdc++6-4.4-doc packages contain manpages c , c++ standard libraries, respectively. similar packages exist other systems, including macosx

loops - Extract list of attributes from list of objects in python -

i have uniform list of objects in python: class myclass(object): def __init__(self, attr): self.attr = attr self.other = none objs = [myclass (i) in range(10)] now want extract list attribute of class (let's attr), in order pass function (for plotting data example) what pythonic way of doing it, attr=[o.attr o in objsm] ? maybe derive list , add method it, can use idiom like objs.getattribute("attr") ? you can write: attr=(o.attr o in objsm) this way generator conserves memory. more benefits @ generator expressions .

java - Serialize objects like Google Gson but into compact binary format? -

i'm hoping there library allows serialization of java pojos, in similar manner google's excellent gson library. however, need serialized format extremely compact (they need fit individual udp packets), , i'm concerned serializing json wasteful, , prefer binary format. is there such thing? some days ago found bson claims simple binary representation of json. did not try this, faq, not more compact json (small numbers use more space), easier (quicker) parse , produce. if have known data types transmit, other protocols more efficient (in terms of space, @ least) this.

forms - Front-End Editor for Wordpress Metaboxes -

i creating frontend editor wordpress using tdo mini forms , wondering if there way post values frontend form custom metabox? using wpalchemy metabox code. maybe 1 of these of assistance? tutorial on editing post data front end. front end editor allows editing entire post. another front end editing plugin. if you're coding yourself, here's wordpress function you'll want use. or editing meta data.