Posts

Showing posts from June, 2013

Close application and launch home screen on Android -

i have 2 different activities. first launches second one. in second activity, call system.exit(0) in order force application close, first activity automatically displayed instead of application returning home screen. how can avoid this, , application return home screen? you should think not exiting application. not how android apps work.

Exception Handling in Jsp -

how handle exception without sending error page? how set message detail exception object?(not using jstl tags) thanks, ravi not using jstl tags i going suggest c:catch , don't want use jstl, stops here. still then, have been bad idea. don't want use jsp business logic. use (indirectly) servlet this. servlets can control, preprocess and/or postprocess requests , forward request jsp file in turn displays data using el , controls page flow dynamically using taglibs <jsp:xxx> , jstl . here's basic example based on "login user" idea: protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { string username = request.getparameter("username"); string password = request.getparameter("password"); if (username == null || username.isempty() || password == null || password.isempty()) { request.setattribute("error", "please en...

submodel, subclass or subcontroller ruby on rails references -

i busy making ruby on rails app. i want make model contains text model, picture model , link model. every model can have comments, don't want make different comment models text, picture , link model. possible make media model witch has subclass(or how called) aka: picture model, text model , link model. or there other clean way this. thanks you can create comment model has polymorphic association : # comment model belongs_to :commentable, :polymorphic => true # other model should has comments has_many :comments, :as => :commentable you can add above line every model needs comments. in order have polymorphic association need have columns in comments table in db: commentable_id - int commentable_type - string you can use plugin comments, on example this .

anonymity - Personally identifying information (of the programmer) in .NET Assemblies -

when going through of applications in past, have noticed compiled assembly information such project is, username (which happened full name, not online handle) in windows, , i'm not sure else. now know primary reason of when compiled under debug, file locations source files or pdb files (can't recall which). the question is, other "personally identifiable" information can end in compiled assemblies , can done prevent ending in assembly? i assume if set project release mode disable debugging symbols in compiled assembly, achieve goal, i'm still curious if else missing. i have no issue people knowing made something, did kind of irk me full name in distributed assemblies without knowledge. depending on vs setup, it's possible might have identifying information in assembly information ( assemblyinfo.cs ). if publish via clickonce, there publish information can publish tab. both of these tags configurable. it's possible have license file...

wcf - Implement IExtensibleDataObject on a Base class -

we have several wcf services expose our domain model directly across wire. in other words, don't have layer of dtos map between our domain , service layers. have no choice directly decorate our domain objects [datacontract] , [datamember]. want implement iextensibledataobject on of our domain objects exposed on wire. sees wrong implementing iextensibledataobject on base class? have: [datacontract] public entitybase:iextensibledataobject{///iextensibledataobject impl} [datacontract] public person:entitybase{} [datacontract] public employee:person{} thanks in advance thanks matt. guess know works fine, questions more related soa design. know in oo world fine, since domain objects serving dtos i'm worried adding inheritance chain lead issues down road. else implementing iextensibledataobject? if so, implementing iextensibledataobject on datacontracts or on base class?

msbuild - Can you do parallel incremental building on a list of projects? -

Image
is possible take list of projects , parallel build them if aren't date? <target name="dependencieslevel7" dependsontargets="dependencieslevel6"> <message text="5 items build" /> <msbuild projects="c:\projects\applicationmanager.csproj;c:\projects\metrics.csproj" properties="$(customallproperties)" buildinparallel="true"> <output taskparameter="targetoutputs" itemname="built_dependencieslevel7" /> </msbuild> this example of format i'm building in, hoping able parallel build items aren't date here? perhaps internal msbuild task calls automatically parallel? if how set it's incremental based on previous build task? (target dependencieslevel6) believed incremental building have use inputs/outputs in target. question summary: is list of projects passed msbuild task automatically incremental (building skipped if build date)? if not, possible increme...

Get current frame in actionscript. What instance should I refer to? -

i'm new actionscript. i'm trying make menusystem jump specific frames depending on frame i'm on. have made switch/case evaluate current frame. have managed find code current frame need instance of entire flash movie seems? have tried (psudo code sort of). var frame = myclip.currentframe; i proceed test frame in switch/case statement. (all event mouse event listener btw). now how can refer myclip? ok, found use this.currentframe; , seems obvious right now.

What are disadvantages of JavaFX and Silverlight? -

