Posts

Showing posts from March, 2010

php - Insert HTML content into db table securely -

i'm using html function inserting html content db table , filter filtering user inputs against sql injection attacks. getting output prntscr.com/3c8ht . got following questions: 1) functions html content needs passed before insert , while output? 2) else filter function needed or there unused function? thx in advance function filter($data, $db) { $data = $db->escape_string($data); $data = htmlspecialchars($data, ent_ignore, 'utf-8'); $data = strip_tags($data); $data = stripslashes($data); $data = htmlentities($data); return $data; } function html($data, $db) { $data = $db->escape_string($data); return $data; } you should use escaping tool required medium, not anywhere. to avoid sql injection, mysql_real_escape_string() is, @ minimun, need use. better alternative using prepared statements , paramerized queries (look pdo extension, shipped php since v 5.1 iirc), safest option avoid kind of exploit. sending u...

java - aspectj-maven-plugin multi module project -

i'm trying use aspectj-maven-plugin in multi-module project , can't understand aspects have placed. want crosscut in-module , between-modules calls. .aj files should located? this did far (structure of maven modules): foo foo-api foo-impl foo-aspects .aj files located in src/main/aspect . sub-modules (except foo-aspects ) using aspectlibraries option of aspectj-maven-plugin , use aspects foo-aspects.jar . at same time every sub-module has own aspects in src/main/aspect . works fine me far.

python - Setting name of variable in a class with a function? -

i have class , want following: class my_class: def my_func(self, var_name): self.var_name = 5 = my_class() a.my_func('yes') print(a.yes) i not sure how set class variable name using function >>> class my_class(object): ... def my_func(self,var_name): ... setattr(self,var_name,5) ... >>> = my_class() >>> a.my_func('yes') >>> a.yes 5

javascript - How can an animation be queued for different elements? -

i have question animation queues in jquery. let's talk on example. let have div , bunch of p elements in , of p elements has class "read": <div class="wrapper"> <div class="inner"> <p>paragraph 1</p> <p class="read">paragraph 2</p> <p>paragraph 3</p> <p class="read">paragraph 4</p> <p>paragraph 5</p> <p class="read">paragraph 6</p> <p>paragraph 7</p> <p class="">paragraph 8</p> </div> </div> i'd fade read ones out , animate height of wrapping div element accordingly. jquery code block won't work. var initheight = $('.wrapper').height(); $('.wrapper').height(initheight); $('p').not('.read').fadeout(300, function() { $('.wrapper').animate({ height: $('...

RESTful Routes help in Rails 3 -

i'm using rails 3, devise , mongoid. i believe can accomplish need using restful routes not sure how it. let me explain have , trying do. let's have 2 controllers - user , simpleform. the simpleform public facing form (no authentication required) when submitted shows in user's account (when login). i have multipul users on system , each 1 see form submissions that's specific them. so question is, how public facing form submit specific user's account? as of route fill out new form looks "site.com/simpleform/new". think can use routes make "site.com/simpleform/user_id/new" or "site.com/user_id/simpleform/new". either variation work think. when form submitted in public application knows user associate because of user_id in url. i think logic works , restful routes can make happen, i'm not sure how it. each user resource has 1 associated simpleform resource. so think route like: resources :users reso...

format - Java output file formatting -

i having bit of trouble formatting output file myself readable. trying output file such as: name of school size of school -------------- -------------- blblah blah 1300 blah blah blah 11300 blah blah blah asdf 14220 blah bblah 1300 but having trouble. using following code following output: file file1 = new file("src\\sortedint.txt"); formatter fmt = new formatter(file1); helpermethods.quicksortstudents(colleges, 0, colleges.length - 1); for(int = 0; < colleges.length; i++) { fmt.format(colleges[i].nameofschool + "%20d" + "\n", (int)colleges[i].numofstudents); fmt.flush(); } which gives me: eastman school of music 800 clark university 1100 walla walla college 1100 drew 1200 juilliard 1200 because padding end of college name. there anyw...

c# - Convert numeric types: Which style to use? -

let's want convert double x decimal y . there's lot of ways that: 1. var y = convert.todecimal(x); // dim y = convert.todecimal(x) 2. var y = new decimal(x); // dim y = new decimal(x) 3. var y = (decimal)x; // dim y = ctype(x, decimal) 4. -- no c# equivalent -- // dim y = cdec(x) functionally, of above same thing (as far can tell). other personal taste , style, there particular reason choose 1 option on other? edit : il generated compiling 3 c# options in release configuration: 1. call valuetype [mscorlib]system.decimal [mscorlib]system.convert::todecimal(float64) --> calls system.decimal::op_explicit(float64) --> calls system.decimal::.ctor(float64) 2. newobj instance void [mscorlib]system.decimal::.ctor(float64) 3. call valuetype [mscorlib]system.decimal [mscorlib]system.decimal::op_explicit(float64) --> calls system.decimal::.ctor(float64) this il generated compiling 4 vb options in release configuratio...

Is there any advantage to using C++ instead of C# when using Direct3D? -

