Posts

Showing posts from March, 2012

asp.net - Can you help with this MVC ViewModel issue? -

i have problem mvc view cannot seem solve. here is. 1) have index view displays list of retailers data retailers table. far good. 2) want include retailer categories each retailer stored in retailerscategories table each retailer can have multiple categories i have tried few things cannot seem make work. closest came wanted using view model. have included code below. i right data of retailer records , of category records. what need 1 retailer record @ time of categories relate retailer. can show me how can achieve this? //controller public actionresult index(int? page, int country) { var viewdata = new retailersindexviewmodel(_retailerrepository.getallretailersbycountry(country), _retailerrepository.getretailercategories()); return view(viewdata); } // viewmodel public class retailersindexviewmodel { public ienumerable<retailersshipping> retailershipping { get; set; } public ienumerable<retailerscategory> retailercateg

asp.net - Html.ValidationSummary showing duplicate error messages -

i have searched , googled answer question no avail. i'm using ef4 , asp.net mvc2 , have ef4 entity "award" non-nullable string field, "recipientid". i'm using dataannotations server-side validation, in "award" partial class i've set recipientid have required attribute. when try submit form recipientid text box empty, see error message "please enter recipient" in html.validationsummary twice. would because error being thrown both entity (in non-nullable field null value), application? whatever reason, there way "fix" , have error message show once? (fix being in quotations because i'm not sure if intended behavior or not.) didn't think necessary include relevant code, if it's needed. thank in advance help. it looks intended, according brad wilson . should have searched "constraintexception" , ef4. :) according brad, input validation fired before model bound resulting in "requi

python - Matplotlib transparent line plots -

Image
i plotting 2 similar trajectories in matplotlib , i'd plot each of lines partial transparency red (plotted second) doesn't obscure blue. edit : here's image transparent lines. plain , simple: plt.plot(x, y, 'r-', alpha=0.7) (i know add nothing new, straightforward answer should visible).

xpath - HtmlUnit getByXpath returns null -

i coding groovy, however, don't believe language specific set of questions. i have 2 questions first question i've run issue while using htmlunit. telling me trying grab null. the page i'm testing on is: http://browse.deviantart.com/resources/applications/psbrushes/?order=9&offset=0#/dbwam4 my code: client = new webclient(browserversion.firefox_3) client.javascriptenabled = false page = client.getpage(url) //coming null title = page.getbyxpath("//html/body/div[4]/div/div[3]/div/div/div/div/div/div/div/div/div/div/h1/a") println title this prints out: [] is because page uses onclick() ? if so, how around that? enabling javascript creates mess in cmd prompt. second question i wanting image having trouble because when attempt xpath (via firebug) shows as: //*[@id="gmi-resviewsizer_img"] how handle that? first answer: /html/body/div[3]/div/div[3]/div/div/div/div/div/div/div/div/div/div/h1/a your xpath off 1 in

How to retain/recall values of tableLayoutPanel of child form from main form button in C#(Visual Studio) 2010? -

i have 2 questions , need guidance 1) please guide me how retain/recall textboxes values of tablelayoutpanel of child form button click event of parent form in c#., scenario , have filled out values in textboxes of tablelayoutpanel in child form , return parent form . if want see/review values of (previously) filled textboxes values of tablelayoutpanel of child form, can that? please suggest me solution., 2)can redraw rows/columns of tablelayoutpanel dynamically upon changing user input(of rows/columns) . please remember in case need discard previous 1 , redraw tablelayoutpanel on again.please suggest how discard previous one? thanks , regards, asad this answer may partially towards resolving query one. for second query, can perhaps override onpaint event might mean custom drawing all controls on form, herculean task depending on how many other controls present.

ipad - Can I cache/store larger files within my native Iphone App -

we looking write app can locally store short videos , pdfs server offline viewing. possible? if so, how storage capacity allowed. so, can pull down 1gb of video view later in app? yes. up storage capacity of device. yes. note ios offers separate temporary, cache , documents folders storage. should aim use temporary or caches folder storage because documents folder backed when syncing itunes, slow if there large files transfer.

java - Fedex checksum algorithm for tracking numbers? -

how validate potential fedex tracking numbers, without hitting web service? i've heard fedex employs modified version of luhn algorithm. check google answer . there different algorithm ground , express.

Can we debug inline javascript through firebug and have break point -

we debug javascript files .js having breakpoing in firebug , there way debug inline javascript inside page. we have lot of inline code in page , let me know if there efficent way of debugging. thanks you can use firebug debug javascript between <script> tags.

nhibernate - How to handle null when comparing equality of value objects? -