javafx new technology introduced sun. know limitations , pitfalls of javafx , silverlight......... the main problems see javafx are: it immature technology. while everything, others have noted, must have start somewhere, javafx immature technology in field has several more mature competitors . makes difference. flex/air , silverlight out there , in active use on place. tackle entrenched market need tools far superior what's out there, not little superior (if @ all). it stacked on top of rather large jre. jre available on every major platform (and many minor ones) not ubiquitously installed. same true of flex/air , silverlight, of course, flash lighter-weight solution whole jre+javafx , latter default on target platform anyway. javafx heavily reliant upon huge infrastructure surrounds java. strength, of course, given if need there's library somewhere, weakness in involves more bloat jre+javafx , starts introduce wonderful world of jar hell. the final re...

windows mobile - WMDC not starting? -

i trying start windows mobile device center on windows 7 machine. shows me small green window shown @ loading time alt text http://img684.imageshack.us/img684/8126/wmdc.png , closed automatically. not getting problem is. i tried uninstall previous update re-installed again problem not gone. guys please me out. need debug app , submit build today. thanks, madhup have tried soft resetting device you're trying connect? have rebooted windows 7 machine you're trying connect to? can see wmdc icon in sys tray? if so, click on open wmdc , see says. go control panel -> sync center , delete existing partnership of device you're trying connect.

python - Reverse Y-Axis in PyPlot -

i have scatter plot graph bunch of random x, y coordinates. y-axis starts @ 0 , goes max value. y-axis start @ max value , go 0. points = [(10,5), (5,11), (24,13), (7,8)] x_arr = [] y_arr = [] x,y in points: x_arr.append(x) y_arr.append(y) plt.scatter(x_arr,y_arr) there new api makes simpler. plt.gca().invert_xaxis() and/or plt.gca().invert_yaxis()

php - Obtain a Blogger's blog ID from its friendly URL without screen scraping -

i'm using blogger api php . want obtain blog id site's name. for example, http://sleeptalkinman.blogspot.com/ has blog id of 3117168333067506122. possible blog id appears in source, screen scraping isn't idea! is possible obtain through api instead of scraping html? today, newest blogger api in version 3.0. new api, can blog id resource type getbyurl . full example using blog , api: https://www.googleapis.com/blogger/v3/blogs/byurl?url=http%3a%2f%2fwww.ifaniqbal.com&key=aizasydnkr52esfobzi9bpkrtytbowoam7js9uy just ctrl+c example , ctrl+v browser test that. 1 of return field of example 'id' field, blog id want (in json), this: { "kind": "blogger#blog", "id": "7107469463017369923", "name": "ifan iqbal", "description": "tips, download, resensi, tutorial, blog, blogspot", "published": "2012-02-28t23:54:48+07:00", "updated": "2013...

redirect - slow update after pipe, stout, stderr redirection and saving file at the same time -

i'm saving output of command after redirecting stdout, stderr , passing through pipe. things seem working fine i'm noticing delay in bash screen update <= 37 seconds. the same delay see when checking output file "tail -f output-ping.txt". i've never seen such delay earlier ping nor think happening cause of tee. because of numerous redirections being performed? thoughts! thanks. ping google.com 2>&1 | awk '{ print strftime("%y-%m-%d %h:%m:%s"), $0; }' | tee -a output-ping.txt i tried myself , needed flush awk stream, dropped str line, think there no problem there ping google.com 2>&1 | awk '{ print $0, fflush() }' | tee -a pepe.txt

Are there documented rendering differences between different versions of an operating system and same versions of browsers? -

i'm involved in browser-compatibility testing, , we're looking @ tools , forth. 1 thing need visual inspection of our site in range of different browsers on different oss , platforms. my question whether there documented differences (or can post html+css) page render differently in ie6 on windows 2000 in ie6 on windows xp (say). or ie7/xp vs ie7/vista. or safari4/macosx leopard vs safari4/macosx snow leopard. we're hoping able slim down count of combinations. i've seen this other question , , don't think it's quite same thing. answers direct me quirksmode.org . we're not looking breakdown of elements/css-rules supported in browsers; we've got existing site better or worse uses uses, , we'd under test able make changes more safely. you can submit http://browsershots.org/ multiple times, different os version called same browser version. not ideal solution.

php - Does cURL NOBODY actually fetch the body? -

i'm not sure if function in curl strips response body out still load fully. true? don't want waste bandwidth, want headers. curlopt_nobody send head request web server. server should respond http headers , no body content. http://www.w3.org/protocols/rfc2616/rfc2616-sec9.html the head method identical except server must not return message-body in response.

regex - Why is this simple javascript not working? -

new js here. trying detect existence of string in present page's url this: var url = window.location; var param = /\?provider=/i; if (url.search(param) != -1) { alert('it exist'); } else alert('it not exist'); it works when manually define url variable so var url = 'http://google.com?provider=' but when try grab dynamically in above script doesn't work, there way make work? you want href property on location object, this: var url = window.location.href; var param = /\?provider=/i; if (url.search(param) != -1) { alert('it exist'); } else alert('it not exist'); location isn't string, it's object, , doesn't have .search() method, .href string does.

