Posts

Showing posts from August, 2010

How to use C# code in C++ project -

i have code in c# want use in other project (coded in c++). researched, need create .lib msvs creates .dll (i think..). think possible use .dll using loadlibrary() on c++ seems not friendly. 1 - can create .lib in msvs? if not, how can create it. 2 - best way integrate code? .lib or using .dll + loadlibrary()? the easiest option, honestly, use c++/cli. lets use both object systems (.net, , traditional c++ standard template library).

ruby on rails - How-to conform to a max/min width/height -

i using carrierwave (https://github.com/jnicklas/carrierwave). need make sure images conform maximum/minimum height , width? otherwise error should display. should handled in uploader class or in model (possibly through custom validation method)? you can validate image width/height on client side, not guarantee anything, because it's easy manipulate/circumvent. for user friendliness: check on client side , give warning before uploading. data integrity, check on server side after upload.

JQuery: I have a unique id for my form. How do I use that to select the element ids within it? -

i have form , generate unique id it. idea if more 1 form generated, duplicate ids on each form not interfere each other because can reference unique form id first. want know syntax doing this. on following view, have jquery script reference date field , couple of checkboxes. written, create more 1 form, id nullableotherleavedate, morningonlyflag, afternoononlyflag duplicated. need prefix them unique formid. <%@ control language="c#" inherits="system.web.mvc.viewusercontrol<shp.models.employeeotherleaf>" %> <% var unique = datetime.now.ticks.tostring(); %> <script language="javascript" type="text/javascript"> $(document).ready(function () { $('#nullableotherleavedate').datepicker({ dateformat: 'dd-mm-yy' }); $('#morningonlyflag').click(function () { $('#afternoononlyflag').attr('checked', false); }) $('#afternoononlyflag')

visual studio - How to switch between header and implementation in VS2010? -

is keyboard shortcut or free addon in visual studio 2010 allows switch between header (c/c++ .h file) , implementation (c/c++ .cpp file)? visual studio not have built-in keyboard shortcut switch , forth. macro far best bet if want automate single keyboard shortcut. list of suggested options, see answers previous question . the add-in visual assist x provides feature shortcut alt + o (however, add-ins not supported express editions of visual studio). if you're trying avoid using macro, there alternative way achieve similar result, although two-click process: to switch header implementation: right-click a.cpp file , choose "go header file" context menu. to switch implementation header: right-click identifier declared in header , choose "go definition" context menu.

Google Maps: adding notes to place/questions -

i'm using google maps (on browser + smartphone) , wondering: is possible add own notes places? need find new customers , woud adding notes is there way create place-categories differenct colors (eg. shops = yellow, doctors=red, restaurants=green)? thanks as schoolbus driver, love leave notes on pins of bus route make google map. helpful me , other bus drivers replace me when absent. leaving notes on google pin helpful. james

android - Nested Parcelling : RuntimeException - Unmarshalling unknown type code 3211319 at offset 440 -

i need send data activity , may running in different context. created class a, has arraylist of datatype b 1 of instance member . declared class b class a's inner class. send class a's instance through intent , made class , b both parcelable . class structure (this not include complete code e.g. code written make classes parcelable ): public class implements parcelable{ public class b implements parcelable{ public arraylist<string> value; .... .... public void writetoparcel(parcel dest, int flags) { dest.writelist(value); } .... .... } public list<b> group; public string name; .... .... public void writetoparcel(parcel dest, int flags) { dest.writelist(group); dest.writestring(name); } .... .... } i used putextra (string name, parcelable value) function put data. but on receiving side, got following exception: uncaught

java - Spring MVC Web Services Dispatcher -

i'm trying build web service integrated in dispatcherservlet insted of messagedispatcherservlet, according spring ws it's possible. i'm tying follow tutorials , implement code according tutorials. tomcat starts normally. however, have page 404 when i'm trying access web service using http://[host]/[project]/holidayservice/ i"m doing wrong? here implementation: <servlet> <servlet-name>doolloop</servlet-name> <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>doolloop</servlet-name> <url-pattern>*.dlp</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>doolloop</servlet-name> <url-pattern>/index.dlp</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>

.net - Unicode-to-string conversion in C# -

how can convert unicode value equivalent string? for example, have "à°°à°®ెà°¶్", , need function accepts unicode value , returns string. i looking @ system.text.encoding.convert() function, not take in unicode value; takes 2 encodings , byte array. i bascially have byte array need save in string field , come later , convert string first byte array. so use byteconverter.getstring(bytearray) save byte array string, can't byte array. try following: byte[] bytes = ...; string convertedutf8 = encoding.utf8.getstring(bytes); string convertedutf16 = encoding.unicode.getstring(bytes); // utf-16 the other way around using `getbytes(): byte[] bytesutf8 = encoding.utf8.getbytes(convertedutf8); byte[] bytesutf16 = encoding.unicode.getbytes(convertedutf16); in encoding class, there more variants if need them.

Blackberry - How to render PDF document? -

how can read .pdf file in blackberry through own application? there no api, nor lib such thing in blackberry. however can try integrate google docs or www.docspal.com or other server side rendering service.

c# - Unable to Copy datacolumn from one data table to another -

how can copy 1 data column 1 data table new datatable. when try it, error column 'xxx' belongs datatable.? datacolumn = datatable1.columns[1]; datatable2 = new datatable(); datatable2.columns.add(datacolumn); thanks in advance you cannot copy datacolumns. you'll need create new datacolumn in new datatable same data type in old datatable's column, , need run loop bring in data old datatable new datatable. see following code. assumes datatables have same number of rows. datatable dt1 = new datatable(); datatable dt2 = new datatable(); dt2.columns.add("columna", dt1.columns["columna"].datatype); (int = 0; < dt1.rows.count; i++) { dt2.rows[i]["columna"] = dt1.rows[i]["columna"]; } also, if data copying reference types , not value types might want see if .clone() method available type, or make 1 yourself. doing 'this = that' in loop not work on reference types.

Facebook C# SDK cannot resolve FB Login -

i'm developing mvc-2 application facebook c# sdk , facebook stopped respond login requests. after research, i've managed working putting 'localhost' in 'site domain' field in facebook application settings. now, login through facebook javascript sdk seems working alright, facebook c# sdk returns facebookapp.session value null. sure issue not because of configuration or development mistakes, i've tried sample application facebook c# sdk website, no luck. any suggestions on issue? thanks. did start sample application? if start should work out of box. guessing have cookie support set false in web.config setting. http://facebooksdk.codeplex.com/releases/view/54371#downloadid=160969 web.config file should this: <configsections> <section name="facebooksettings" type="facebook.facebookconfigurationsection"/> </configsections> <facebooksettings apikey="your_api_key"

java - mediaplayer not working -

i create media player. display songs in listview when click song. log cat show error: mp.reset(); mp.setdatasource(songpath); mp.prepare(); mp.start(); logcat error: 11-15 19:12:32.250: info/stagefrightplayer(34): setdatasource('/sdcardparatha.mp3') 11-15 19:12:32.289: error/mediaplayer(2515): error (1, -2147483648) 11-15 19:12:32.289: verbose/song(2515): prepare failed.: status=0x1 of course thats not going work since set resource /sdcardparatha.mp3 whereas meant /sdcard/paratha.mp3 .

java - How do I display the header row in a JTable that uses AutoBinding against model -

for reason header row not visible. using swingbindings.createjtablebinding bind pojo table. table showing rows header row not visible. if inspect jtableheader in table there , columns have names expected. jtable header properties: isenabled , isvisible set true. is there missing? i don't know swingbindings.createjtablebinding is, when use swing add table jscrollpane. table header used column header view of scrollpane. if not using jscrollpane, need create jpanel using borderlayout. table added center , table header added north.

.net - recursive assert on collection -

i test one: [test] public void testcollectionassert () { var a1 = new [] { new [] { "a" } }; var a2 = new [] { new [] { "a" } }; assert.arenotequal (a1, a2); //collectionassert.areequal (a1, a2); collectionassert.areequivalent (a1, a2); } to pass. real case more complicated, solving 1 in generic way do. ideas? there's useful linq operator called sequenceequal() compares 2 sequences equality. sequenceequal() walks through 2 ienumerable<> sequences , verifies have same number of elements , elements @ same index equal (using default equality comparer). however, since have nested collections, need extend concept of equality apply them well. fortunately, there's overload allows supply own iequalitycomparer<> object. since it's awkward have define class provide equality semantics, i've written generic extension allows use delegate instead. let's @ code: public st

apache - Redirect Links 301 -

i have question 301 redirect please: example: http://stackapp.com/post/35642 to: http://google.com/posts/index.php?q=http://stackapp.com/post/35642 note: want redirect posts.(not id = 35642 post) redirectmatch 301 (post/.*) http://google.com/posts/index.php?q=http://stackapp.com/$1

xquery - expected return found let -

i error saxon, engine name: saxon-pe xquery 9.2.1.2 severity: fatal description: xquery syntax error in #... (:return :) let $#: expected "return", found "let" start location: 776:0 on function declare function local:set-internet-type($req1 element(ns0:req), $cate element()) xs:string { if(count( $itm in $req/*:cust/*:inter/*:itm $789/*:product/*:030/*:specs/*:name/text()= data($11/internet) , $22/*:action/text()="change" return $33)>0) ( $44 in $55 $tt/*:name/text()= data($t/internet) , $u/*:action/text()="change" (:return <fake/>:) let $z:= $a/*:product/*:c/*:e[1] return concat($x,'>',$y) ) else ("") }; i new xquery , spent lot on error without getting solution. vars masked intentionally error message seems related function flow. any appreciated. thanks in advance alessandro saxon declares have "partial support of xquery 1.1&quo

bytearray - Convert object to byte array in c# -

i want convert object value byte array in c#. ex: step 1. input : 2200 step 2. after converting byte : 0898 step 3. take first byte(08) output: 08 thanks you may take @ getbytes method: int = 2200; byte[] bytes = bitconverter.getbytes(i); console.writeline(bytes[0].tostring("x")); console.writeline(bytes[1].tostring("x")); also make sure have taken endianness consideration in definition of first byte .

iphone - uitableview section headings going under nav bar when translucent on iOS3 only -

i have pretty same issue uitableview scrolling under navigation bar posting new question have more specifics. i have full screen table (with sections) on page black translucent navigation bar. within uiviewcontroller have views overlaid on top table created programatically thus; - (void)viewdidload { [super viewdidload]; self.navigationcontroller.navigationbar.barstyle = uibarstyleblack; self.navigationcontroller.navigationbar.tintcolor = nil; self.navigationcontroller.navigationbar.translucent = yes; tableview = [[uitableview alloc] initwithframe:[[uiscreen mainscreen] bounds] style:uitableviewstyleplain]; tableview.delegate = self; tableview.datasource = self; [tableview setcontentinset:uiedgeinsetsmake(44,0,0,0)]; [self.view addsubview:tableview]; [tableview release]; } my problem although works on ios4 - in section headings butt bottom of translucent tableview scroll, on ios3 headings butt bottom of status bar instead :( if set transluc

telerik - javascript closure, not working? -

i have function call retrieve sliding pane (telerik splitter control) thought use function function getzone() { var slidingzone = $find("<%= slidingzone.clientid %>"); return function () { return slidingzone; }; } so didn't have "find" sliding zone every time. doesn't work. this does... function getzone() { var slidingzone = $find("<%= slidingzone.clientid %>"); return slidingzone; } can tell me why first 1 isn't working? btw, i'm using this.... function hidetreepane() { var paneid = "<%= slidingpane.clientid %>"; getzone().undockpane(paneid); return true; } well, first function, returns function, , want inner function executed. if invoke result of see work, e.g.: getzone()(); i think want following, use executed anonymous function, call $find method once, storing result: var getzone = (function() { var slid

Serving images for a cakePHP site from a different sub-domain -

what best practice serving images different sub-domain(like media.host.com) in cakephp? should put images in img folder provided cakephp , make folder document root of sub-domain, or there better way of doing this? roland. i don't think matters long images in same place. in case can't use $html->image() is, or can it's wiser modify or roll own helper don't have give full path. while you're doing can make use whatever url root want.

Resizing Iframes in Facebook Applications -

so looks facebook has removed page referencing how resize iframe apps except this one includes 404'ed js file. all of examples finding online either reference aforementioned missing javascript file or not work. any guidance appreciated. thanks! found it.. here . edit: lovely, doesn't seem work.

javascript - Show just particular parts of website - select via CSS? -

what easiest method display specific elements on website? example, on news site headlines , nothing else. i'd select elements via css should displayed. tried use :not pseudoclass: :not(.myclass) { display: none; } but obviously, parents of .myclass -elements aren't displayed , aren't them. know possibility achieve this? doesn't have css-only, javascript possible too. web-app great. i'd able filter sites visit, apply user-stylesheet. you can load page jquery , select elements want... $("body").load("path/to/page.html div.headline"); the above load <div class="headline"> elements body of document. note: of course have keep same origin policy in mind.

python - from CSV to ndarray, and rpy2, -

i can make numpy ndarrays rec2csv, data = recfromcsv(dataset1, names=true) xvars = ['exp','exp_sqr','wks','occ','ind','south','smsa','ms','union','ed','fem','blk'] y = data['lwage'] x = data[xvars] c = ones_like(data['lwage']) x = add_field(x, 'constant', c) but, have no idea how take r data frame usable rpy2, p = roptim(theta,robjects.r['ols'],method="bfgs",hessian=true ,y= robjects.floatvector(y),x = base.matrix(x)) valueerror: nothing can done type <class 'numpy.core.records.recarray'> @ moment. p = roptim(theta,robjects.r['ols'],method="bfgs",hessian=true ,y= robjects.floatvector(y),x = base.matrix(array(x))) valueerror: nothing can done type <type 'numpy.ndarray'> @ moment. i'm not 100% sure understand issue, couple things: 1) if it's ok, can read csv r directly, is:

javascript - jQuery submit form IF -

hey guys, have great scripts on stack overflow helped me out with, except 1 major function need missing. this game user picks number (by entering number in text field) hits play button. after hit play button series of numbers appear, have click on number matches number. the query script i'm using counts how many times hit number , how many times missed number. take @ script in action here. link text now need do, send score (hits , misses ) database after 3 misses, can keep high score. ideas? here's script. var hitcount = 0, misscount = 0; function isnumeric(n) { return !isnan(n); } $("#getit").click(function() { var li = [], intervals = 0, n = parseint($('#mynumber').val()); if (isnumeric(n)) { setinterval(function() { li[intervals++ % li.length].text(math.random() > .1 ? math.floor(math.random() * (10 + n) + (n / 2)) : n).attr('class', ''); }, <?php echo $time ?>); } $('#randomnumber&

css - Floats working, but are now stepping. -

this page: the boxes floating fine , showing 4 products across middle. after coleague copied , pasted exact same code notepad, other url change, floating issue has occurred. have looked through , can't see culprit. any appreciated. looks you're missing closing div tags: ... <div class=xmashp-bottom-box-price>from £9.99</div><!--<div style="float: left; width: 35px;"> </div>--> <div class=hp-bottom-box1> ... so hp-bottom-box* boxes nested inside each other. add closing </div> tag before open next hp-bottom-box* tag , should good.

SQL First Match or just First -

because part of larger sql select statement, want wholly sql query selects first item matching criteria or, if no items match criteria, first item. i.e. using linq want: dim t1 = t in tt dim t2 = t in t1 criteria(t) dim firstifany = t in if(t2.any, t2, t1) take 1 select t because if not part of linq, linqpad doesn't show single sql statement, two, second depending upon whether criteria matches of tt values. i know select top 1 etc. , can add order by clauses specific first 1 want, i'm having trouble thinking of straightforward way first of 2 criteria. (it @ point when able solve myself.) seeing don't see existing question this, let stand. i'm sure else see answer quickly. select top 1 * ( select top 1 *, 1 rank mytable somecolumn = mycriteria union select top 1 *, 2 rank mytable order myordercolumn ) order rank

How to pass value from one Silverlight page to another? -

i have 2 .xaml pages loginpage , child page - workloads_new . need pass loginid loginpage workloads_new. in workloads_new keep getting loginid value 0. here code in loginpage: void webservice_getuseridcompleted(object sender, getuseridcompletedeventargs e) { int id = e.result; //for example id=2 if (id > 0) { this.content = new mainpage(); workloads_new child = new workloads_new(); child.loginid = id; //in debug mode see id=2 , loginid=2 } } and in workloads_new have: public int loginid { get; set; } private void childwindow_loaded(object sender, routedeventargs e) { //to test want see id in textblock keep getting loginid=0 why? this.errorblock.text = this.loginid.tostring(); } the urimapper object supports uris take query-string arguments. example, consider following mapping: in xaml : <navigation:urimapping uri="products/{id}" mappeduri="/views/productpage.xaml?id={id}"></navigation:urimappi

python - Django queryset update fields with the lowercase equivalent - Django -

i update various models in go. i need update varchar field lowercase equivalent. any idea if can done single queryset? since one-off easier run ./manage.py dbshell , run update queries directly. update sometable set somefield=lower(somefield);

c++ - stack depth for quicksort -

i using tail recursive version of quicksort here code #include <iostream> using namespace std; int partition(int a[],int l,int r){ int pivot=a[l]; std::swap(a[pivot],a[r]); int store=l; (int i=l;i<r;i++){ if (a[i]<=pivot){ std::swap(a[i],a[store]); store=store+1; std::swap(a[store],a[r]); } } return store; } void tail_quick(int a[],int p,int r){ while(p<r){ int q=partition(a,p,r); tail_quick(a,p,q-1); p=q+1; } } int main(){ int a[]={21,10,13,8,56,9,34,11,22,44}; int n=sizeof(a)/sizeof(int); tail_quick(a,0,n-1); (int i=0;i<n;i++) cout<<a[i]<<" "; return 0; } but output not correct not sorted , randome numbers in output please help you using uninitialized variable in call partition below. sure shouldn't else? void tail_quick(int a[],int p,int r){ while(p&l

python - accessing variables in the debugging session with ipython and %pdb on -

i'm new ipython , trying use ipython debug code. did: [1]: %pdb automatic pdb calling has been turned on and then in [2]: %run mycode.py and in code, have 1/0 raises exception , automatically goes debug session. zerodivisionerror: float division ipdb> variable array([ 0.00704313, -1.34700666, -2.81474391]) so can access variables. when following: ipdb> b = variable *** specified object '= variable' not function or not found along sys.path. but works: ipdb> b = self.x b used set break points. whatever follows b expected function or line number. if type ipdb> help see full list of commands (reserved words). you use, say, x or y variable: ipdb> y = variable or ipdb> exec 'b = variable'

Python+ubuntu error -

am trying run following python program import re regex=re.compile("http...imgs.xkcd.com.comics.[\\s]*.[jpg|png]") f=open('out.txt') in f: print regex.findall(a) print '\n' when type code interpreter manually, works expected when save file , try run , gives errors. command used run is chmod +x sudo ./pymod.py error: ./pymod.py: 2: syntax error: "(" unexpected if dont use sudo, error is ./pymod.py: line 2: syntax error near unexpected token `(' ./pymod.py: line 2: `regex=re.compile("http...imgs.xkcd.com.comics.[\\s]*.[jpg|png]")' am using ubuntu 10.04 on default it takes 10-15 seconds error appear when set executable, have specify want run with, or linux consider bash script. add first line of file: #!/usr/bin/python or run like: python pymod.py cheers!

ios - Texture lookup in vertex shader behaves differently on iPad device vs iPad simulator - OpenGL ES 2.0 -

i have vertex shader in texture lookup determine gl_position. using part of gpu particle simulation system, particle positions stored in texture. it seems that: vec4 texturevalue = texture2d(datatexture, vec2(1.0, 1.0)); behaves differently on simulator ipad device. on simulator, texture lookup succeeds (the value @ location 0.5, 0.5) , particle appears there. however, on ipad texture lookup returning 0.0, 0.0. i have tried both textures of format gl_float , gl_unsigned_byte. has else experienced this? glsl es spec says texture lookups can done in both vertex , fragment shaders, don't see problem is. i using latest gm beta of ios sdk 4.2 i tested well. using ios 4.3, can texture lookup on vertex shader on both device , simulator. there bit of strangeness though (which maybe why it's not "official" szu mentioned). on actual device (i tested on ipad 2) have lookup on fragment shader on vertex shader. is, if not using on fragment shader, you'll

asp.net - Preserve Session Variables in Web Application After Build -

every time build web application, session variables lost before build. there anyway preserve session variables during build? session variables default held in memory web server. when build, resetting application, , hence losing session (and static, cache, etc) values. if wish, can configure asp.net use different session state provider changing session state mode . note "inproc" default, holds them in memory. can use stateserver runs in different process , can on different machine, or sqlserver - or write own.

visual studio - Web Deploy returns 401 unauthorized when publishing via [proj].deploy.cmd -

i'm having bit of problem web deploy can't seem iron out. every time try , publish wmsvc via [proj].deploy.cmd command in package i'm getting "the remote server returned error: (401) unauthorized". command looks (project called "web", server named "autodeploy"): web.deploy.cmd /y /m:https://autodeploy:8172/msdeploy.axd -allowuntrusted i can publish fine https://autodeploy:8172/msdeploy.axd via visual studio service running , can authenticate administrator. running locally on machine against package while logged on administrator (it's little local win 2k8 vpc) isn't working , adding /u , /p parameters administrator account nothing. i've enabled failed request tracing , getting this output @ least there's refer unfortunately can't determine root cause is. i'm trying connect same service same credentials in visual studio different. just out of interest, can publish fine web deployment agent service (msdepsvc)

Good precautions (practices) to start C++ programming -

i'm starting c++ programming in first job. i'm cs student , have learn programming in java. advice tell me watch out don't cause trouble in new job? have advice or references appreciated. (example: know c++ more have memory problem java) thank much! maybe know this, 1 common mistake folks used java , learning c++: don't use new unless have (and don't really have to). in cases want create object, should create "on stack", classtype obj; .

Is it possible to post to pages that you are an admin for using the Facebook Javascript SDK? -

i able write on own wall not on wall of pages admin for. using code below (javascript sdk): fb.ui( { method: 'stream.publish', message: 'getting educated facebook connect', attachment: { name: 'connect', caption: 'the facebook connect javascript sdk', description: ( 'a small javascript library allows harness ' + 'the power of facebook, bringing user\'s identity, ' + 'social graph , distribution power site.' ), href: 'http://github.com/facebook/connect-js' }, action_links: [ { text: 'code', href: 'http://github.com/facebook/connect-js' } ], user_message_prompt: 'share thoughts connect', target_id: '170500829645508',

iphone - iOS 4.0 contentScaleFactor and scale - how to handle in 3.1.3? -

i tasked making app works in ios 4.0 work in 3.1.3 , 3.2 again. straightforward handling of new api scale , other situations values must passed/returned hard. respondstoselector/performselector takes care of else. here's simplified version of going on: -(float)getimagescalefactor { if([[uiscreen mainscreen] scale == 2.0) return kscalefactorforretinadisplay; else return kscalefactorforolderdisplay; } scale isn't in ios prior 4.0. can show code sample work in versions of ios? i use similar code, you're missing 1 important part: respondstoselector: if([[uiscreen mainscreen] respondstoselector:@selector(scale)] && [uiscreen mainscreen].scale == 2.0f) return kscalefactorforretinadisplay; else return kscalefactorforolderdisplay;

jQuery hide div on focus out unless certain div is clicked -

i have div popped list of items type text box. on blur of textbox hide list of items. however, have click events on items no longer trigger because focusout event fires first. what want hide list on blur unless item in list has been clicked. does know of way? it should work same tags section of site when asking question. with jquery 1.6 or higher can use :focus selector see if div has children have focus before hiding div. $("#textboxid").blur(function () { if ($("#divid").has(":focus").length == 0) { //if click on other results $("#divid").hide(); //hide results } }); update: turns out worked in ie. here better solution, though little complex task. http://jsfiddle.net/cb2cn/ var resultsselected = false; $("#resultsdiv").hover( function () { resultsselected = true; }, function () { resultsselected = false; } ); $("#textbox").blur(function () { if (!resultsselected)

sql server - Conn.Open() still work after SQL Service is stopped -

i have met issue sql server 2005 sp2, have created windows form , button on it, , following steps: make sure sql service running, click button, ok stop sql service, , click button again, on machine, there not exception @ code of line 1 , exception occurred @ line 2 , , exception info: message: transport-level error has occurred when sending request server. (provider: shared memory provider, error: 0 - no process on other end of pipe.) using system; using system.collections.generic; using system.componentmodel; using system.data; using system.drawing; using system.text; using system.windows.forms; using system.data.sqlclient; namespace reconnectsql { public partial class form1 : form { private string m_connectionstring = @"server=(local); database=testdb; user id=sa; password=admins; connection timeout=15"; public form1() { initializecomponent(); } /// <summary> /// /// </sum

c# - Help with LINQ-SQL GroupBy -

i'm trying convert t-sql linq-sql query: -- top 3 pros city select top 3 description, ispro, count(*) numberofvotes tblprocon idprimarycity = @idprimarycity , ispro = 1 group idprimarycity, ispro, description union -- top 3 cons city select top 3 description, ispro, count(*) numberofvotes tblprocon idprimarycity = @idprimarycity , ispro = 0 group idprimarycity, ispro, description order ispro, numberofvotes desc here's have far: // construct base query var query = (from p in db.tblprocons p.idprimarycity == idprimarycity group p new { p.idprimarycity, p.ispro, p.description } g select new { description = g.key, ispro = g.any(x => x.ispro), numberofagrees = g.count() }); // split queries based on pro/con, , apply top(3) var pros = query.where(x => x.ispro).take(3); var cons = query.where(x => !x.ispro).take(3); result = pros .union(cons) // union pro/cons .orderbydescending(x => x.ispro) // order #1 - pro/c

cookies - php curl strange question -

when create 1 curl object $ch = curl_init(); , go on many site pages, it's ok (if pass cookie), if create each request new curl object, if set cookie, site anyway redirect me login page. object curl contains else allow site recognize curl client? must set except cookie? the remote server might checking user agent. try setting it: $ua = 'mozilla/5.0 (x11; u; linux x86_64; en-us; rv:1.9.2.12) '. 'gecko/20101027 ubuntu/9.10 (karmic) firefox/3.6.12'; curl_setopt($ch, curlopt_useragent, $ua);

delphi - Implementation of FNV -

i trying implement fnv hash http://isthe.com/chongo/tech/comp/fnv/ i converted powerbasic's inline asm on page delphi. function readfiletomem(spath:string):pointer; var hfile: thandle; pbuffer: pointer; dsize: dword; dread: dword; begin hfile := createfile(pchar(spath), generic_read, file_share_read, nil, open_existing, 0, 0); if hfile <> 0 dsize := getfilesize(hfile, nil); if dsize <> 0 begin setfilepointer(hfile, 0, nil, file_begin); getmem(result, dsize); readfile(hfile, result^, dsize, dread, nil); if dread = 0 messagebox(0, pchar('error reading file.'), pchar('read error'), mb_iconexclamation) end; closehandle(hfile); end; function getpointersize(lpbuffer: pointer): cardinal; // function erazerz begin if lpbuffer = nil result := cardinal(-1) else result := cardinal

c# - String or string -

possible duplicate: in c# difference between string , string what's difference between string , string. in c#, preferred? actually string alias system.string erash right... here list of other alias' shamelessly lifted jon skeet in this post : * object: system.object * string: system.string * bool: system.boolean * byte: system.byte * sbyte: system.sbyte * short: system.int16 * ushort: system.uint16 * int: system.int32 * uint: system.uint32 * long: system.int64 * ulong: system.uint64 * float: system.single * double: system.double * decimal: system.decimal * char: system.char

windows phone 7 - Programmatically close ListPicker from WP7 Silverlight Toolkit -

my app being rejected marketplace because of requirement 5.2.4.c (back button must close menu or dialog , cancel navigation). i'm using listpicker silverlight toolkit , that's what's causing failure: pressing button when listpicker open goes instead of closing listpicker , cancelling navigation. this seems simple enough fix: if user presses button , listpicker open, close , cancel navigation. however, haven't seen way of programatically either detecting whether listpicker open, or closing listpicker. am missing something? how fix bug? one again, have asked question soon. answer here: http://silverlight.codeplex.com/workitem/7643

Javascript - innerHTML function in IE -

i have html file content <html> <body> <script language="javascript"> function fun1() { alert(document.getelementbyid('id1').innerhtml); } </script> <div id="id1"> <ul> <li>here111</li> <li>here222</li> <li>here333</li> </ul> </div> <a href="javascript:void(0)" onclick="fun1()">click</a> </body> </html> in innerhtml function iam getting only <ul> <li>here111 <li>here222 <li>here333</li> </ul> the </li> tag missing how can entire content? you have set id of div "test" getting "test1" alert(document.getelementbyid('test1').innerhtml); it should alert(document.getelementbyid("test").innerhtml);

Regular Expression for valid css and/or jQuery selector -

i need : regex validselector = new regex("^[.#a-za-z0-9_:[] ]+[,><a-za-z0-9_~=\"\":[] ]*$"); has written regular expression validating jquery or css selectors? (css3/jquery1.4) or, know can find regex or regex generator validate jquery selector?(or atleast css selectors?) i've tried going through code of sizzle.js bu john resig , w3c docs css (http://www.w3.org/style/css/) ended havin headache :( thought i'd rather ask if of has written or used snippet this. thanks!! the specification of css 3 selectors has section grammar of selectors can use build regular expression. start selector , replace each variable production until there no variables left.

Word count query in Django -

given model both boolean , textfield fields, want query finds records match criteria , have more "n" words in textfield. possible? e..g.: class item(models.model): ... notes = models.textfield(blank=true,) has_media = models.booleanfield(default=false) completed = models.booleanfield(default=false) ... this easy: items = item.objects.filter(completed=true,has_media=true) but how can filter subset of records "notes" field has more than, say, 25 words? try this: item.objects.extra(where=["length(notes) - length(replace(notes, ' ', ''))+1 > %s"], params=[25]) this code uses django's extra queryset method add custom where clause. calculation in where clause counts occurances of "space" character, assuming words prefixed 1 space character. adding 1 result accounts first word. of course, calculation approximation real word count, if has precise, i'd word count in python.

php - How can I translate "select from this variable to this variable only" into a code? -

i have 3 variables here. $first= 'start'; $second = 'end'; $testvar = 'start here , here until end more more more strings here'; how can search $testvar if contains start , end strings, , want post start end string only. another way using substr() , strops() substr($testvar,strpos($testvar,$first),strpos($testvar,$second)+3)

asp.net - Using an actual tilde in a URL Route -

i need set routing in global.asax going page actual tilde in url (due bug tilde ended in shared link) redirected proper place using routing. how can set route url actual tilde ("~") in it, e.g. www.example.com/~/something/somethingelse go same place www.example.com/something/somethingelse - never seems work! in addition gerrie schenck: you should never ever use unsafe characters in url's. it's bad practice , can not sure browsers recognize character. webdevelopment creating websites/webapplications function under browsers(theoretically ofcourse, practically resolves limited few used based on goal serves: p ) the encoding should work, if not, proves gerrie , point why should not use unsafe characters. list of unsafe characters , encoding used: http://www.blooberry.com/indexdot/html/topics/urlencoding.htm

visual c++ - WOW6432Node registry problem -

i made application install setup install shield 5.0 on 32bit machine before migrated application 64bit. after installed application on 64bit machine, application registry values gone under wow6432 node hklm\software\wow6432node(myapplication) application trying read values hklm\software(myapplication). please wrong. shall case. thanks, kam your install 32-bit , automatically writes wow6432node on 64-bit system. need disable registry reflection or directly write 64-bit registry key (i don't know how on install shield, should find in manual, search registry reflection).

How to call external program from vim with visual marked text as param? -

call pattern: path-to-programm visual-marked-text filetype directory example: "c:\programme\wingrep\grep32.exe" search-pattern *.sql d:\myproject\build the following vim-script function can used that. function! feedvisualcmd(cmdpat) let [qr, qt] = [getreg('"'), getregtype('"')] silent norm! gvy let cmd = printf(a:cmdpat, shellescape(@")) call setreg('"', qr, qt) echo system(cmd) if v:shell_error echohl errormsg | echom 'failed run ' . cmd | echohl none endif endfunction it copies selected text unnamed register (see :help "" ), runs given template of command through printf function, , executes resulting command echoing output. if part of command changes pattern, convenient define mapping, vnoremap <leader>g :<c-u>call feedvisualcmd('"c:\programme\wingrep\grep32.exe" %s *.sql d:\myproject\build')<cr>

.NET FtpWebRequest: How to check if file is ready to download -

i have service .net using ftpwebrequest download images ftp server. have camera stores images on same ftp server. if service see image , tries download before camera has finished storing same image, 'not-yet-stored-part' of image appears grey (corrupted). question: how detect whether image ready download (stored completely)? if had control on sending service, implement using marker files. if sending service e.g. write ".finished" file when it's done, wait file appear. however, suspect not have control on software in camera. there few issues detecting whether camera has finished uploading, slow internet connection. i think best solution check changes in file size. monitor folder , see whether new files appear. then, if file size has not changed e.g. minute, should safe download file.

iphone - shopkick application UI widgets -

please see link below. http://itunes.apple.com/app/id383298204?mt=8 there screen shots of showpick application. in there collect button impossible implement under ui tab bar. can me figure out how have implemented it? actual uitabbar? thank you i figured out workaround. add dummy controller middle entry of uitabbarcontroller. , in viewdidload add button uitabbar so: tabbarbutton = [[uibutton alloc]initwithframe:cgrectmake(125, -10, 70, 33)]; [tabbarbutton setbackgroundimage:[uiimage imagenamed:@"state-inactive"]forstate:tabbarbutton]; [topbarbuttonscan setbackgroundimage:[uiimage imagenamed:@"state-active"]forstate:uicontroleventtouchdown]; [tabbarbutton addtarget:self action:@selector(tabbarbuttonclicked:) forcontrolevents:uicontroleventtouchupinside]; [[[self tabbarcontroller]tabbar ] addsubview: tabbarbutton];

groovy - Grails - trying to deploy a nojars application into glassfish 3.0.1 -

because of memory constraint trying build grails app smaller memory footprint. build war argument "--nojars". created war file without jar , when deploy within glassfish encounter error exception while loading app : java.lang.exception: java.lang.illegalstateexception: containerbase.addchild: start: org.apache.catalina.lifecycleexception: java.lang.illegalargumentexception: java.lang.classnotfoundexception: org.codehaus.groovy.grails.web.util.log4jconfiglistener it seems application fail find jar file. i had indicates path library before deploying application in glassfish. did miss out somethinng? it commonly recommended use glassfish's common classloader . means putting shared jars $domain-dir/lib folder (but not subfolder of that). you're trying use application classloader asadmin deploy --libraries command. more complicated , error-prone. if don't need different versions of same jars different web applications, should go common classl

parsing - How can I parse this xml? -

<?xml version="1.0" encoding="utf-8"?> <soap:envelope xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:xsd="http://www.w3.org/2001/xmlschema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:body> <paymentnotification xmlns="http://apilistener.envoyservices.com"> <payment> <uniquereference>esdeur11039872</uniquereference> <epacsreference>74348dc0-cbf0-df11-b725-001ec9e61285</epacsreference> <postingdate>2010-11-15t15:19:45</postingdate> <bankcurrency>eur</bankcurrency> <bankamount>1.00</bankamount> <appliedcurrency>eur</appliedcurrency> <appliedamount>1.00</appliedamount> <countrycode>es</countrycode> <bankinformation>sean wood</bankinformation> <merchantreference>esd

javascript - Setting style attribute to none for every table tr and td elements inside a div using jquery -

i have div id testdiv. inside div have table no id or class . set style attribute of table tr , td elements inside div none. how can done using jquery code. example code appreciated please help. thank you you can use .removeattr() , this: $("#testdiv").find("table, tr, td").removeattr("style"); note though removes inline styles, whatever's defined in stylesheets still apply. from more general standpoint, id never needed select element, can use element selector have in .find() call above, example code looks <table> , <tr> , , <td> elements descendants of <div id="testdiv"> .

Windows batch: Unicode parameters for (robo) copy command -

i need copy multiple files in single batch file. files have unicode names map different codepages. example: set arabicfile=ڊڌڵڲڛشس set cyrillicfile=щЖЛдЉи set germanfile=bücher copy %arabicfile% someplaceelse copy %cyrillicfile% someplaceelse copy %germanfile% someplaceelse problem: batch files cannot unicode. question: how can write unicode file names batch file copy command recognizes them? notes: i not care how file names displayed. batch file more copy these files, simplified description make problem clearer. correct batch file: with arnout's answer modified batch file follows. works correctly without requiring font change (which messy, arnout commented). @echo off chcp 65001 set arabicfolder=ڊڌڵڲڛشس set cyrillicfolder=щЖЛдЉи set germanfolder=bücher robocopy /e d:\temp\test\%arabicfolder% d:\temp\test2\%arabicfolder% /log:copy.log robocopy /e d:\temp\test\%cyrillicfolder% d:\temp\test2\%cyrillicfolder% /log+:copy.log robocopy /e d:\temp\test\%germa

WCF 4 default time outs? -

my last experience wcf 3.0 pretty bad, because of reverted using asmx. see wcf 4.0 seems provide better configuration model, concern wcf 3.0 had lot of timeouts on extended service calls, asmx these timeout values can configured through iis , accept negative integer value of -1. does wcf 4.0 default configuration support getting timeout values iis, or once again need configure timeouts handle extended web service calls take time complete (could 6 hours). thanks in wcf have configuration level control on timeouts on both servers , clients editing binding configuration. since wcf not designed coupled iis don't think can inherit timeouts iis might have set them in both places. check link documentation on basichttpbinding element (which used soap 1.1): http://msdn.microsoft.com/en-us/library/ms731361.aspx and 1 details on different timeout configurations in wcf: http://social.msdn.microsoft.com/forums/en-us/wcf/thread/84551e45-19a2-4d0d-bcc0-516a4041943d/ i have

osx - Dynamic symbol lookup fails with statically embedded Python on Mac OS X -

i'm building mac os x application embed python. application technically bundle (i.e. main executable mh_bundle); it's plug-in application. i'd embed python statically, want able load extensions dynamically. i did following: included whole library ( -force_load path/to/libpython2.7.a ), reexported python symbols ( -exported_symbol_list path/to/list ), , added -u _pymac_error , got using this linking advice . bundle loads fine, internal python code appears work, fails when it tries import dynamic library ( time.so ) following message: traceback (most recent call last): ... importerror: dlopen(/<stripped>/time.so, 2): symbol not found: _pyexc_overflowerror referenced from: /<stripped>/time.so expected in: dynamic lookup this symbol part of python api , must in bundle already. can check this: nm -g build/debug/pyfm | grep _pyexc_overflowerror 00172884 d _pyexc_overflowerror 0019cde0 d _pyexc_overflowerror (it's listed twice because have 2 arc

objective c - How to call two digital phone number from the iphone App -

i try call 2 digital phone number app using schema: nsstring *strphone = [nsstring stringwithformat:@"tel:12"]; nsurl *phonenumberurl = [nsurl urlwithstring:strphone]; [[uiapplication sharedapplication] openurl:phonenumberurl]; but nothing happens. if use 3 digital number or more - works fine. know why so? apple's restriction?

iphone - Integrating Different Xcode projects into a single project -

in iphone app, had divided app modules. each module prepared individual xcode project. now have integrated modules referencing , copying necessary files. i want submit app store. will apple accept project comprised of different individual modules being referenced one? is right way of doing it? is there better way? should consider recreating whole project one? would different app delegates not issue if so? please , suggest thanks. when submit app store submit single .app binary , not xcode project. apple won't know you're referencing other projects. build files need , compile single binary.

Algorithm(s) for automatic layout of nodes and connections -

i'm planning on building subsystem of 1 of projects laying out set of interlinked nodes optimally. nodes represent websites , website pages , connections represent links between pages. user add first page diagram, add additional pages link original page. along way, pages cross-link other pages. where can start researching algorithms automatically select "clean" paths connection lines, automatically selecting best place position new nodes added , automatically laying out entire diagram? look @ work done authors of graphviz . website has links of background reading ought tackls.

javascript - jQuery UI Dialog IE8 problem -

i have jquery ui dialog contains form, allowing user post ad. since form contains file upload, form's target iframe. from iframe, destroy dialog in parent window , create new 1 (or change options of original dialog, doesn't make difference). point iframe, define new buttons new dialog attached events work on main window elements. in firefox, safari, chrome works well: var p = parent; p.$('#dialog_new_ad').html('<form id="post_ad_form" style="display: none" data-remote="true"></form><div class="header"><h1 class="header_title"></h1><div class="header_company"></div><div class="header_location"></div></div><div class="content"></div>'); p.$('#dialog_new_ad').dialog({ minheight: 600, width: 800, position: ['center',25], modal: true, autoopen: false, title: '<%= 'previ

Lifetime of objects in a collection in VB.Net -

i'm trying figure out lifetime of tmptabpages in following bit of code. lets assume form has empty tabcontrol named mytabcontrol, there's collection of strings called namecollection. private sub form1_load(byval sender system.object, byval e system.eventargs) handles mybase.load each itm in namecollection dim tmptabpage new tabpage(itm.tostring) 'add controls tmptabpage mytabcontrol.tabpages.add(tmptabpage) next end sub since scope of tmptabpage for/next block, typically it's lifetime until end of block right? since added collection has scope outside of block same lifetime collection, or in case mytabcontrol? finally, if call mytabcontrol.tabpages.clear tmptabpages in collection destroyed or sit around taking memory? the big deal classes derived control (including tabpage) dispose() method. immune automatic garbage collection, winforms keeps internal table maps handle of control control reference. that's why, say

Getting Started with Eclipse CDT -

i have downloaded latest eclipse cdt release (helios) , wanted try luck c++ programming (haven't done in ages). i tried "hello world" project, got stuck quite fast. first thing - #include <stdio.h> , #include <stdlib.h> got marked 'unresolved symbol' warning. found place can add include paths , pointed these headers visual studio installation have. after that, looked fine but: i don't see compilation errors/warnings in problems tab. i cannot run code - 'launch failed. binary not found' error my question simple - steps really need code compiled, linked , executed? tried looking on eclipse's site, didn't find reference that. i'm making guess here, running on windows, because particular error seems windows related one. you seem missing basic toolchain needed cdt build project. need files before started . suggest mingw installer, simple, , lets build windows compatible binaries. check out link above,