note: use c# example, problem virtually same in java , many other languages. assume implement value object (as in value object pattern m. fowler ) , has nullable field: class myvalueobject { // nullable field (with public access keep example short): public string myfield; } then, when overriding equals(), how treat case when both value objects have myfield set null? equal or not? in c#, treating them equal seems obvious, because: this behaviour of equals() when use c# struct instead of class , not override equals(). the following expressions true: null == null object.referenceequals(null, null) object.equals(null, null) however, in sql (at least in sql server's dialect), null = null false, whereas null null true. i wondering implementation expected when using o/r mapper (in case, nhibernate). if implement "natural" c# equality semantics, may there ill effects when o/r mapper maps them database? or maybe allowing nullable fields in val

Why not python implicit line continuation on period? -

is there reason python not allow implicit line continuations after (or before) periods? is data.where(lambda d: e.name == 'obama'). count() data.where(lambda d: e.name == 'obama') .count() does conflict feature of python? rise of method chaining apis seems nice feature. both of situations can lead valid, complete constructs, continuing on them complicate parser. print 3. 1415926 print 'hello, world' .lower()

iphone - UIImagePickerController not working for iOS 3 yet works for iOS 4...backwards compatibility issue -

so created entire app , works flawlessly way envisioned. created update uses uiimages, , works on ios 4 , above. reason exact same code not work same on 3.0. since original app on store @ min os being 3, not want cut off user base because of silly mistake on part. i'm not doing new, should backwards compatible. basically app takes image chosen either camera or photo album , saves it, , displays image on screen. when go next screen pulls image file off disk , displays in image view on next screen. again, works fine on ios4 , above. using 3.0 sim on older version of xcode, not function same way. know allowimageediting changed allowediting, allowed that, else seems according docs, should work on ios 3 , above. below going photo album , returning. -(ibaction) getphotofromalbum { uiimagepickercontroller *picker = [[uiimagepickercontroller alloc] init]; picker.delegate = self; if (editingswitch.on) { #ifdef __iphone_3_0 picker.allowsimageediting = yes; #else

NSIS - Delete all files except one file -

could 1 clarify me that, when uninstalling need delete form installation folder except license file. how can nsis scripting? thanks regards, roboalex. instead of opening file, in anders' third point, i'd way: rename $instdir\license.txt $pluginsdir\license.txt rmdir /r $instdir # remembering, of course, should care createdirectory $instdir rename $pluginsdir\license.txt $instdir\license.txt depending on when gets file can't delete, rmdir /r may leave of behind, believe stop when can't delete something; way rid of properly. lose directory stats, that's not important. i'd recommend 1 of anders' first 2 solutions on this, though. they're more precise.

eclipse - Android Project Type -

i'm working on eclipse plugin android. in order make plugin controls visible if selected folder project added org.eclipse.core.resources.iproject as object class in plugin manifest. however, makes controls visible eclipse project. there possibility make plugin visible android projects? did not find interface iandroidproject. regards, florian i figured out type iproject can use natures instead.

JSP url argument passing -

is there way pass params function in way:       www.smth.com/func.jsp/1/2/3 not this:       www.smth.com/func.jsp?a=1&b=2&c3 using php define method       function func($a, $b, $c) {       ...       } of course can write       www.smth.com/func.jsp?1&2&3 not clean as       www.smth.com/func.jsp/1/2/3 thank you you can use urlrewritefilter this. it's similar apache's mod_rewrite .

html - How to format a sentence in seam -

i trying format html sentence <span>x<sup>2</sup> + y<sup>2</sup> = ____</span> using <s:formattext/> . string "____" not formatted correctly. how sentence xpow(2) + ypow(2) = _____ after formatting. note: have surrounded _ _ apostrophe show in stackoverflow editor properly the _ special character, used underlining. try escaping it: \_\_

asp.net - Passing complex JSON data jQuery to Action -