zend framework - Zend_Form : Adding fields in sub-forms on user's click -

i'm having zend form - comprised of number of zend - sub forms, user creating new question (its content management system). in 1 of subforms, user can click on button add more textfields, this: [----------] [----------] [click add more] which should give [----------] [----------] [----------] [click add more] i'm trying set flag in sub form in question - or set count on how many times button has been clicked, add many total fields subform - not working. tried using static count variable - value doesnt incremented @ all. any thoughts on how in zend-subform within zend form? i'll update if hit solution. thanks! i used sessions store click. tried doing javascript within subform not working. if have such situation there 1 form (no subforms), javascript solution works fine. effectively, increment counter 1 onclick. sessions, or other global variable, same - increment counter, , unset var when form submitted. - when u come form, previous session var value...

model view controller - Where does input validation belong in an MVC application? -

i have mvc application receives input form. login form validation necessary check whether input non-empty. right before pass model validate in controller. best practice or not? belong model? i don't think there's official best practice limiting validation single part of mvc pattern. example, view can (and should) up-front validation using javascript. controller should offer same types of validation, more business-logic related validation. model can offer forms of validation, i.e., setters not allowing null values. there's interesting discussion of at joelonsoftware .

ruby on rails - How to return boolean result in named_scope? -

named_scope :incomplete?, lambda { |user_id, todo_id| { :select => 1, :conditions => [ "#{user_id} not in (select user_todos.user_id user_todos) , #{todo_id} not in (select user_todos.todo_id user_todos)" ] } } i'm getting nil result. want return true. gotta do!? also, there better way write this? there's huge issue code: named scopes not intended return booleans or single values, intended returns filters chained. use class method instead. also, use interpolation, don't write values directly sql code. class yourmodel def self.incomplete?(user_id, todo_id) exists?(["? not in (select user_todos.user_id user_todos) , ? not in (select user_todos.todo_id user_todos)", user_id, todo_id]) end end

Oracle - AURORA$JIS$UTILITY$ -

doing archiving/deleting of uncommonly used databases on oracle server. has heard of aurora$jis$utility$ , purppose? i believe 1 of jserv accounts created automatically when oracle servlet engine (ose) installed in old version - hasn't been supported form time (since 8i?). not sure used within though.

sql server 2005 - SQL: Convert GMT in seconds to DateTime -

i have table 2 columns of gmt time in seconds, , offset in minutes this: select top 1 starttime, offset mytable; 1247242537 -420 -- example what sql function can use convert datetime in yyyy-mm-dd hh:mm:ss timestamp? sql using sql server 2005. this should it, assuming epoch date 1/1/1970 (usually gmt seconds, need confirm) select dateadd(ss,1247242537+(-420*60),'1/1/1970') == > 2009-07-10 09:15:37.000 for code, use select dateadd(ss,starttime+(offset*60),'1/1/1970') thetime mytable be sure find test cases make sure epoch date expected. basically, gmt time number of seconds past 1/1/1970 12:00am, dateadd handles part. offset number of minutes different gmt, multiply 60 seconds , adjust value dateadd accordingly

php - getting RSS feeds on website -

i had code wrote last year , returns rss feeds term enter: <html> <body> <form name="form" action="search.php" method="get"> <input type="text" name="q" /> <input type="submit" name="submit" value="search" /> </form> <?php require_once "rss.php"; // want parse $row[1] variable out words, make new string + instead of spaces $college = "college"; $collegelen= strlen($college); for($i = 0; $i < $collegelen; $i++){ if ($college{$i} == " ") {$spaced = $spaced . "+";} else {$spaced = $spaced . $college{$i};} } echo("yahoo! news rss"); $rss_yahoo =& new xml_rss("http://news.search.yahoo.com/news/rss?p=" . $spaced . "&ei=utf-8&fl=0&x=wrt"); $rss_yahoo->parse(); foreach ($rss_yahoo->getitems() $item) { echo "<li><a href=\"" . $item[...

c# - How is the performance of entity framework 4 vs entity framework 3.5? -