is there advantage using c++ instead of c# when using direct3d? tutorials i've found c++ , directx use direct3d (which knowledge managed). similarly, of c# tutorials i've found direct3d. is direct3d managed? there difference between using d3d in either of 2 languages? directx entirely native. impression may have it's managed , utterly wrong. there managed wrappers allow use directx managed code. in addition, directx programmed accessed c++ or c, or similar languages. if @ slimdx project, encountered numerous issues, due resource collection, because c# doesn't genuinely support non-memory resources being automatically collected , using doesn't cut mustard. in addition, game programming can cpu-intensive, , often, additional performance lost using managed language untenable, , virtually existing supporting libraries c or c++. if want make small game, or that, there's nothing @ stopping using managed code. however, know of no commercial games ta...

vbscript - With Acrobat Javascript can you open a file in the recent documents list? -

i have round-about way planning on launching acrobat sharepoint can manipulate file both on way in , way out, curious if there way launch adobe acrobat 9 standard edition , have automatically open document 1 recent documents list. i know possible open new document @ app launch code such as: trustedroutine = app.trustedfunction( function(){ app.beginpriv(); if (app.activedocs.length<1){ app.opendoc("/c/documents , settings/username/desktop/filename.pdf"); } app.endpriv(); }) what curious doing though put object or parameter opendoc cause read key registry. any appreciated. update: been researching more, , realize vbscript can additional things. vbscript able instead? after doing ton of research, have come realize not possible rewrite integration without writing out own ocx control handle opendocument call sharepoint. because of this, company going instead invest in upgrading acrobat x has control written.

permissions - Access error uploading file using winsp -

Image
i trying upload 2 files webserver teacher can see it. using winsp since filezila doesnt work. reason telling me don't have access page. can tell me why doing that.here picture of screen. i not understanding why telling me don't have access it. problem definitly isn't in code. there error while uploading files. can connect ftp regulary? if can. active or passive file transfer ftp. if can upload files, files must in public_html folder visible browser. active or passive

java - inputstream.available() is 0 always -