i have 2 classes used mirror data ajax call. 1 ( customer ) contains property name, , other array of products . public class customer private _name string private _products product() public property name() string return _name end set(byval value string) _name = value end set end property public property products() product() return _products end set(byval value product()) _products= value end set end property and ajax call: $.ajax({ url: '../../customer/savecustomerdata', type: "post", datatype: "json", data: { "name": this.name, "products": [{ "productcode": "product 1", "productname": "product 1" }, { "productcode": "product 2", "productname": &qu

Large ChildWindow from small Silverlight control? -

i have developed silverlight control shows list of documents. takes or little space integrating developer likes. however, when users adds documents use childwindow bunch of metadata before document uploaded. dialog can large. we've found way go full-screen think surprise users (and not in sense of surprise , delight!). there better way allow dialog use more screen space parent silverlight container? interesting question. moment, thought circumvent issue opening true or fake html popup calling host page's javascript. popup silverlight instance big necessary. however, solution has several challenges: list item you need fake 'modalness' of original sl instance and/or host page you need fiddle javascript, though largely alleviated using jquery the target sl instance should sized childwindow covers entire surface in order hide fact there instance here you'll need establish way communicate data acquired in childwindow original sl instance; ca

PHP fix image bytes -

i'm gonna strart use case, before i'll explane problem i'm running in to. i'm building mobile application using phonegap framework. application need upload file (a picture made camera). on platforms can image base64 encoded image. can send server, , can decode , save it. (and other funcy stuff it's qr code). now on symbian, can't base64 string, , can uri image. isn't problem, becouse can use xmlhttprequest image data , encode base64 using javascript. this methode works, gives me problem. symbian browser appears have bug. it's webkit based browser 2005 (yes, it's old, on newest s60 phones). bug converts characters doesn't know (not in utf-8 table) 2 bytes. if remember correctly above 127. i have tried fix bug using javascript, no go (btw, canvas , getbinaries or not supported canvas 2d not supported browser). so, try build workaround in php fix bytes. have right now, though it's not working: function getvalidbin($bin, $of

android - General application design (IntentService/ContentProvider/AsyncTask) -

i'm trying figure out best general design applications access several web services , have multiple activities information displayed. the way implemented latest android application following. have intentservice receives requests activities information web services. service notifies activities through resultreceiver status of request (started/error/finished). after calling web service, getting result(xml/json) , parsing it, put information in contentprovider (backed sqlite database) , use contentresolver notify activities changes. activities notified changes (some use contentobserver , others use simplecursoradapter s , notified automatically). now, problems approach: every time enter activity, request info web service through method described above , delete rows in particular table, fill new info , notify activity. so, if user presses , enters again, whole dance again. think should add fields in database when last updated etc. don't know how proceed that. sugges

iphone - Orientation after if statement -

i have code calls method (one un comment out use) // override allow orientations other default portrait orientation. - (bool)shouldautorotatetointerfaceorientation:(uiinterfaceorientation)interfaceorientation { // return yes supported orientations nslog(@"so orientation %d", orientationinteger); //1 button left, 0 right. if (orientationinteger == 1) { return uiinterfaceorientationlandscapeleft; nslog(@"setting orientation landscape left"); } if (orientationinteger == 0) { return uiinterfaceorientationlandscaperight; nslog(@"setting orientation landscape right"); } else { return (interfaceorientation == uiinterfaceorientationlandscaperight); nslog(@"no instructions regarding orientation."); } } however, orientation not change, nor log messages after first fire. nslog(@"so orientation %d", orientationinteger); gives 'so orientation 1' or 'so orientation 2' sometimes.

How do I stop a Git commit when VI is on the screen waiting for a commit message? -

i have asked git perform commit within git bash, has brought vi does. i wish cancel commit, how prevent proceeding commit point? you have 2 options: provide empty commit message. if it's new commit , haven't yet saved message, can use :q! (quit without saving). if you’ve saved (or you're amending previous commit), delete entire log message , save again. can done ggdg + :wq in vim. have editor exit non-zero exit code. in vim, can use :cq (quit error code). it's worth noting can reset working copy state in before commit git reset head^ .

php - Translating .htaccess to web.config -

i hosting php application on virtual windows server running iis. the person wrote php website me asked me put piece of codes in .htaccess: <ifmodule mod_rewrite.c> rewriteengine on rewritebase / rewritecond %{request_filename} !-f rewritecond %{request_filename} !-d rewriterule . /index.php [l] </ifmodule> but application running on iis, need translate piece of codes web.config. 1 have experience this, please me translate them web.config? thanks in advance! what htaccess code redirecting requests otherwise result in 404 error (!-f , !-d mean "file not exist" , "dir not exist") /index.php. iis7 has feature import mod_rewrite rules - use this: start iis manager. on left, in connections pane, select default web site. on right, in features view, click url rewrite. on right, in actions pane, click import rules. copy mod_rewrite rules , paste them rewrite rules text box. the tree view tab of converted rules box instantly shows re

javascript - Why is this illegal in strict mode? -

yeah, yeah, know, strict mode ain't around yet, really, i'm planning future... so, why this: $('#'+ $(this).attr('id').replace('control-', 'legend-')).fadein(); ... not allowed in es5 strict mode? or misinterpreting? jslint: problem @ line 516 character 18: strict violation. could little more verbose, wonder...? edit: to avoid confusion, here's more of original code: function displaylegend() { $('#'+ $(this).attr('id').replace('control-', 'legend-')).fadein(); } some trial-and-error of code in jslint "use strict"; var that="dd"; function $(x){return x;} $('#'+ $(this).attr('id').replace('control-', 'legend-')).fadein(); $(this); shows me what's wrong: you're using this parameter. changing both this es that s doesn't trigger error. as the specification says: if this evaluated within strict mode code,

sql server - Making sense of the number of reads/writes in SQL Profiler -

Image
see sql statements indicated in sql profiler view. these events coming 1 client machine busy long-running process, working through couple thousand rows. each processing of row takes 6.5 seconds, sql profiler showing time between logouts, though actual update statement takes 1ms. each login/logout uses same spid. see between given login , logout event, sql statements indicate reads count of 17 , writes count of 0. yet, logout event indicates total reads count in excess of 2million , writes count in excess of 10k. events need profiling try figure out statement causing reads/writes, because suspect ones causing 6.5 second delay, yet can't see them happening? the reads/writes figures given audit:logout event cumulative totals duration of connection. in itself, values don't tell detail - if run 10 commands within lifetime of connection, you'll seeing total figures 10 commands within session. to know breakdown statement, need @ sql:batchcompleted (or sql:stm

iphone - <video> causes many requests *before being clicked* -

even preload disabled, simple <video> tag <video src="video.mp4" preload="none"></video> will cause 10 requests server before being clicked : 89.212.77.133 - - [01/dec/2010:11:48:43 +0100] "get /temp/html5-video-requests-test/one-noposter.html http/1.1" 200 267 "-" "mozilla/5.0 (iphone simulator; u; cpu iphone os 4_0_2 mac os x; en-us) applewebkit/532.9 (khtml, gecko) version/4.0.5 mobile/8a400 safari/6531.22.7" 89.212.77.133 - - [01/dec/2010:11:48:43 +0100] "get /temp/html5-video-requests-test/video.mp4 http/1.1" 206 2 "-" "applecoremedia/1.0.0.8a400 (iphone simulator; u; cpu os 4_0_2 mac os x; en_us)" 89.212.77.133 - - [01/dec/2010:11:48:43 +0100] "get /temp/html5-video-requests-test/video.mp4 http/1.1" 206 8621463 "-" "applecoremedia/1.0.0.8a400 (iphone simulator; u; cpu os 4_0_2 mac os x; en_us)" 89.212.77.133 - - [01/dec/2010:11:48:43 +0100] &

xml - xsd:unique with optional attributes -

i have xml file: <objects> <object name="id1" /> <object name="id2" /> <object name="id2" color="green" /> <object name="id3" color="green" /> <objects> i validate against xsd schema, combination between name , color unique in document. the problem that, if use: <xs:unique name="uniqueobjectnamecolor"> <xs:selector xpath="./object" /> <xs:field xpath="@name" /> <xs:field xpath="@color" /> </xs:unique> ... rule ignore object elements without optional color attribute. following validates correctly while shouldn't. <object name="id2" /> <object name="id2" /> can tell me how can specify rule enforces unique name , color combinations and, when color attribute not present in element object , checks name ? use use , default or without value

php - MembershipProvider.GetPassword algorithm -

we converting asp site (using dotnetnuke) new php site. thing have right full export of existing database. 1 of tables called "aspnet_membership" , contains following fields: password (looks base64) passwordformat (always value 2) passwordsalt (looks base64) passwordquestion (always empty) passwordanswer (always empty) we decode these passwords , hash them fit our own framework. understand .net documentation these kind of passwords can decrypted. there algorithm available can or more complicated that? possible if create asp script on current server? thanks in advance i think 2 means "encrypted", not "hashed" (see definition here ) encrypted means can decrypt need machine key stored in configuration files (take @ link sent) of physical machine these passwords created. if have copy of database, can't it.

algorithm - Gaussian Distribution + Hash Tables -

i had weird idea hashing function. problem statement is you storing id-numbers of 162 students in class obtaining n marks out of 300 in course (for each n=0, 1, 2, ... 300) in hash table. devise simplest , least collision prone hash function such wasted memory cells minimum. here, collision when 2 students scoring n 1 , n 2 same slot in hash table. one solution can use h(n) = (n*5 + 7) % 163 along chaining. there can @ 162 distinct marks. edit there can several standard ways this. i'd try idea , check (maybe mathematically). might have lesser collisions lesser memory. now, here's idea had. can assume distribution of marks gaussian . so, there more people near average score , lesser @ extremes. so, can have hash function this: h(n) = 0 (if n<100 || n>200) h(n) = 1 (if 100<=n<125 || 175<=n<200) h(n) = 2 (if 125<=n<140 || 160<=n<175) h(n) = 3 (if 140<=n<160) for such conditions

decompression - django multiwidget subclass not calling decompress() -

i trying implement multivaluefield ip adress/domain name entries. works expected entering data. problem if want display form bound specific data, ip address/domain name field stays empty. other fields filled desired data. if use normal charfield, data expect. not work custom field. have tracked down fact custom multiwidget not call decompress method. here field: class accessipfield(forms.multivaluefield): """ custom field access ip """ def __init__(self, *args, **kwargs): self.fields=( forms.ipaddressfield(label='ip adress'), forms.charfield(max_length=50,label='domain na

.net - What is the difference between NetworkStream and Socket classes? -

i have project might want abstract communication between client , server. using sockets , tcp. thought might nice able switch inter process communication channel. looked @ system.io.pipedstream class , saw there lot of overlap between pipestream , socket class. when had @ socket class inherits object. there no common interface or abstract class between socket , pipestreams. i remembered networkstream. apparently wraps socket class. @ least both networkstream , pipestream inherit stream. means can swap implementation out. think, haven't tried yet. have been using sockets time. so question is: there disadvantage using networkstream class on socket class. gotchas or watch out for? if forced use low level options such sockets , pipes, , want abstraction pulling streaming data data sources stream class perfect, provides abstraction model. if code against stream instances, can have implement stream, , not worry underlying transport. in reference using networkstream

wpf - Static resource shared in merged dictionaries -

i'm working on having dictionaries of styles , templates can dynamically apply application. before "new wanted" dynamical behavior, had several resource dictionaries, 1 each styled control, merged in app.xaml: <application.resources> <resourcedictionary> <resourcedictionary.mergeddictionaries> <resourcedictionary source="colorsdictionary.xaml"/> <resourcedictionary source="controlstemplatesdictionary.xaml"/> </resourcedictionary.mergeddictionaries> </resourcedictionary> </application.resources> now, i'd application styled, decided merge previous resources new 1 called "myfirsttemplates" , add dictionary app.xaml. new dictionary "myfirsttemplates.xaml": <resourcedictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml

c# - Page Methods throwing Undefined -

i trying use page methods call function , getting "pagemethods undefinded" error. have used them before whilst using c# not vb i'm wondering if syntax wrong examples can find c#. wondering if it's because scriptmanager on master page? i've read error everywhere have appears correct! can point me @ doing wrong? thanks! my code: part of master page <form id="form1" runat="server"> <asp:scriptmanager id="scriptmanager1" runat="server" enablepartialrendering="true" enablepagemethods="true" > </asp:scriptmanager> <div id="header">~~~~~ content page html <asp:content id="content1" contentplaceholderid="head" runat="server"> <script type="text/javascript"> function selectzones(commaseparatedlist){ pagemethods.zones(commaseparatedlist); } </script> </asp:content>

iphone - UISwitch - change from on/off to yes/no -

does know of way can change text label on , off yes , no. i did ((uilabel *)[[[[[[switchcontrol subviews] lastobject] subviews] objectatindex:2] subviews] objectatindex:0]).text = @"yes"; ((uilabel *)[[[[[[switchcontrol subviews] lastobject] subviews] objectatindex:2] subviews] objectatindex:1]).text = @"no"; however, release of ios 4.2, no longer supported (this wasn't recommended apple anyway) my client insisting on yes/no switches. i'd appreciate advice! many thanks you need implement custom uiswitch that. or use 1 of implemented :) (check this question , this post )

iphone - Custom control doesn't display in window -

i'v created view based application. , added new class extends uiview. class contains controls in (simple controls). want display/hide control when user click on something. control should displayed overlay window. on other controls. try like: - (void)viewdidload { [super viewdidload]; addsubview:myoverlaychannelpicker; } everything goes fine, debug in custom control code nothing display on screen. tried add manually , works, need add in runtime. reason not displaying control? complete code overlaychannelpicker @implementation overlaychannelpicker @synthesize myimage; @synthesize img1; @synthesize img2; - (id)initwithframe:(cgrect)frame { if ((self = [super initwithframe:frame])) { // initialization code } return self; } - (void)awakefromnib{ img1 = [uiimage imagenamed:@"imgtest.jpg"]; img2 = [uiimage imagenamed:@"imgtest2.jpg"]; arrayofimages = [[nsmutablearray alloc] init]; [arrayofimages addobje

wpf - Performance penalty of continuous CanExecute calls in Command -

i applying mvvm pattern project. have usercontrol has button bound command exposed viewmodel. since button visible, it's calling continuously canexecute method of button. tells me carries performance penalty, i'm not sure. expected behavior? or there better way of having button bound command? thank you. sorry, found out happening. implementation of relaycommand. public class relaycommand : icommand { #region fields readonly action<object> _execute; readonly predicate<object> _canexecute; #endregion // fields #region constructors public relaycommand(action<object> execute) : this(execute, null) { } public relaycommand(action<object> execute, predicate<object> canexecute) { if (execute == null) throw new argumentnullexception("execute"); _execute = execute; _canexecute = canexecute; } #endregion // constructors #region ico

nginx - How can I get rails/ngnix to cleanup /tmp/RackMultipart* files? -

when user uploads image, files build in /tmp rackmultipart20101130-1130-1l2q8dt-0 rackmultipart20101130-1130-1t11oa9-0 rackmultipart20101130-1130-59nrpq-0 rackmultipart20101130-1130-6jdqem-0 rackmultipart20101130-11807-1usq3d8-0 rackmultipart20101130-11807-nns7dw-0 how can rails / nginx / passenger clean these files after upload finished? i'm using: nginx 0.8.53 phusion passenger 2.2.15 (mod_rails/mod_rack) ruby on rails 2.3.8 paperclip ruby gem upload images the first thing comes mind rake task crontab clear /tmp directory time time. create new rake task in lib/tasks removes rackmultipart* files. execute rake task crontab each x hours. (optional) use whenever simplify step 2 (quite powerful in combination capistrano ) this said better ask paperclip clear files approach above remove temporary file still in use paperclip don't know how that.

php - Manipulate Var Char column in Mysql DB if inserted by VB.Net Now() -

stupidly, way vb.net program insert timestamp mysql db using now() in vb , putting column var char in mysql db. have royally screwed myself or can still pull in php , manipulate data, ie select * test date between...etc. how mysql interpret var char column in terms of dates/times if can't fix table (e.g. change datatype), can use cast() or convert() in sql. see http://dev.mysql.com/doc/refman/5.0/en/charset-convert.html

c++ - Functionality of pointers and references -

i'm pretty beginner @ c++. started learning few weeks ago. i'm interested in improving skills programmer, , there's that's been confusing me in last few days. pointers. pointers , reference operator. question is, functionality of pointers , reference operator? how know when use them, , purposes , common usages. examples consisting of common algorithms using dereference , reference appreciated. how can use reference , dereference become better programmer, , improve algorithms(and possibly make them simpler)? thanks :d definitely check this question out, accepted answer explains pointers , common errors them in nice manner. update: few words of own pointers bunches of bits, other kind of variable. use them because have several convenient properties: their size (in bytes) fixed , making trivial know how many bytes need read value of pointer. when using other types of variables (e.g. objects), mechanism needs in place compiler knows how large ea

caching - How can I override the URL writing mechanism for .script <include-script> tags in Tapestry 4? -

previously on stackoverflow, wrote this question asked how append build number parameter generated urls tapestry assets solve caching problems. answered own question: replace tapestry's default asset source custom 1 wraps generated assets tack on build number. i've found out .js files imported <include-script> tag in .script files not using mechanism , therefore not getting build number on them. i'd accomplish same objective them. how?

postgresql - How to determine what type of index to use in Postgres? -

i have postgres database has 2 columns not primary keys (nor can be), searched on lot , compared equality 2 columns in other tables. i believe perfect case adding index tables. have never used indexing on database before trying learn proper way of doing this. i have learned there multiple types of indexing can pick from. how determine method efficient database? proper method create single index covers both columns? postgres support b-tree, r-tree, hash, gist , gin indexing types. b-tree indexing common , fits common scenarios. syntax: create index idex_name on table_name using btree(column1, column2); here createindex documentation , here more info on different indextypes in postgres. what type of index should use depends on types of operations want perform. if want equality checking hash index best. common operations(e.g. comparison, pattern matching) b-tree should used. have never used gist or gin indexing. guru out there? the documentation describes these

jsf 2 - JSF - Two Questions about actions on UIComponent -

so, let me show troubles :) 1 - when click on commandbutton <h:commandbutton value="somethings"> <f:setpropertyactionlistener target="#{bean.method}" value="some" /> <f:ajax render="rendering"/> </h:commandbutton> i dont action commandbutton . fire ajax call. if add action on button (like action="bean.myaction ) executedat 5° phase of jsf lifecycle (allright, if write event="action" in f:ajax, thats default). right? f:ajax fired cliccing on button default? because listbox example, it's fired if write event="change" (the same, shouldnt write it, because default). 2 - when click on image <h:graphicimage value="img/img.png" alt="img"> <f:setpropertyactionlistener target="#{bean.method}" value="some" /> <f:ajax event="onclick" render="rendering"/> </h:graphicimage> this doesnt work.

graphics - Flipping vertically a raw image in Java -

i need flip in java raw image has rows inverted. inverted mean, first row of image stored @ end of file. i managed achive want reordering image rows using auxiliar buffer. included code below. i think can optimized translating coordinates, avoiding memory copy. tried implement databuffer invert rows, raster i'm using requires databufferbyte (a final class). does knows more optimized way of doing want? thank you ... int w = 640; int h = 480; byte[] flippeddata = new byte[640*480*4]; int scanlinelength = w*4; for(int i=0;i!=h; ++i) { system.arraycopy(originaldata, scanlinelength*i, flippeddata, scanlinelength*(h-i)-scanlinelength, scanlinelength); } databuffer db = new databufferbyte(flippeddata,flippeddata.length); writableraster raster = raster.createinterleavedraster(db, w, h, scanlinelength, 4, new int[]{2,1,0}, new point(0,0)); colorspace cs = colorspace.getinstance(colorspace.cs_srgb); colormodel cm = new componentcolormodel(cs, false, false, transparency.opaqu

Ant script passing arguments to Batch file -

i have ant script need call batch script follows: <exec dir="${basedir}\work_internal\${platform}" executable="cmd.exe"> <arg line ="/c example.bat 'c:\work_internal\${platform}' 'revn=120 special_objs='a b''" /> i need pass arguments example.bat, first argument directory , second argument 'revn=120 special_objs='a b'', special_objs='a b' 'a b' must in quotes. when calls bat script, discards quotes around 'a b' in second argument interpreted revn=120 special_objs= b. how can make read revn=120 special_objs="a b"? the single quotes don't pair how want them to, aught able embed single quotes using &quot; entity - like: <arg line=" ... &quot;revn=120 special_objs='a b'&quot;" /> for me ant -verbose above gives below: [exec] executing 'cmd.exe' arguments: [exec] '/c' [exec] '

datetime - python count down to event (in days and hours) -

please can advise on this, i've tried various methods don't seem able work. i need countdown from datetime.now() to datetime(2011,05,05) in days hours you can use delta = datetime.datetime(2011, 05, 05) - datetime.datetime.now() to datetime.timedelta object describing remaining time. number of remaining days delta.days , remaining hours delta.seconds/3600. or delta.seconds//3600 .

caching - Embedded C - How to create a cache for expensive external reads? -

i working microcontroller has external eeprom containing tables of information. there large amount of information, there chance request same information cycle cycle if 'stable' - i.e. if @ constant temperature example. reads eeprom take around 1ms, , around 30 per cycle. our cycle 100ms there significant savings had. i therefore looking @ implementing ram cache. hit should faster 1ms since microcontroller core running @ 8mhz. the lookup involves 16-bit address returning 16-bit data. microcontroller 32-bit. any input on caching appreciated, if totally missing mark , should using else, linked list, or pre-existing library. here think trying achieve: -a cache made of array of structs. struct contain address, data , sort of counter indicating how piece of data has been accessed (readcount). -the array sorted address normally. have efficient lookup() function lookup address , data (suggestions?) -if got cache miss, sort array readcount determine least used cach

Sharepoint 2010 - Document Upload via Web Service (Exception) -

i using "copy" web service attempt upload document sp2010 website. however, when execute "copyintoitems" method, receive webexception (details below). i'm following general approach suggested in post: simplest way upload document sharepoint using web services . any suggestions? system.net.webexception unhandled message="the request failed error message:\r\n--\r\n<html><head><title>object moved</title></head><body>\r\n<h2>object moved <a href=\"%2f_login%2fdefault.aspx%3freturnurl%3d%252fsites%252fnn%252f_vti_bin%252fcopy.asmx\">here</a>.</h2>\r\n</body></html>\r\n\r\n--." source="system.web.services" stacktrace: @ system.web.services.protocols.soaphttpclientprotocol.readresponse(soapclientmessage message, webresponse response, stream responsestream, boolean asynccall) @ system.web.services.protocols.soaphttpclientprotocol.invoke(s

algorithm - How can i diff two trees to determine parental changes? -

i've got tree structure need rearrange (drag , drop) , submit changes. what's going best way capture changes? see there 2 ways, store every change command, submit list of changes execute each one serialize tree , diff new tree old tree work out whats changed, execute changes 1 seems easiest implement, although wasteful if many repetitive actions have occurred (i.e. dragging nodes around many times, putting them started) 2 avoids above problem, how can "diff" trees work out parental change commands execute? presumably there algorithms this? edit clarify, every node has "id" , "parentid". need allow users rearrange tree (thereby changing parentid of nodes). for option 2, should straightforward enough serialize changed tree, work out differences iterate on the original tree in preorder, find same node in new tree , record change if parents different? robust approach wont stuck in cycle? edit no, wont work. need iterate on new tr

java - How to reference a file in Eclipse that is not in src -

i'm trying resource mybatis. tutorial states need following in connection factory: string resource = "org/mybatis/example/configuration.xml"; reader reader = resources.getresourceasreader(resource); sqlmapper = new sqlsessionfactorybuilder().build(reader); my directory structure is: src/ com/ utils/ mybatisconnectionfactory.java config/ configuration.xml i having troubles referencing configuration file. tried "config/configuration.xml", "configuration.xml" , "/config/configuration.xml". anyone have idea do? you can add config directory source-folder (right-click > build path > use source folder). thus configuration files go on root of classpath , accessible via getclass().getresourceasstream("/configuration.xml")

Ruby. Mocking in RSpec -

i have problem mocking. have class distancematrix , indicate method form_matrix called in if/else statement. need use mocha , rspec. ideas? class distancematrix def initialize(*args) if args[0].class == string form_matrix(get_data_from_yaml(args[0], args[1])) elsif args[0].class == array || args[0] == nil form_matrix(get_data_from_db(args[0])) end end def form_matrix(...) ... end end it tried: describe distancematrix, "when mocking ..." "should call form_matrix" distancematrix.any_instance.expects(:form_matrix).with([1]).once distancematrix.any_instance.expects(:get_data_from_yaml).with("file_name.yml").once.returns([1]) distancematrix.new("file_name.yml") end end but got error: failures: 1) distancematrix when mocking ... should call form_matrix failure/error: distancematrix.new("file_name.yml") unexpected invocation: #<anyinstance:distancematrix>.get_data

c# - Streamreader does not work when I close HttpWebResponse early -

uri targeturi = new uri(targeturl); httpwebrequest request = (httpwebrequest)httpwebrequest.create(targeturi); httpwebresponse response = (httpwebresponse)request.getresponse(); streamreader reader = new streamreader(response.getresponsestream()); string data = reader.readtoend(); response.close(); why above code work fine following not? notice close response in following code. uri targeturi = new uri(targeturl); httpwebrequest request = (httpwebrequest)httpwebrequest.create(targeturi); httpwebresponse response = (httpwebresponse)request.getresponse(); streamreader reader = new streamreader(response.getresponsestream()); response.close(); string data = reader.readtoend(); closing response closes response stream well... streamreader no longer has read from. from documentation webresponse.close : the close method cleans resources used webresponse , closes underlying stream calling stream.close method.

mySQL: Querying one-to-many -table? -

what appropriate way query products specific property in following database design one-to-many approach? i guess should doing following: select (*) productproperties property = 'weight' , value = '10' but if need products has both weight = 10 & color = blue in same query? example of database design: table: products ------------------------ id | name | price ------------------------ 0 | myname | 100 1 | myname2 | 200 table: productproperties ------------------------------------------------ product | property | value ------------------------------------------------ 0 | weight | 10 1 | weight | 20 1 | color | blue what if need products has both weight = 10 & color = blue in same query? one option: select product, name products inner join productproperties on (products.id = productproperties.product) (property = 'weight' , value = '10'

Best way for a beginner to learn screen scraping by Python -

this might 1 of questions difficult answer, here goes: i don't consider self programmer - :-) i've learned r, because sick , tired of spss, , because friend introduced me language - not complete stranger programming logic. now learn python - screen scraping , text analysis, writing webapps pylons or django. so: how should go learning screen scrape python? started going through scrappy docs feel "magic" going on - after - trying learn, not do. on other hand: there no reason reinvent wheel, , if scrapy screen scraping django webpages, might after worth jumping straight scrapy. think? oh - btw: kind of screen scraping: want scrape newspaper sites (i.e. complex , big) mentions of politicians etc. - means need scrape daily, incrementally , recursively - , need log results database of sorts - lead me bonus question: talking nonsql db. should learn use e.g. mongodb right away (i don't think need strong consistency), or foolish want do? thank thoughts - ,

asp.net - Building an import process that checks for duplicates -

using asp.net, i'm building admin tool requires function import list of email addresses. upon uploading file, want check existing records of email addresses supplied. non-existing email addresses, create them using dao. basically want to: receive list of emails retrieve data existing emails create data new emails in db return full data emails in list. since want know of emails exist front, first thought query table records where email in ('email001fromfile', 'email002fromfile', 'etc...') list potentially contain thousands of email addresses, , i'm not supplying many email addresses in operator idea. i thought looping through list , checking record each email, potentially generate far many queries. my next thought generate temp table hold list , modify in clause use temp table, rather explicit list of items, require execute sql or stored procedure directly, i'm not inclined since i'm using nhibernate access db. though using a

Android: Set Ringtone for existing record in Mediastore.Audio.Media -

i able set ringtone perfectly, when insert row in mediastore.audio.media newuri = this.getcontentresolver().insert(mediastore.audio.media.getcontenturiforpath(k.getabsolutepath()), values); but existing record i.e when trying insert row again, logcat shows me database constraint error 19. how work around this? need set .ogg file sound board app ringtone, existing in mediastore database... appreciated.. i figured out. delete existing record in database before inserting. uri uri = mediastore.audio.media.getcontenturiforpath(file.getabsolutepath()); getcontentresolver().delete(uri, mediastore.mediacolumns.data + "=\"" + file.getabsolutepath() + "\"", null); hope helps too.