i have 1 query on page takes @ least half second execute using ef 3.5. when used stored procedure speed noticably faster. complex query. there performance improvements in upcoming ef 4.0? , ef 4.0 beat out 3.5 performance wise? the short answer it's tell. .net guys focusing entirely on performance until release on april 12th has finalized , localized. also, meant faster? faster can viewed in many ways, example: entity framework 4.0 has new features , object tracking improvements alone may mean huge wins since you're not doing manual work yourself...in case, @ least development's faster. if didn't work @ before, lighter weight objects poco support may mean lot less memory being shifted when dealing lots of objects well. no matter how small cost of properties being populated when fetching db, there cost both in instantiating , tracking them (load time , memory consumption). in specific case, half second long time complex or high volume query...h...

http headers - difference between REMOTE_HOST and REMOTE_ADDR -

what difference between these 2 variables? remote_host , remote_addr remote_host pertains hostname of client (i.e. computer making request). remote_addr refers ip address of client. there times when hostname unresolvable remote_host return remote_addr or ip address instead.

What's the easiest way to exchange row HTML in table via jQuery (not drag and drop) -

what's easiest way in jquery take entire html <tr> (including tr itself, not tr innerhtml) , swap one? i'm messing around replacewith, that's swapping innerhtml , want swap whole tr html. seems should easy task jquery. i'm thinking there's gotta way reference trs index , easy as: temp = table.children[4]; table.children[4] = table.children[7] table.children[7] = temp; of course that's pseudocode, i'm looking easy in jquery... nicest wrap in reuseable custom function: $.fn.swap = function(other) { $(this).replacewith($(other).after($(this).clone(true))); }; so can use as: one.swap(other); the clone(true) used events taken account. here's sscce demonstrates swapping rows next row (if any): <!doctype html> <html lang="en"> <head> <title>so question 2078626 part i</title> <script type="text/javascript" src="http://ajax.googleapis.com/aja...

html div with text on top and bottom -

i need create <div> of height 200px has text @ top , bottom. needs work in major browsers. i've tried various combinations of alignment/vertical-alignment no luck. use 2 spans (or whatever) inside div: <div> <span id="top">text @ top</span> <span id="bottom">text @ bottom</span> </div> then give div position: relative; , position spans absolutely: div { position: relative; height: 200px; } span { position: absolute; } span#top { top: 0; } span#bottom { bottom: 0; } live example: http://jsbin.com/ucowi3

javascript - Best method for posting page source across domains? -

i'm try figure out if there way pass page source across domains using javascript or method each time page loaded? know in javascript can output page source in variables using code below, how go passing on different domain? var head_src = document.head.innerhtml; var body_src = document.body.innerhtml; can point me in right direction? seems every method i've tried or researched doesn't work correctly or has lot of issues , i'm running out of ideas. in advance. edit more info below imagine have 2 websites on different servers. website source data needs sent , website b website users browse , want collect source of each page view , post website a. have access both servers , hoping add js code on website b pass data over. use server-side language of choice make request , store data in javascript. proxying method common way of grabbing data different domains.

C++ vector max_size(); -

on 32 bit system. std::vector<char>::max_size() returns 2 32 -1, size of char — 1 byte std::vector<int>::max_size() returns 2 30 -1, size of int — 4 byte std::vector<double>::max_size() returns 2 29 -1, size of double — 8 byte can tell me max_size() depends on what? and return value of max_size() if runs on 64 bit system. max_size() theoretical maximum number of items put in vector. on 32-bit system, in theory allocate 4gb == 2^32 2^32 char values, 2^30 int values or 2^29 double values. appear implementation using value, subtracting 1. of course, never allocate vector big; you'll run out of memory long before then. there no requirement on value max_size() returns other cannot allocate vector bigger that. on 64-bit system might return 2^64-1 char , or might return smaller value because system has limited memory space. 64-bit pcs limited 48-bit address space anyway.

Use of Acronyms in LaTeX -