i have no idea of happening code. getting no errors , no response well. writing data serialport , waiting response activating port.notifyondataavailable(true); event not triggered , inputstream.available() returns 0 always. might wrong ? using rxtx in linux. edit package testconn; import forms_helper.global_variables; import java.io.bufferedreader; import java.io.ioexception; import java.io.inputstream; import java.io.inputstreamreader; import java.io.outputstream; import java.io.printstream; import java.io.unsupportedencodingexception; import java.util.logging.level; import java.util.logging.logger; import javax.comm.*; import java.util.*; /** check each port see if open. **/ public class openport implements serialporteventlistener { static enumeration portlist; static commportidentifier portid; static string messagestring; public static serialport serialport; static outputstream outputstream; inputstream inputstream; ...

python - Managing Mac OS created filenames with non ASCII characters in windows environments? -

i deal large collection of unknown files, , have been been learning python me filter / sort , otherwise wrangle these files. a collection looking @ has large number of resource forks, , wrote little script find them, , delete them (next step find them, , move them, thats day). i found in collection there number of files have non ascii characters in file name, , seems tripping os.delete function. example file name: ._spec com report 395 (n.b. 3 has small dot underneath it, can't find example, or figure out how show hex of filename...) i log filenames, log records file: ._spec com report 3?95 the error windowserror, can't find file (the string passing not file known windows os.) put in try clause allow me work rounf it, deal properly. i tried using unicode switch in walk option `os.walk(u'.') per post: handling ascii char in python string (top answer) , see following error: traceback (most recent call last): file "<stdin>", line 3, in...

.htaccess - How to logout of an HTTP authentication (htaccess) that works in Google Chrome? -

i got solution firefox , ie didn't find solution google chrome. is there way in google chrome? i know it's old post... mean friggin 5 years now, found solution. inside protected folder, create folder, let's call "logout". place same .htaccess file in here have in protected folder, except small modification. instead of: require valid-user now write: require user exit and make sure, don't have user named exit! :d in protected area, logout link or button or whatever, should redirect user address: example.com/protectedfolder/logout the browsers able keep 1 user logged in 1 site name or realm name... sign in attempt user exit overwrite everything, logged in user, have log in again protected area. but always, might wrong, , should still close browser window, , restart computer if want sure! :) also, wouldn't hurt, if tell users going happen, when hit logout! i have tested in chrome , in internet explorer 11.(will not work in edg...

c# - Write PDF stream to response stream -

if have pdf file stream, how can write response output stream? since using mvc, best way use filestreamresult : return new filestreamresult(stream, "application/pdf") { filedownloadname = "file.pdf" }; playing response.write or response.outputstream controller non-idiomatic , there's no reason write own actionresult when 1 exists.

class - Timer Thread with passed Function* and Param -

i'm working on finishing server first iphone application, , want implement simple little feature. i run function (perhaps method well), if function returns value after waiting period. simple concept.... right? here's basic foundation. template <typename t,class typ> struct funcpar{ t (*function)(typ); typ parameter; funcpar(t (*func)(typ),typ param); funcpar& operator=(const funcpar& fp); }; the goal here able call funcpar::function(funcpar::parameter) run stored function , parameter, , not have worry else... when attempted use void* parameter instead of template, couldn't copy memory object (because didn't know end object going be, or beginning matter) , when tried multiple timers, every single object's parameter change new parameter passed new timer... previous struct have question: is possible make all-inclusive pointer type of object inside method of class? can templatize method, , not whole class? work function template? ...

regex - Python: parsing help needed! -

i trying retrieve fields within .lua file. thought split on commas second set of curly brackets ruins that. example: return { { 6163, 0, "tv", false, {1302}, "espn deportes", "espn deportes es el", nil,"tv","936",nil,"4x3", mediarestrictions={"m2g" } }, { 57075, 0, "tv", false, {1302}, "video rola", "video \"música para tus ojos\", uedes ver.", nil,"tv","948",nil,"4x3", mediarestrictions={"m2g" } }, { 717242, 0, "tv", false, {1302,1301,1288}, "hits", "asdlfj", nil,"cliplinear","6310",nil,"4x3", mediarestrictions={"m2g" } }, { 122719, 0, "tv", false, {1302,1301,1288}, "bombone", "asdf", nil,"tv","74",nil,"4x3", mediarestrictions={"m2g" } }, } so looking following first line: ...

sorting - PHP: sort tournament round teams by multiple attributes -

i developing soccer tournament management system , i'm stuck problem. have show user round teams ranking based on different attributes. i'm right considering following order: team points ( 3*won match + 1*tie match ) team confrontational( not sure if right word mean matches between same teams, i.e. if 2 teams have same points 1 defeated other, winning 1 above loser 1 ) goal difference (goal scored-goal taken) goal scored alphabetical order data build model retrieved through different database query , structure i'm using right save them array of objects this: teamid played matches won matches lost matches tie matches points goal scored goal taken goal difference teams defeated current 1 = array(teamid1,teamid2...) teams defeated current one= array(teamid1,teamid2...) teams had tie current 1 = array(teamid1,teamid2...) for sorting attributes can use php array_multisort function , job done issue team confrontational. example let's have situ...

flex - ArrayCollection sort by czech locale -

how can sort string field in arraycollection czech locale... á b c č d ď e é ě f g h ch í ..... alike collator("cs-cz", collatormode.matching); array thanks help this may helps you, adobe globalization blog show sorting example in data grid hope helps

Objective-c - iOS - hide/unhide label, textfield etc -

i want hide/unhide controls of subview in view. example: when button action occurs, labels become hidden unhide on subsequent button action , on. have implemented functionality through interface builder. how can same implementation programmatically? i've tried [label1 hidden: true]; which hasn't worked me. here answer: [label1 sethidden:yes]; yes objective-c's version of true .

iPhone: Suppress NSLog in production? -

i got bunch of nslog statements in code. there anyway can suppress them executing in production, execute when i'm developing? want not comment them out, , them put them in when developing, it's hassle. debug macro defined (xcode default) when doing debug/development build of project. cause code between #ifdef debug , #endif lines not included when doing release build compiled , included debug/dev/test build. example: #ifdef debug nslog(@"hello world!"); #endif this use in project-prefix.pch file (called debuglog(@"abc %@", somestr); ): #ifdef debug extern void dbgquietlog(nsstring *format, ...); #define debuglog(fmt, ...) dbgquietlog((@"[line: %d] %s: " fmt), __line__, __function__, ##__va_args__); #else #define debuglog(fmt, ...) #endif #ifdef debug void dbgquietlog(nsstring *format, ...) { if (format == nil) { printf("nil\n"); return; } va...

Javascript: Compare three arrays -

i want compare many arrays , combine identical: a = [1,2,3]; b = [1,2,3]; c = [1,2,3]; d = [10,11,12]; e = [10,11,12]; f = [10,11,12]; g = [13,14]; h = [13,14]; if there identical arrays i'd create new arrays out of identical ones: i = [1,2,3]; j = [10,11,12]; k = [13,14]; would need iterate through each element in 1 array against of elements in other arrays? for (var in a) { (var j in b) { if (a[i] == j[j]) { // create new arrays } } } etc... then, create new arrays out of matches? sounds lot of overhead. what's best way accomplish this? thanks! if you're trying finish unique arrays, use hash approach: var myarrays = [a,b,c,d,e,f,g], uniques = [], hashes = {}; (var i=0; < myarrays.length; i++) { var hash = json.stringify(myarrays[i]); // or .tostring(), or whatever if (!(hash in hashes)) { hashes[hash] = true; uniques.push(myarrays[i]); } } // uniques holds unique...

c# - Setting ViewModel's Property from XAML -

i have usercontrol , it's datacontext binded viewmodel, how set viewmodel's property xaml ? possible? upd : sorry being not clear, i'm trying : usercontrol's datacontext binded viewmodel, need set viewmodel's property (let's say, usercontrol's width property). possible? upd2: seems not possible.i know twoway binding mode, etc, thing wanted - set viewmodel's property usercontrol's one this example should clear <set property={binding somepropertyonviewmodel} value={binding relativesource={relativesource self}, path=somepropertyonusercontrol}> binding works both ways: i.e. source (e.g. viewmodel) target (e.g. usercontrol) , target source. specify direction via mode of binding. following bindingmodes : twoway oneway onetime onewaytosource in case, if want bind width property of usercontrol thewidth property of viewmodel: case a: want bind in both directions, use mode=twoway <us...

Daylight Time Zone conversion in C# asp.net -

how check whether particular time zone falls under "daylighttimezone" or not using c# asp.net? if time zone falls under "daylighttimezone" should changing time standard time zone? i time zone(time zones listed in windows os) input user , store in database,whenever user logs in display time , date based on timezone selected user.now role daylightsaving play here? whether changes should made if particular timezone falls under "daylightsavingzone". use timezoneinfo class introduced in .net 3.5. it's not clear bigger goal is, timezoneinfo should cover whatever you're trying do, such converting 1 time zone another. it's not simplest class use correctly, partly because datetime type badly designed start with, unfortunately :( i'm working (occasionally!) on new date , time library .net called noda time , unfortunately that's not ready yet :( edit: okay, steps should be: work out how time zone user in appropriate f...

retrieve resultset based on where clause condition order in sql server -

consider following table colid value 100 b 200 c 300 d 400 e 500 what query retrieving values colid 'c','a','d' in same order? for particular ordering have like: select * mytable colid in ('c', 'a', 'd') order case colid when 'c' 0 when 'a' 1 else 2 end

iphone - Saving remote image to Documents/Images Folder -

i've checked every answer other questions posted here no answers seem work. im trying save image( e.g http://dl.kr.org/logos/dl-small.gif ) on website documents/images folder on iphone. can paste me code need , i've tried long , small answers none of them work nsdata *data = [nsdata datawithcontentsofurl:[nsurl urlwithstring:@"http://dl.kr.org/logos/dl-small.gif"]]; nsstring *imagepath = [nsstring stringwithformat:@"%@/dl-small.gif", [nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes) objectatindex:0]]; [data writetofile:imagepath atomically:no];

java - Reading integers from a line -

i'm trying read 2 integers on same line. scanner a=new scanner(system.in); x=a.nextint(); y=a.nextint(); now, if input 3 4 3 4 x = 3 , y = 3. tried using a.usedelimiter("\\s") doesn't work. there must error elsewhere in code. works fine me. import java.util.scanner; class main { public static void main(string[] args) { scanner = new scanner(system.in); int x = a.nextint(); int y = a.nextint(); system.out.println("x = " + x + ", y = " + y); } } input: 3 4 3 4 output: x = 3, y = 4 see working online: ideone

entity framework - Suffix a term to every class generated -

i generating poco entititied using poco entity generator, fine. but want sufix term "entity" every class generated. is ther option ,such every entity generated have sufix it? user userentity role roleentity if use poco generator template can open template , modify use new naming convention. must modify type generation (and perhaps file name generation) , navigation property generation.

JavaScript create regex programmatically -

i know can create javascript replace this: str = str.replace(/mytarget/g, 'some value'); that replace occurrences of literal mytarget . however, have big array of words/phrases want use in regex replace, , regexps language elements (they not wrapped in string when declaring), can't find way declare regexps programmatically unless hard-code them. if have: var arr=['word', 'another', 'hello']; i want produce: str = str.replace(/word/g, 'some value'); str = str.replace(/another/g, 'some value'); str = str.replace(/hello/g, 'some value'); please post example can use regexps, i'll adding more expressions regexps such whitespace etc. need regexp way. finally, please don't offer using eval , i'm sure there better way. you need invoke regexp constructor function that. example: ['word', 'another', 'hello'].foreach(function( word ) { var myexp = new regexp(word, ...

html - iPhone front end development workflow best practice -

i front-end developer working first iphone application , looking stack overflow folk insight on workflow. able test in iphone broswer make use of development tools such firebug / web developer toolbar. code in live environment using combination of firebug , webdeveloper toolbar or textmate (preview in browser mode). stick methods actively use have them applied iphone. can make recommendations developing front-end portion of application? note: plan on using html5boilerplate mobile , have xcode installed. apple has documentation on preparing content ipad . should give push in right direction.

objective c - XCode: Why is my event not being added to the calendar? -

i have added following code app: nsdate * selected = [datepicker date]; nsstring * date = [selected description]; nsdatecomponents *components = [[nscalendar currentcalendar] components:nsdaycalendarunit fromdate:datepicker.date]; callabel1.text = [nsstring stringwithformat:@"%d", [components day]]; ekeventstore *store = [[ekeventstore alloc] init]; ekevent *event = [ekevent eventwitheventstore:store]; event.title = @"test event"; //required event.startdate = [datepicker date]; event.enddate = [datepicker date]; event.calendar = store.defaultcalendarfornewevents; //end nserror *err; [store saveevent:event span:ekspanthisevent error:&err]; why not adding ios calendar? thanks. your event needs valid time span save it. try this event.startdate = selected; event.enddate = [selected datebyaddingtimeinterval:30*60]; //30 minutes example

android - Adapter of ListActivity -

i have problem listactivity , hope can me. have created adapter : public class mylistadapter extends baseadapter { private arraylist<string> lista= new arraylist<string>(); private layoutinflater myinflater; public mylistadapter(context context){ myinflater= (layoutinflater)context.getsystemservice(context.layout_inflater_service); } public void additem(final string item){ lista.add(item); notifydatasetchanged(); } public int getcount() { return lista.size(); } public object getitem(int position) { return lista.get(position); } public long getitemid(int position) { return position; } public view getview(int position, view convertview, viewgroup parent) { viewholder holder= null; if (convertview == null){ convertview= myinflater.inflate(r.layout.index, null); holder= new viewholder(); holder.textview= (textview)convertview.findviewbyid(r.id.empty); holder.checkbox= (checkbox) convertview.findviewby...

jquery - how to deal with delete buttons in php? -

i want know best way handle delete or edit buttons? so let's comment box, should use post or method , make validations in page suppose delete comment? as specific example, i'm gonna point out facebook's comment box, has little button deleting comments, doesn't display url in bottom of browser, guess uses post method jquery in it. i'm right? if not should use type of buttons? i don't know facebook uses, yes, should use post . might want use this: <div class="comment"> <p><code>post</code> should used actions change data.</p> <form action="comments/1/delete" method="post" class="delete-form"> <input type="submit" value="delete" /> </form> </div> $(".delete-form").submit(function() { var me=$(this); $.ajax({ type: 'post', url: me.attr('action'), success...

how to debug php mail? -

a simple script simple mail function called in localhost , live server. $message = "line 1\nline 2\nline 3"; $message = wordwrap($message, 70); $rs = mail('myemail@gmail.com', 'my subject', $message); both of them return bool true. localhost can receive email in live server cannot receive mail. then check /var/mail/www-data there message mailing remote domains not supported linux, apache or php problem? it seems smtp server configuration issue, since asking how debug php mail, best approach sniffing tcp conversation. can capture conversation using wireshark (or tcpdump if on console) , inspect actual commands sent , server.

dns - Trying to set up a .ka domain name -

i'm trying set domain .ka suffix url shortener project i'm working on. similar drbl.in example. i've checked online , suffix doesn't seemed registered country yet or appear of domain name service. ideas on how fix up, or if possible? thanks there no .ka tld. you'll have pick different one. full tld list: http://data.iana.org/tld/tlds-alpha-by-domain.txt

1-way anova in R help -

i new in r (statistic packet) programming , make 1way anova. my frame of data q1 sex 1 n m 2 y f 3 u f ... 1000 y m could me please ? following on @thilo's , @dwin's comments above: if want analyze relationship between 2 categorical variables, might try this: ## make random data (no real pattern) dat <- data.frame(q1=sample(c("n","y","u"),size=1000,replace=true), sex=sample(c("m","f"),size=1000,replace=true)) dtab <- with(dat,table(q1,sex)) chisq.test(dtab) mosaicplot(dtab) it helpful point of view of answering questions have more context: question trying answer? also, always, it's nice have reproducible example (just save time of coming own way of generating fake data play with). one small point pearson chi-square test testing association; doesn't distinguish between response , predictor variables anova framework does. of course, if have contin...

uiimagepickercontroller - iphone: show UIImagePicker in UIview -

i have situation here please me in this, can show imagepicker in view insted of presenting them in modalview i tried code doesnt work uiimagepickercontroller *picker=[[uiimagepickercontroller alloc] init]; picker.delegate=self; picker.sourcetype=uiimagepickercontrollersourcetypesavedphotosalbum; //[self presentmodalviewcontroller:picker animated:yes]; [imagepickerview addsubview:picker.view]; please shed light on thanx in advance the uiimagepickercontroller needs shown modal, think.. uncomment line. http://developer.apple.com/library/ios/#documentation/uikit/reference/uiimagepickercontroller_class/uiimagepickercontroller/uiimagepickercontroller.html

iphone - Keyboard notifications after modal dialog -

i have uitableviewcontroller rows containing textfields, , other rows show modal view. register uikeyboardwillshownotification , uikeyboardwillhidenotification in viewwillappear , , unregister in viewwilldisappear . next this: - click on textfield. uikeyboardwillshownotification , resize table have place keyboard. - select row presents modal view controller, receive uikeyboardwillhidenotification , , viewwilldisappear called. - after closing modal view controller, viewwillappear called, , uikeyboardwillshownotification . no keyboard shown. table resized, no keyboard appears. is bug in sdk? or common behavior , i'm missing something? your logic seams correct me. wonder possible problem registering uikeyboardwillhidenotification every time viewwillappear . try register once in viewdidload , unsubscribe in dealloc . thinking maybe when register again after dismiss modal view notification center sends old notification. if register once notification not more post...

Displaying a Drupal content type field outside of a node -

i have created custom field on content type in drupal 7 need display outside of node, in separate area on page. similar how $title variable works (in can place in page.tpl.php file) able create variable called $subtitle call data current node , allow me print out variable in area on page.tpl.php file. i've seen view examples seeming use views , blocks accomplish task, seems bit excessive , wondered if there easier way. there easier way, need bear in mind though not every page node page, , not every node page of right content type should selective. add theme's template.php file: function mytheme_preprocess_node(&$vars) { $node = $vars['node']; if ($node->type == 'my_type') { $vars['subtitle'] = $node->field_my_field[language_none][0]['value']; } } then in page.tpl.php should this: if (isset($subtitle)) : echo $subtitle; endif; make sure clear caches (at admin/config/development/performance) once you...

Python matrix problems -

this continued thread: python matrix, solution? input from numpy import * import numpy x=[['1','7'], ['1.5', '8'], ['2', '5.5'], ['2','9']] code y = x[:, :, none] * x[:, none] print y.sum(axis=0) i received error: "list indices must integers, not tuple" but if x x = numpy.array([[1, 7], [1.5, 8], [2, 5.5], [2, 9]]) it's ok, don't have such input . convert x numpy array of numbers: x = numpy.asanyarray([[float(z) z in y] y in x])

how to use map properly when passing through method inside class in c++ -

i can't make map work class, what's wrong here? can't figure out, please help: #include <map> #include <iterator> class base { public: bool delete_lowest(map<char, double> &frequencies) { double min=1; char del ; box b1; (iterator itr = frequencies.begin(); itr != frequencies.end(); ++itr) { if(itr->second < min) { min= itr->second ; del= itr->first ; } } frequencies.erase(del) ; return true; } i getting errors "map not declared" , on. think way code not proper way. how proceed? thanks map in std namespace. try bool delete_lowest(std::map<char, double> &frequencies)

c++ - Specific things with type cast operator -

#include <iostream> using namespace std; struct { a(int a):a(a){} int a; }; struct b { operator a() { return 10; } }; int main() { b b; cout << ((a)b).a << endl; return 0; } this code compiles , prints 10 in visual studio. in wikipedia next cast operator found sentence: note: user-defined conversions, return type implicitly and necessarily matches operator name. now how code above works? feature of visual studio? or shoud match implicitly? operator a() user-defined conversion operator. it's job return a by-value when cast b a . your operator a() function returning literal integer value, 10 . operator a needs return a , a 's convert constructor called value 10 . results in temporary a being constructed. accessing .a on temporary object, , inserting value of .a in stream, results in seeing 10 on screen. edit when wiki said converstion operator "implicitly" returned a , m...

Flash Media Server: How to fully protect stream? -

i developing lightweight protection mechanism on fms. currently, can authenticate user using sso token provided main server. however, authenticating sso token requires webservice/remoteobject of server, expensive , unrealistic large number of concurrent users. hence, created session each validated user, returned session id user , user can use further connections. what have concern in solution session hijacking attack. imposter can use session id stream, if sniffed customer's request. prevent this, have 2 solutions: first, every client create 2 connections server, 1 ssl control message (e.g. netconnection.call function), 1 streaming data. other creating secured rtmpe channel stream. both require more processing power implement (15% more latter, don't know how former). is there better solution problem? there's no way can prevent session token being hijacked without communication between fms , sso server. the least create single use token when client goes th...

facebook - og:video doesn't work -

this video want share on facebook: http://evahd.com/vutzn and facebook post: http://www.facebook.com/permalink.php?story_fbid=108674929242461&id=100003033559409 everything works fine (thumb, link, title, description) except embeded video white empty flash video the debug platform indicate og meta tags correct any ideas how find out what's wrong, how debug thing ? thank you

C, Calculating the distance between two GPS locations? -

if have 2 gps locations, 51.507222, -0.1275 , 48.856667, 2.350833, formula use calculate distance between two? i've heard lot haversine formula, can't find information it, or how apply c. i've written following code, however, it's innacurate. know why? can't figure out. problem comes function itself, don't know is. float calcdistance(float a, float b, float c, float d) { float dlat; float dlon; dlat = (c - a); dlon = (d - b); dlat /= 57.29577951; dlon /= 57.29577951; float v_a; float v_c; float distance; v_a = sin(dlat/2) * sin(dlat/2) + cos(a) * cos(c) * sin(dlon/2) * sin(dlon/2); v_c = 2 * atan2(sqrt(v_a),sqrt(1-v_a)); distance = r * v_c; return distance; } this page has block of javascript i'm sure adapt enough in c: var r = 6371e3; // metres var φ1 = lat1.toradians(); var φ2 = lat2.toradians(); var Δφ = (lat2-lat1).toradians(); var Δλ = (lon2-lon1).toradians(); var = math.sin(Δφ/...

Sql Server Performance And Order Of Fields -

does order of fields creation in table effect on performance of commands on table? if answer yes, can discuss it? for example have create table this create table software(int id,alpha datetime,beta datetime,title nvarchar(100),stable datetime,description nvarchar(200) ) if change to create table software(int id,alpha datetime,beta datetime,stable datetime,description nvarchar(200),title nvarchar(100) ) is there performance effect ? is clear? the field order makes no difference whatsoever (if fields same of course) the on-disk structure remain same pretty regardless. simply: header fixed length columns null bitmap variable length columns all you're doing above rearranging columns inside "fixed length" , "variable length" sections. however, same processing required retrieve them no matter order in. see paul randal's article

sql - Text values in a pivot table? -

i have table (in mysql) 3 columns: location category supplier computers company x printers company y b computers company x b printers company y b software company y c computers company y c software company z now need make matrix containing above information, : computers printers software company x company y b company x company y company y c company y company z eventually need have in excel. in reality have variable number of categories, doing in mysql join each column not option. write function in php, wondering if there's more elegant solution. i looked pivot tables in excel, seem more suited numbers values. maybe i'm overlooking something, since never work excel myself. any idea's? i ran same problem pivot tables... perfect summaries, not text matrices. i have "lifted...

c# - LINQ doesn't provide a byte[] data type for storing files -

i'm trying store file in sql server database , using asp.net mvc 3 linq to sql in c#. when try set data type of column byte[] says invalid data type. using vrabinary(max) data type instead seems logical thing do. the goal store pdf files in database user has elected upload using http file uploader. error occurs during assignment of linq member variable refers column file stored. error 3 cannot implicitly convert type 'system.web.httppostedfilebase' 'system.data.linq.binary' c:\users\aaron patten\documents\visual studio 2010\projects\myapp\myapp\controllers\mycontroller.cs 66 31 myapp i haven't found in way of other people encountering problem, think there must i'm missing elementary post. my controller: public actionresult uploadpdf() { list<viewdatauploadfilesresult> r = new list<viewdatauploadfilesresult>(); httppostedfilebase hpf;// = request.files[file] httppostedfilebase; ...

html - create app which required visitors to click like or subscribe to email newsletter -

i want create app included in facebook fan page. app have 2 things: 1. protect wall, wall posts visible people clicked on page, 2. have textbox , button , users able signup our newsletter. idea how can 1 or both of them? you can't hide wall people not fans. if create custom fan page tab, can set default landing tab page. facebook documentation shows want need build sign page describing. require custom coding store emails somewhere.

html - show/hide with CSS -

hello i'm making mailbox website , want show/hide css3 know there few tutorial etc on how it, tried bit differently. i'm getting result, there 1 issue. when hover on item item :hover height not changing text: styles.css: .mailbox_item { width: 440px; height: 20px; margin: 0 auto; border-bottom: 1px solid #ccc; overflow: hidden; } .mailbox_item:hover { min-height: 100px; overflow: visible; display: block; -webkit-transition: 0s ease-in-out; -moz-transition: 0s ease-in-out; -o-transition: 0s ease-in-out; -ms-transition: 0s ease-in-out; transition: 0s ease-in-out; } .mailbox_item_top { min-height: 20px; line-height: 13px; } .mailbox_item_body { min-height: 20px; } item.php <div class="mailbox_item"> <div class="mailbox_item_top"> <h2 class="titleannouncement">test announcement</h2> <span class="mail_author"...

sql server - Problem with unique SQL query -

i want select records, have query return single record per product name. table looks similar to: sellid productname comment 1 cake dasd 2 cake dasdasd 3 bread dasdasdd where product name not unique. want query return single record per productname results like: sellid productname comment 1 cake dasd 3 bread dasdasdd i have tried query, select distict productname,comment ,sellid tbl#sells but returning multiple records same productname. table not realy simple this, sample. solution? clear? select productname, min(comment) , min(sellid) tbl#sells group productname if y ou want 1 record per productname, ofcourse have choose value want other fields. if aggregate (using group by) can choose aggregate function , htat's function takes list of values , return 1 : here have chosen min : smallest walue each field. note : comment , sellid can come different records, s...

c++ - Qt- How to use connect between incompatible signal and slot -

i trying game. in want call function, function receive point . function should invoked timer's timedout signal. can how achieve this. below required/error code point p(a,b); connect(timer,signal(timedout()),this,startdestruction(p)); can how achieve this? create method use intermediate slot, this. point p(a,b); connect(timer, signal(timedout()), this, q); q() { startdestruction(this->p) }

php - Image gallery display like zoom in using jquery -

please below url, http://www.wix.com/sujatatibre/wwwwixcomsujatatibre in site displaying slideshow using flash. can display images using jquery that?. surf web can't find jquery that. maybe can contentflow , fancybox .

iphone - How to load images in UIScrollView asynchronously? -

hi, i getting images using json , need display image @ time when app running please tell me how use asynchronous method load images uiscrollview ? thanks. whether use uitableview or uiscrollview, use same pattern, have bit more plumbing uiscrollview. use uitableview unless want roll own multi-column image thumbnail picker. with uiscrollview, need create own virtual rows , columns , detect when scrollview has scrolled new row or new column view. need queue (remove) images have scrolled out of view, , load images have come view. in all, not trivial code. the uitableview (rows only, no concept of columns) having said that.. here reference using nsoperation class lazy load images uitableview while giving user smooth experience.. uiimage in uitableviewcell slowdowns scrolling table

how to change android webview context menu(open, open inOpen in new window, bookmark link ...)? -

when, used long press on web link(url) on web page, android display context menu actions (open, open in new window, bookmark link, save link, share link, …. ). per under stand these options provided android. how can customize above context menu , add 1 more action context menu?

wcf security - Implementing Basic Authentication in WCF -

i've requirement implement basic authentication in wcf user credentials stored in database instead of active directory. whenever client call service method i've username & password soap headers , authenticate using database. can body point out references implement this? note: service using basic-http binding. what want use? combining multiple authentication strategies because basic authentication refers basic http authentication , doesn't use soap header. uses http header. if want use basic http authentication choices differ hosting type: in self hosting scenario , wcf 4 should able validate credentials custom password validator in iis hosted service need custom authentication module because default authentication goes against windows accounts if want use authentication based on soap header can again use custom password validator.

c++ - More than one construction matches argument list -

i tried compile vs2010 long long min = std::numeric_limits<int>::min(); unsigned long long max = std::numeric_limits<int>::max(); std::bitset<64> minimal(min);//here i'm getting error cout << "minimal: " << minimal; error: error c2668: 'std::bitset<_bits>::bitset' : ambiguous call overloaded function 1> 1> [ 1> _bits=64 1> ] 1> c:\program files\microsoft visual studio 10.0\vc\include\bitset(136): 'std::bitset<_bits>::bitset(_ulonglong)' 1> 1> [ 1> _bits=64 1> ] 1> c:\program files\microsoft visual studio 10.0\vc\include\bitset(127): or 'std::bitset<_bits>::bitset(int)' 1> 1> [ 1> _bits=64 1> ] 1> while trying match argument list '(__int64)' ...

php - Checking a constant for security reason -

some applications use code first line on every page included index.php : if (!defined('secure_const')) { die("access denied!"); } why need use this? necessary security? if yes, how can use properly? it's done ensure files not executed directly. example: /index.php <?php define('secure_const', 1); include 'include_me.php'; ?> /include_me.php <?php if (!defined('secure_const')) { die("access denied!"); } ?> then, if http://example.com/index.php requested secure_const defined , die() not invoked when include_me.php included. however, if http://example.com/include_me.php requested directly, secure_const never defined , script bails. if web server configured securely--i.e. files not intended accessed directly outside web root or in directory made inaccessible e.g. .htaccess --this should unnecessary. developers use "security" measures because assume, rightly, many people u...

Computed Column Help - TSQL -

create table [dbo].[tbllocations]( [latitude] [float] not null, [longitude] [float] not null, [location] [varchar](500) not null, [timestamp] [datetime] not null, [point] [geography] geography::point(latitude, longitude, 4326) not null ) giving me bad syntax @ word as . isn't how declare computed column? you don't declare datatype or nullability yourself create table [dbo].[tbllocations]( [latitude] [float] not null, [longitude] [float] not null, [location] [varchar](500) not null, [timestamp] [datetime] not null, [point] geography::point(latitude, longitude, 4326) ) in general sql server assume column nullable unless add isnull() around formula . however tried following column definition [point2] isnull(geography::point(latitude, longitude, 4326), geography::stgeomfromtext('linestring(-122.360 47.656, -122.343 47.656)', 4326)) and still shows is_nullable in sys.computed_columns doesn't appl...

java - How to detect ctrl-f in my SWT application -

i have written swt ui has primary function of displaying text in styledtext control. want add handler ctrl + f when shortcut pressed focus set search box. have tried using following code detect keypress. swindow = new shell(); ... swindow.getdisplay().addfilter(swt.keydown, new listener() { @override public void handleevent(event e) { system.out.println("filter-ctrl: " + swt.ctrl); system.out.println("filter-mask: " + e.statemask); system.out.println("filter-char: " + e.character); } }); i expecting when pressed ctrl + f see following output: filter-ctrl: 262144 filter-mask: 262144 filter-char: f however, in practice see following. filter-ctrl: 262144 filter-mask: 262144 filter-char: <unprintable char - displayed box in eclipse console> i have 2 questions: is display.addfilter(...) best way add global shortcut? tried display.addlistener(...) didn't receive events @ all. why don't pressed character whe...

What is the difference between Java Deployment Toolkit Plug-in and deployJava.js? -

i reading article: http://www.java.com/en/download/faq/deployment_toolkit.xml and confused purpose , use of dt plug-in , deployjava.js. i believe deployment toolkit set of functions of deployjava.js file (like link says: http://blogs.oracle.com/thejavatutorials/entry/deployment_toolkit_101 ) according article there 2 parts of deployment toolkit: plug-in , interface developer. i'm asking of because deployjava.js fails detect appropriate version of java in of machines of our users , wondering if dt plug-in improve detection, don't know how detects java version , when or how can use solve detection problems? most of doubts driven question in article: " does deployjava.js work if java dt toolkit plug-in disabled? yes, deployjava.js contains pure javascript functions, continue work if java dt toolkit plug-in disabled." so... why need deployjava.js if dt plug-in exists or vice versa? any on matter appreciated. thank much. if has doubts it, i...