i'm trying add list of acronyms use @ end of document. this example of i'm trying: \begin{thebibliography}{mel} \bibitem[sigurdur]{mel} sigurdur sigurdsson,\emph{'mel frequency cepstral coefficients: evaluation of robustness of mp3 encoded music'}, informatics , mathematical modelling, technical university of denmark \end{thebibliography} \begin{acronym}{h2o} \acro{h2o}[$h_2o$]{water} \end{acronym} i want print page after bibliography page. at beginning of document i'm adding following line: \usepackage[printonlyused,withpage]{acronym} and within document try \ac{h2o} , didn't print acronym h2o, nor acronym list. does know missing? thanks. your example doesn't compile correctly (you should have square brackets argument acronym environment); here's minimal example should started: \documentclass{article} \usepackage[printonlyused,withpage]{acronym} \begin{document} acronym: \ac{h2o} \\ again: \ac{h2o} \begin{acronym...

How to filter an array in Java? -

how can filter array in java? i have array of objects, example cars: class: public class car{ public int doors; public car(int d){ this.doors = d; } } use: car [] cars = new cars[4]; cars[0] = new car(3); cars[1] = new car(2); cars[2] = new car(4); cars[3] = new car(6); now want filter array of cars, keeping 4 doors , more: for(int = 0; i<cars.length; i++){ if(cars[i].doors > 4) //add cars[i] new array } } how should this? before did vector: vector subset = new vector(); for(int = 0; i<cars.length; i++){ if(cars[i].doors > 4) //add cars[i] new array subset.addelement(cars[i]); } } and make new array size of vector. loop on vector again , fill new array. know large procedure simple. i'm using j2me. edit: saw arraylist not in j2me, based on documentation, have vector. if vector class different j2se vector (as this documentation indicates ), perhaps following code work: v...

javascript - Return from closure? -

how 1 return closure, without returning containing function? in following function, return statement returns gm_xmlhttprequest : not closure. naturally can see arrange code that execution drops off end of closure, i'm curious how return in example. function gm_xmlhttprequest(details, callback) { var xhr = new xmlhttprequest(); xhr.onreadystatechange = function() { if (xhr.readystate != 4) return; // <-- zomg returns parent function wtf if (xhr.status != 200) callback(null); callback(xhr); } xhr.open('get', details.url, true); xhr.send(); }; return ever exit callee (current function) , return control caller (calling "parent" function), never return caller . in situation describe, callee anonymous function set onreadystatechange , there no caller (per se). gm_xmlhttprequest returns undefined after xhr.send() line before onreadystatechange function runs because there no return statement , xhr asynchr...

sql - How to create view that combine multiple row from 2 tables? -

i want create view combine data 2 tables, sample data in each table below. select command tablea select [id], [date], [sum] tablea result id | date | sum 1 | 1/1/2010 | 2 1 | 1/2/2010 | 4 3 | 1/3/2010 | 6 select command tableb select [id], [date], [sum] tableb result id | date | sum 1 | 1/1/2010 | 5 1 | 2/1/2010 | 3 1 | 31/1/2010 | 2 2 | 1/2/2010 | 20 i want output below id | date | suma | sumb 1 | 1/1/2010 | 2 | 10 1 | 1/2/2010 | 4 | 0 2 | 1/2/2010 | 0 | 20 3 | 1/3/2010 | 6 | 0 how can on sql server 2005? date information vary, modify in table. try this... select isnull(tablea.id, tableb.id) id, isnull(tablea.date, tableb.date), isnull(tablea.sum,0) suma, isnull(tableb.sum, 0) sumb tablea full outer join tableb on tablea.id =...

php - Returning 2 values from a function -

this question has answer here: multiple returns function 26 answers is possible return 2 values when calling function output values, example, have this: <?php function ids($uid = 0, $sid = '') { $uid = 1; $sid = md5(time()); return $uid; return $sid; } echo ids(); ?> which output 1 , want chose ouput, e.g. ids($sid) , still output 1 . is possible? you can return 1 value. can use array contains other 2 values: return array($uid, $sid); then access values like: $ids = ids(); echo $ids[0]; // uid echo $ids[1]; // sid you use associative array: return array('uid' => $uid, 'sid' => $sid); and accessing it: $ids = ids(); echo $ids['uid']; echo $ids['sid'];

.NET API for SQL Server Service Broker -

is there .net api or object model using sql server service broker? there isn't official supported api. there community samples though developed service broker team or related teams in ms can use starting point, not officially supported (you cannot call product support , report bug): wcf transport channel sql server service broker sql server service broker product samples service broker interface (a .net api programming ssb, part of samples linked above)

iphone - TableView not displaying correctly and crashing, -

i have tableview in midddle of tab bar template application.. wanted add contents of nsmutablearray called 'routines'. here .h file #import <uikit/uikit.h> @interface firstviewcontroller : uiviewcontroller <uitableviewdelegate, uitableviewdatasource> { nsmutablearray *routines; } @property (nonatomic, retain) nsmutablearray *routines; - (ibaction)showneweventviewcontroller; @end and .m file. #import "firstviewcontroller.h" #import "neweventviewcontroller.h" @implementation firstviewcontroller @synthesize routines; - (nsinteger)tableview:(uitableview *)tableview numberofrowsinsection:(nsinteger)section { return [routines count]; } - (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath { static nsstring *cellidentifier = @"cell"; uitableviewcell *cell = [tableview dequeuereusablecellwithidentifier:cellidentifier]; if (cell == nil) { cell = [[[uitableview...

C++ equivalent to the Python len() function? -

i have integer , need find out how many digits in it. a little tricky handle negative numbers , case input zero: int length(int n) { int len = 0; if (n < 0) { len = 1; n = -n; } while (n > 9) { n /= 10; len++; } return len+1; }

objective c - Match first word of a phrase in a String -

i using gtmregex class google toolbox mac (in cocoa / objective-c) app: http://code.google.com/p/google-toolbox-for-mac/ i need match , replace of 3 word phrase in string. know 2nd , 3rd words of phrase, first word unknown. so, if had: lorem biff bam boo ipsem and lorem beep bam boo ipsem i watch match both (beep bam boo) , (biff bam boo). want wrap them in bold html tags. here have: gtmregex *requiredheroregex = [gtmregex regexwithpattern:@"(\\([a-z][a-z0-9]*)\\b hero required)" options:kgtmregexoptionsupressnewlinesupport|kgtmregexoptionignorecase]; out = [requiredheroregex stringbyreplacingmatchesinstring:out withreplacement:@"<b>\\1</b>"]; however, not working. basically, cant figure out how match first word when dont know it. anyone know regex this? update: gtregex uses posix 1003.2 regular expresions, solution is: gtmregex *requiredheroregex = [gtmregex regexwithpattern:@"([[:<:]][a-z][a-z0-9]*[[:>:]])( he...

.net - Update Href of Link button Through Jquery -

i using link button redirect page desired location query string value jquery. link button code follows: <td> <a id="selectalllink" class="button" rel="nofollow ibox&width=800&height=400&title=contact now" href="#" onclick="return (this.href=='#');">contact selected</a> </td> and jquery create/update link on click event of link button follows: function cotactselected() { var = []; var n = $("td.title_listing input:checked"); var s = ""; n.each(function() { a.push($(this).val()); }); var s = a.join(','); if (s != null) { $("@.button#selectalllink").attr("href", "/d_contactseller.aspx?property=" + s); } else { alert("select atleast 1 property contact!"); } } what wanted collect comma separated value check boxes , pass...

java - enum.values() - is an order of returned enums deterministic -

i have enum some_enum : public enum some_enum { en_one, en_two, en_three; } will some_enum.values() return enums in order of enum declarations: en_one, en_two, en_three ? rule or not guaranteed not changed in next jdk releases? the java language specification uses explicit language: @return array containing constants of enum type, in order they're declared [source] so, yes, returned in declaration order. it's worth noting order might change on time if changes class careful how use this.

javascript - Style switcher help -

i need have made style switcher, cannot work out how replace stylesheet, @ moment code empties <head> need replace previous stylesheet, code, menu , javascript <ul id="options"> <li><a class="option" href="<?php echo base_url();?>welcome/setbackground/red">red</a></li> <li><a class="option" href="<?php echo base_url();?>welcome/setbackground/green">green</a></li> <script type="text/javascript"> $('a.option').click(function(ev) { ev.preventdefault(); var url = $(this).attr("href"); alert(url) $.ajax({ url : url, type : "post", data : "js=true", success : function(html) { $('head').html(html); } }); }); </script> php function setbackground() { $data['style'] = $this->uri->segment(3); $_cookie[] = setcook...

c# - Recommended way to check if a sequence is empty -

a method returns sequence, ienumerable<t> , , want check if empty. how recommend doing that? i'm looking both readability , performance. the first , obvious way check count greater zero: if(sequence.count() == 0) has decent readability, terrible performance since has go through whole sequence. a method use following: if(!sequence.any()) this doesn't (as far know) have go through whole sequence, readability bit backwards , awkward. (reads lot better if checking sequence not empty though). another option use first in try-catch, this: try { sequence.first(); } catch(invalidoperationexception) { // } not pretty solution, , slower too, since using exceptions , stuff. prevent using firstordefault of course, except have big problem if first item in sequence was default value ;) so, other ways check if sequence empty? 1 use? 1 recommend use? note: optimal readability put 1 of above snippets in isempty extension method, still curious since h...

java - Fastest way to read long[] from file? -

i have file contains 200,000 long values want read fast possible long[]. it's android app; function calls slow (so involving reading long @ time "for" loop super slow) , need loading fast. can use? @ seems read bytes fast. i've used bytebuffer , filechannel nio package before , seems fast way load arrays of values files. however, cannot work out how use read data long[]. i've tried wrapping long[] longbuffer, cannot see way can feed data file longbuffer. edit: whatever method use, need able use arrays.binarysearch on long[] array @ end. there no way cast byte[] long[] . however, try use filechannel read content bytebuffer , hold of longbuffer through bytebuffer.aslongbuffer long[] through longbuffer.array() . you try filechannel.map mappedbytebuffer of file. may faster going through filechannel.read . if doesn't work try use filechannel read content bytebuffer , access long s inside it, using bytebuffer.getlong(index) . ...

javascript - Frame breaking only cross-domain but not for iframes from the same origin? -

this question asked , answered correctly, there did not seem solution posted. if site has iframes, , 1 wants prevent being enclosed in frame different domain, simplistic frame-busting not useful: <script>if (top != self) top.location = location</script> however, since cross-frame scripting other domains should generate exceptions, seems work inside iframe: <script> try { if (window.document.domain != top.document.domain) { // throws exception throw "you naughty puppy!"; // should not ever here, right? } } catch () { top.location = "/error/naughtypuppy"; } </script> the if above should enough on own prevent cross-domain framing of iframes. should ever return false or throw exception, there anyway script reach throw statement in browser? would sufficient prevent framing other domains? <script> try { var bogus = top.document.domain; } catch () { top.location = "/error/naughtypuppy"; } </s...

sql - how to approach this specific query -

i have rather complex logical query i'm trying execute. there series of related tables. having difficulty figuring out way approach it. tables: transaction - t_id discount - d_id item_id type (percentage or basic value) value transaction_discount - t_id d_id item - item_id price edit: additional table purchase t_id item_id i attempting pull price adjusted after discount applied. avoid adding column adjusted price database... possible calculate adjusted price each transaction data entered (so it'd redundant store data). this basic logic: if(this transaction had discount applied) //apply discount , return adjusted price else(no discount applied) //pull price it possible in several separate queries using php logic. //1st step - create array of bool's: true = discount_used/false = no_discount //2nd step - if(discount_used) return price adjusted discount //3rd step - if(no_discount) return price //4th step - combine 2 differ...

flash - Make Uploadify work in a jquery accordion header when wmode=transparent -

i have jquery accordion, , want insert uploadify inside accordion header. putting there worked fine, when set uploadify swf wmode transparent, not work well: -in chrome clicking upload swf nothing -in firefox open upload window, closes/opens accordion -in internet explorer acutally works fine if set wmode window work fine, must use transparent mode. any ideas? arad. edit: solution invoke uploadify swf click using javascript- possible? edit2: code- relevant html: <div id="accordion"> <div class="category" id="category$category_id"> <h3 class="ui-accordion-header"> <div class="header-div"> <div id="categorytitle$category_id" class="categorytitle">$category_name</div> </div> <div class="rightpart"> <input id="fileinput$category_id" class="f...

html - How to toggle selection of an option in a multi-select with jQuery? -

i have standard select multiple html input field, example: <select multiple="multiple" size="5" id="mysel" name="countries"> <option value="2">afghanistan</option> <option value="4">aland</option> </select> as multi-select, select more 1 value have hold ctrl key , select further elements. want achieve is, that: clicking unselected option selects it clicking selected option unselects it. the idea avoid having press ctrl key , change usage semantics of input field. elements should selectable , un-selectable clicking (ie. toggling of select status). i have not yet been able implement this. pseudo-code should this. catch click event. check if element clicked unselected, select it or if element clicked selected, unselect it. how should implement this? you may use following snippet achieve desired effect $("select[multiple] option").mouse...

c# - DDD - How to implement high-performing repositories for searching -

i have question regarding ddd , repository pattern. say have customer repository customer aggregate root. & find methods return populated aggregate, includes objects address, etc. good. when user searching customer in ui, require 'summary' of aggregate - flat object summarised information. one way deal call find method on repository normal, , in application layer, map each customer aggregate customersearchresult / customerinfo dto, , send them client. but problem performance; each customer aggregate may require multiple queries populate of associations. if search criteria matched 50 customers, that's quite hit on db potentially retrieving data i'm not going need. the other issue may wish include summarised data customer outside of customer's aggregate root boundary, such date of last order made example. order has it's own aggregate , therefore customer's order information have call orderrepository, degrading performance. so think i'm le...

Security Exception when Uploading From Silverlight to PHP -

i using official microsoft example , this example basis code upload file silverlight php script. i calling **httpwebrequest.begingetrequeststream()** , writing file on file stream, , calling **httpwebrequest.begingetresponse()** response. when call httpwebresponse.endgetresponse() following exception every single time: {system.security.securityexception ---> system.security.securityexception: security error. @ system.net.browser.browserhttpwebrequest.internalendgetresponse(iasyncresult asyncresult) @ system.net.browser.browserhttpwebrequest.<>c__displayclass5.<endgetresponse>b__4(object sendstate) @ system.net.browser.asynchelper.<>c__displayclass2.<beginonui>b__0(object sendstate) --- end of inner exception stack trace --- @ system.net.browser.asynchelper.beginonui(sendorpostcallback beginmethod, object state) @ system.net.browser.browserhttpwebrequest.endgetresponse(iasyncresult asyncresult) @ fileupload.fileuploadprocess.ge...

download - Downloading an email attachment using java -

i doing mail application using javamail. every thing fine, when user downloading attachment, exact attachment (fine) .at same time 0 byte file creating in server same file name. how stop creation of 0 byte files in server. my code :- attfile = new file(attname); fileoutputstream fileoutput = new fileoutputstream(attfile); inputstream = part.getinputstream(); bufferedoutputstream outs = new bufferedoutputstream(fileoutput); byte b[] = new byte[part.getsize()]; is.read(b); out = response.getoutputstream(); out.write(b); you have 2 different (unrelated afaict) output streams: outs (wrapping fileoutput ) , out . outs , fileoutput not seem used create empty file.

mysql - Bloated innodb datafile (ibdata1) and how to reclaim space? -

i have 12gb of data in tables , datafile, ibdata1, used 12gbs in size. ran following command alter table `rails_production`.`pictures` change `data` `image_file_data` mediumblob null while making temporary copy of table, got following error error 1114 (hy000): table '#sql-7fe4_12c9' full i assume means there wasn't enough space make temporary copy of table. datafile 17gb! how reclaim space in datafile? is there way check how of 17gb being used? unfortunately can't reclaim space innodb database if not using innodb_file_per_table in configuration: mysql innodb not releasing disk space after deleting data rows table

Capture the browser screen as JPG/PNG/etc with Flash? -

is there way create screenshot of browser in flash? know in java possible, , popup dialog asking trusting signed applet, there way in flash? flash has not security model such java or silverlight things downright intrusive out of question. except the clipboard.

A good practice/project for PHP programmer -

i know oop (but not skilled) in php. nowadays want build something, since beginning of semester holiday (3 weeks). have suggestions me? (note: i'm statistician, , know c, c++, minitab, matlab, spss, sas, r , database design) not need related statistics. i build care - in task or problem domain interested in. otherwise when going gets tough, say, "why bother" or "there's out there this." if you're stats, project might write php/html/js query dataset , run analytics (mean, mode, filtered date, other criteria). i'd suggest doing dynamic ajax style interaction jquery. way you're getting pretty sense of how php works, , how use render interesting in html. best of all, may solve actual problem or colleague has, rather writing throw away code no value.

python - Json communication between flash and javascript -

note: using django/python/javascript/flash so been 2 days since i'm stuck @ error. did things told me , found couple of ways around nothing worked. these results. javascript not receive normal string has json object so. in views.py somestring = json.dumps("hello world") which renders in html &quot;hello world&quot; and in javascript rendered a240527176321_quote_hello now, since json object need convert in flash. when gets in flash receive this function something(hellovar){ ..... ...... } it not come inside function. thoughts? why communicate between flash , js via json? actionscript has powerfull build in externalinterface communicate javascript.

c - Linux Kernel: System call hooking example -

i'm trying write simple test code demonstration of hooking system call table. "sys_call_table" no longer exported in 2.6, i'm grabbing address system.map file, , can see correct (looking through memory @ address found, can see pointers system calls). however, when try modify table, kernel gives "oops" "unable handle kernel paging request @ virtual address c061e4f4" , machine reboots. this centos 5.4 running 2.6.18-164.10.1.el5. there sort of protection or have bug? know comes selinux, , i've tried putting in permissive mode, doesn't make difference here's code: #include <linux/kernel.h> #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/unistd.h> void **sys_call_table; asmlinkage int (*original_call) (const char*, int, int); asmlinkage int our_sys_open(const char* file, int flags, int mode) { printk("a file opened\n"); return original_call(file, flags, mode);...

data modeling - how to store/model users/facebook users/linkedin users, etc, with ActiveRecord? -

my app has "normal" users: come through typical signup page facebook(fb) users: come facebook connect "fb-normal" users: user can log both email/password * fb connect further, there's slew of other openid-ish login methods (i don't think openid acceptable since doesn't link accounts , allow 3rd party specific features (posting twitter, adding fb post, etc etc)) so, how model this? right have user class #facebook_user? defined -- gets messy "fb-normal" users - plus validations become tricky , hard interpret. also, there methods #deliver_password_reset! make no sense in context facebook-only users. (this lame) i've thought out sti (user::facebook, user::normal, user::fbnormal, etc.) makes validations super slick, doesn't scale other connection types, , permutations between them... user::facebooklinkedinnormal(wtf?) doing bunch of modules think suck lot. any other ideas? i split concerns, seems doesn't...