Posts

Showing posts from March, 2015

NHibernate HQL - select count(*) with having - can't get it to work -

Image
trying run following hql nhibernate: select count(distinct t) tweetcount tweet t join t.tweeter u left join t.votes v left join t.tags tag t.app = :app having count(distinct v) > 0 but reason having clause being ignored , it's counting tweets when 2 tweets have vote. want count number of tweets have @ least 1 vote. here database i tried adding group query so: select count(distinct t) tweetcount tweet t join t.tweeter u left join t.votes v left join t.tags tag t.app = :app group t having count(distinct v) > 0 ...but ended returning collection containing 2 integers each set '1' instead of unique result. this fit thwe bill select count(distinct t.id) tweetcount tweet t inner join t.votes v t.app = :app since inner joining votes table, tweet has no votes not counted against result set. an other way using pure hql syntax be select count(distinct t.id) tweetcount tweet t t.app = :app , size(t.votes) > 0 which...

Is there a difference between a ternary operator and an if statement in C#? -

this question has answer here: nullable types , ternary operator: why `? 10 : null` forbidden? [duplicate] 9 answers conditional operator cannot cast implicitly? 3 answers i'm working nullable datetime object , ran strange behavior. here's sample function: public datetime? weird() { datetime check = datetime.now; datetime? dt; if (check == datetime.minvalue) dt = null; else dt = viewer.activethroughutc.tolocaltime(); //this line give compile error dt = (check == datetime.minvalue) ? (null) : (viewer.activethroughutc.tolocaltime()); return dt; } as far know, line ternary operator should same preceding 4 lines, vs2010 giving me compile error, saying no conversion exists betwe...

android - Right to Left ProgressBar? -

does know how make view reversed, have horizontal progressbar , want right left instead of left right make subclass of normal progress bar view , implement ondraw method rotate canvas before drawing it: @override protected void ondraw(canvas canvas) { canvas.save(); canvas.rotate(180,<centerx>,<centery>); super.ondraw(canvas); canvas.restore(); } this should trick.

.net - C# abstract base class for common columns in LINQ -

this have far using system; using system.collections.generic; using system.data.linq; using system.data.linq.mapping; using system.linq; using system.text; namespace firelight.business { public interface ibaseentity<k> { k id { get; } } /// <summary> /// base business database connection object, primary key int /// </summary> /// <typeparam name="t">table name</typeparam> public abstract class baseentity<t> : baseentity<t, guid> t : class, ibaseentity<guid> { } /// <summary> /// base business database connection object /// </summary> /// <typeparam name="t">table name</typeparam> /// <typeparam name="k">primary key type</typeparam> public abstract class baseentity<t,k> : ibaseentity<k> t : class, ibaseentity<k> { // avoids having declare ibaseconnection @ partial c...

vim - fresh installation of gvim on ubuntu. where should I put my plugins? -

i installed gvim on fresh installation of ubuntu lucid. i've messed before that's why want start on correct step here. where should keep plugins , .vimrc? ? my current runtimepath on gvim is: runtimepath=~/.vim,/var/lib/vim/addons,/usr/share/vim/vimfiles,/usr/share/vim/vim72,/usr/share/vim/vimfiles/after,/var/lib/vim/addons/after,~/.vim/after one thing i've never been able working on gvim snipmate. has pointers on having work gvim? i use pathogen ~/.vimrc , plugins in ~/.vim/bundle , more details here . can see example here .

linux - Parse folder name in bash -

i have folders naming convention: yearmonthday_jobcode_descriptor ie 20101007_gr1234_whatsit i'm attempting write script few things: move folders date older $x ./old move folders date in future ./old move folders dont conform convention ./old delete folders in ./old date older $x + $y here current loop, can see bash scripting pretty mediocre. #!/bin/bash file in $1/*; if [ -d $file ]; echo $(echo $file | grep -oe "[0-9]{8}_[a-z]*[0-9]*_?.*") fi done i can handle looping, main concern @ moment how extract folder names variables can compared dates. current regex above checks conformity convention. you can use cut command tokenize string (-d specifies delimiter, -f specifies field want keep) - echo 20101007_gr1234_whatsit | cut -d'_' -f1 gives 20101007 from there, can use date command parse date- foo=`date -d 20101007 +%s` will convert date string epoch time (seconds since jan 1, 1970) can compared. if don...

solrnet - Solr stops responding (or slows down to molasses)...(Solr newbie) -

running multi-core solr under tomcat 6.0 /win 2008 server , asp.net queries via solrnet. 1 of cores huge i.e. ~25 million documents (~20 gb disk-space) , several fields. other 3 cores smaller (few gigs each). after couple of queries large index, solr slows down dramatically , stops responding i.e. can't open admin console. if restart tomcat, things again works ok few more queries , molasses stop. have checked machine ram , processor usage, both <50% utilization. i not sure issue might - memory leak? how can go finding issue? don't know solr/tomcat logs , logs should looking at. hope can help. you'll have tune jvm memory allocation -xms , -xmx settings. see: http://wiki.apache.org/solr/solrperformancefactors#ram_usage_considerations http://www.lucidimagination.com/community/hear-from-the-experts/articles/scaling-lucene-and-solr#d0e245

C# linq FirstOrDefault() -

i select 1 double value ienumerable, how can overload firstordefault() function, return null on default, instead of zero, iwant like: double? x = ... .firstordefault(); i can catch exception, , write double? x = null, have 20 variables, , not way why not do: double? x = mydoubles.cast<double?>().firstordefault();

Unable to open the stream coming from google map api in android? -

when using below url drawing route on map on android: stringbuilder urlstring = new stringbuilder(); urlstring.append("http://maps.google.com/maps?f=d&hl=en"); urlstring.append("&saddr="); urlstring.append(src); urlstring.append("&daddr=");// urlstring.append(dest); urlstring.append("&ie=utf8&0&om=0&output=kml"); its throwing exception when urlconnection.getinputstream called. httpurlconnection urlconnection=(httpurlconnection)url.openconnection(); urlconnection.setrequestmethod("get"); urlconnection.setdooutput(true); urlconnection.setdoinput(true); urlconnection.connect(); documentbuilderfactory dbf = documentbuilderfactory.newinstance(); documentbuilder db = dbf.newdocumentbuilder(); doc = db.parse(urlconnection.getinputstream()); new code: document doc=null; try { string url = geturl(p,...

c++ - Is my design for UDP socket server correct? -

i designing server used in udp communication using mfc. have following classes cmydlialog - take care of user interface ccontroller - act mediator between classes cprotocolmanager - take care of encoding/decoding msgs (this static class) cconnectionmanager - take care of udp connection, sending, receiving i creating object of cconnectionmanager member variable in ccontroller , object of ccontroller member variable in cmydialog. when user type , presses send, calling method in ccontroler call method in cprotocolmanager construct packet , call cconnectionmanager method send it. when receive data, handled in thread of cconnectionmanager. there creating local object of ccontroller , call method, pass data cprotocolmanager decode. now want inform ui data, how should ccontroler it? can post message ui making main dialog handle global, correct approach. also tell me whether design correct one. thanks in advance i think designs never right or wrong, can rate the...

c# - Parse a Number from Exponential Notation -

i need parse string "1.2345e-02" (a number expressed in exponential notation) decimal data type, decimal.parse("1.2345e-02") throws error it floating point number, have tell that: decimal d = decimal.parse("1.2345e-02", system.globalization.numberstyles.float);

php - Get information from JSON -

so doing this.. function get_info($data) { $json = file_get_contents("http://site.com/".$data.".json"); $output = json_decode($json, true); return $output; } which fine , returns this: array(1) { ["allocation"]=> array(20) { ["carrier_ocn"]=> string(4) "6664" ["available_on"]=> null ["status"]=> string(9) "allocated" ["access_type"]=> string(8) "wireless" ["ratecenter"]=> string(9) "charlotte" ["lat"]=> float(35.2270869) ["contaminations"]=> null ["city"]=> string(9) "charlotte" ["lng"]=> float(-80.8431267) ["current_on"]=> string(10) "2010-04-28" ["block_code"]=> null ["npa"]=> int(704) ["geo_precision"]=> int(4) ["nxx"]=> int(291) ["assigned_on"]=> null ["country"]=>...

c# - How do I convert ContextMenuEventArgs cursor location to window coordinates -

i'm trying display context menu user clicks mouse in wpf application. i've handled opencontextmenu event , handler has pair of doubles , e.cursorleft , e.cursortop coordinates of mouse click relative control clicked (in case datagridcell ). if display context menu using coordinates appears relative application window offset cursor amounts. how can convert datagridcell -relative cursor coordinates window coordinate space? you can use uielement.translatepoint(point, visual) method convert coordinates 1 control's coordinate space another. following code should want (not tested!) : point target = mydatagridcell.translatepoint(new point(e.cursorleft, e.cursortop), application.current.mainwindow); however, if want display context menu, assign frameworkelement.contextmenu property control should show context menu. way, position positioned @ mouse cursor automatically. if have more complicated scenario, might still use method above.

sql server - I can't add Microsoft.SqlServer.Management.Common to my ASP.NET MVC Application -

i trying add reference above assembly not appear in asp.net mvc .net 4 (not client) applications assembly list. know how reference assembly? the microsoft.sqlserver.management.common namespace resides in microsoft.sqlserver.connectioninfo.dll assembly. microsoft.sqlserver.management.common namespace (msdn) assuming default installation folders can find microsoft.sqlserver.connectioninfo.dll assembly in: c:\program files\microsoft sql server\xxxx\sdk\assemblies where xxxx represents version of sql server you're running: 80 -> sql server 2005 90 -> sql server 2008 100 -> sql server 2008r2 if you're running sql server 32bit on x64 instead of c:\program files use c:\program files (x86) .

c++ - Finding Pixel Color -

i trying figure out how extract rgb value pixel chosen. every time click though, gives me value of 0, though clicking on colored triangle. void mouse(int button, int state, int x, int y) { if(state == glut_down) { float mx = p2w_x(x); // pixel world coordinates float = p2w_y(y); float rgb[3]; glreadpixels(mx, my, 1, 1, gl_rgb, gl_float, rgb); std::cout << rgb[0] << std::endl; // prints 0 red } } i don't think should convert pixel coordinates world coordinates. don't know gl, looks wrong me. pixel coordinates mouse right? , want pixel color value, from framebuffer . maybe use integer type color value, gl_unsigned_byte , array of unsigned char rgb[3]; instead. , use gl_rgb8 format, instead of plain gl_rgb. also see how set pixel format (store) of frame buffer. affect subsequent glreadpixels calls.

perforce - TeamCity: Error on VCS update -

hey guys, have trouble getting vcs of teamcity work. i'm using perforce , tc-server should configured correct, when running project i'm getting error: [updating sources: server side checkout...] error while applying patch: failed change text file: c:\projects\buildsrv7... c:\projects\buildsrv7.. (access denied) i checked settings , has full rights in directory. and idea, do, or how happen? thanks in advance - thomas please check known issues . it's case.

dll - Programming an ActiveX component in Visual Studio 2008 vc++ -

anyone knows tutorial programming activex in visual studio 2008 vc++? or way create methods , properties automatically, old wizzard in vs6.0 did? i trying harder find info, c#, vb, or it's explained vs6.0 , not 2005 or newer :( thanx everybody. well, do take hint lack of decent samples or tutorials. if want in c++ check out copy of chris sells' atl internals. still in print afaik. contains complete walkthrough creating activex control using atl.

Selenium RC and PHP for beginners -

i running ubuntu server apache/php/mysql. want use selenium on 1 of php projects. basically, want setup can more or less copy paste code firefox selenium ide (format set php) php project, this: <?php require_once 'phpunit/extensions/seleniumtestcase.php'; class example extends phpunit_extensions_seleniumtestcase { protected function setup() { $this->setbrowser("*chrome"); $this->setbrowserurl("http://www.google.com/"); } public function testmytestcase() { $this->type("q", "stack overflow"); $this->click("link=2"); $this->waitforpagetoload("30000"); $this->click("btng"); $this->waitforpagetoload("30000"); $this->type("q", "stack overflow php"); $this->click("btng"); $this->waitforpagetoload("30000"); } } ?> i have tried figure out how in php using selenium rc, doc...

Https Implementation in asp.Net -

how can implement https login in asp.net , c# i'm assuming ok normal login page. ssl buy certificate , install http://www.instantssl.com/ssl-certificate-support/cert_installation/iis_ssl_certificate_5x.html then make sure login page redirects https rather http. if (!request.issecureconnection) { response.redirect(request.url.absoluteuri.tolower().replace("http", "https"), true); }

c# - How to specify data types when dragging content to Excel -

i initiating drag , drop winforms application using simple idataobject data = new dataobject(); string texttoexcel = "hello\tworld\t1\t2\nhello\tworld\t1\t2\n" data.setdata(dataformats.text, texttoexcel); i works fine when dropped on excel, ends nicely in columns , rows. problem excel not know cells values 1 , 2 numerics , gets worse when dropping date value. how can tell excel data types of individual cells, there richer type excel accepts when content being dropped it. all able communicate drag-drop excel strings, excel automatically convert date or numeric type if can. if don't want convert identifable types data type should begin value appostrophe (') character, such '100, instead of 100. if wish have full control, should subscribe excel.worksheet.change event triggered @ end of drag-drop action. @ point can custom conversion of own data. facilitated if transmit data custom format begin with, 1 not automatically converted excel. example, i...

entity framework - EF CTP4 lazy loading not playing ball -

i'm using ctp4 code first ef framework, i'm having problems getting lazy loading work. reading on it, should simple, it's not public class folder { public int id { get; set; } public string name { get; set; } public int? parentfolderid { get; set; } public virtual ilist<folder> childfolders { get; set; } } in model configuration: hasmany(f => f.childfolders).withoptional().hasconstraint((child, folder) => child.parentfolderid == folder.id); however, when this: folder folder = context.folders.singleordefault(f => f.id == 1); folder.childpages null....but should lazy loading it... i found answer this, actually: empty constructor "folder" marked internal, , although there no hard failures, seems enough cause problems.

spring - JPA and DAO - what's the standard approach? -

i'm developing first app jpa/hibernate , spring. first attempt @ dao class looks this: @repository(value = "userdao") public class userdaojpa implements userdao { @persistencecontext private entitymanager em; public user getuser(long id) { return em.find(user.class, id); } public list getusers() { query query = em.createquery("select e user e"); return query.getresultlist(); } } i found examples using jpadaosupport , jpatemplate . design prefer? there wrong example? i'd approach looks totally sound. don't use jpadaosupport or jpatemplate because can need entitymanager , criteria queries. quote javadoc of jpatemplate : jpatemplate exists sibling of jdotemplate , hibernatetemplate, offering same style people used it. newly started projects, consider adopting standard jpa style of coding data access objects instead, based on "shared entitymanager" reference injected via ...

windows xp - C# system stopping tray application -

i have c# app starts @ system boot in tray, , have following problem it, on windows xp i can't restart pc while application running. if use file > exit, stops ok , can restart. if try restarting application open, won't it i tried adding in main window constructor, dunno if right thing do: application.applicationexit += new eventhandler(this.onapplicationexit); and onapplicationexit function app's shutting down procedure.. doesn't help any ideas? do have formclosing event handler somewhere e.cancel = true; ? if so, change first @ close reason decide if should cancel or not as: if(e.closereason != windowsshutdown) e.cancel = true; there might other closereasons should not cancel closing might worth looking @ msdn that.

dependencies - maven dependency range does not work as expected -

maven 2.2.1 claims support version ranges (see e.g. http://www.sonatype.com/books/mvnref-book/reference/pom-relationships-sect-project-dependencies.html#pom-relationships-sect-version-ranges ) i tried brandnew maven installation following pom: <project> <modelversion>4.0.0</modelversion> <artifactid>rangetest</artifactid> <groupid>my.group</groupid> <version>1.0</version> <packaging>jar</packaging> <description>test project containing 1 dependency, only</description> <dependencies> <dependency> <groupid>junit</groupid> <artifactid>junit</artifactid> <version>4.8</version> <scope>test</scope> </dependency> </dependencies> </project> the dependency should resolve junit 4.8.2, right? instead, version 4.8 resolved: c:\users>mvn dependency:tree [info] scanning projects... [info] sea...

android - Question related to current View -

is there way can current view specifying position of view? i have view position me , need view. there way? assuming know root view should start with, can walk down hierarchy using depth-first search. when going or down in level, offset coordinates results of getleft , gettop methods, return coordinates of specific view relative level.

asp.net - Google Sitemap HttpHandler cacheing -

i have httphandler generates google sitemap based on asp.net web.sitemap. standard stuff. except heavy database work auto-generate additional urls ajax tabs within pages. all means our db gets hit heavily if bot hits sitemap.axd. what need, of course, output caching. how go caching inside writes directly xmltextwriter? the simplest answer write xml string , store in static field.

trouble in converting Generic List coming from a WCF Service to a DataTable -

i confused on how can use generic methods parse generic list datatable/dataset. setup: 1. have class customers defined in wcf service library. namespace wcf.sample.servicelibrary { public class customers { public string id = string.empty; public string companyname = string.empty; public string contactname = string.empty; } } 2. use class return generic list operationcontract. namespace wcf.sample.servicelibrary { [servicecontract] public interface icustomerservice { [operationcontract] list<customers> getallcustomers(); } } 3. consume wcf service in web client page. on button click populate gridview list returned getallcustomers(). works fine. gridview1.datasource = client.getallcustomers(); gridview1.databind(); 4. issue is, reason (sort/paging function) want convert returned generic list datatable. so, have method returns me datatable want bind gridview. here methods: public static data...

port - Configure a PIC pin for Input and Output -

i working on project uses pic24fj64ga002 mcu. working on bit-banged serial communication function use 1 wire send data , switch receive mode receive data on same pin. separate pin used clocking controlled different board (always input). wondering there way configure pin open-collector operation that can used input , and output or have change pin configuration every time go reading writing? you need change direction of pin each time using tris register. if pin set output, reading port register tell level driving pin (assuming there high impedance on pin). if pin set input, won't able drive desired output value. also, make sure read incoming data using port register, output data using lat register. ensures don't suffer issues if code (i assume programming in c here) gets converted bset/bclr/btgl instructions read-modify-write. if writing in assembler, same rule applies know when using these r-m-w type instructions. if want more reasoning on this, please ask.

cocoa - Getting an image from NSGraphicsContext -

how can drawing in graphics context image? if graphics port cgbitmapcontext, can create image that. but that's not want rely on. if context's graphics port isn't cgbitmapcontext, you're screwed. moreover, there's no safe way tell whether it's cgbitmapcontext or not. so, really, can't create image nsgraphicscontext. this leads question of alternatives. if it's nsview that's drawing context, problem solved: can ask view pdf of draws , , (if necessary) create image that. or, lock focus on view , create nsbitmapimagerep focused view. neither 1 of these work inside drawrect: (the latter may work, wouldn't trust not call drawrect: ). if think need image within drawrect: in order rubber-stamp drawing multiple places, there 2 much-better solutions: move drawing code method , call every time need draw that, or create cglayer , draw image once it, , draw cglayer needed. drawing same thing repeatedly cglayers exist for.

unix - C++: how to convert date string to int -

hi need procedure convert string time int. support formats under unix: "wed, 09 feb 1994 22:23:32 gmt" -- http format "thu feb 3 17:03:55 gmt 1994" -- ctime(3) format "thu feb 3 00:00:00 1994", -- ansi c asctime() format "tuesday, 08-feb-94 14:15:29 gmt" -- old rfc850 http format "tuesday, 08-feb-1994 14:15:29 gmt" -- broken rfc850 http format "03/feb/1994:17:03:55 -0700" -- common logfile format "09 feb 1994 22:23:32 gmt" -- http format (no weekday) "08-feb-94 14:15:29 gmt" -- rfc850 format (no weekday) "08-feb-1994 14:15:29 gmt" -- broken rfc850 format (no weekday) "1994-02-03 14:15:29 -0100" -- iso 8601 format "1994-02-03 14:15:29" -- zone optional "1994-02-03" -- date "1994-02-03t14:15:29" -- use t separator "19940203t141529z" ...

ios4 - iPhone 4 App continues to run in background with debugger -

on iphone multitasking , ios4.1, if have debugger connected noticed code still being run in background, breakpoints still hit, timers running. without of background modes set. is case having debugger connected prevents app being suspended? an app can continue running short period of time after it's been suspended. should use uiapplicationdelegate methods check what's going on. here's quote: applicationdidenterbackground: implementation of method has approximately 5 seconds perform tasks , return. if need additional time perform final tasks, can request additional execution time system.

encapsulation - Using a strategy pattern and a command pattern -

Image
both design patterns encapsulate algorithm , decouple implementation details calling classes. difference can discern strategy pattern takes in parameters execution, while command pattern doesn't. it seems me command pattern requires information execution available when created, , able delay calling (perhaps part of script). what determinations guide whether use 1 pattern or other? i'm including encapsulation hierarchy table of several of gof design patterns explain differences between these 2 patterns. better illustrates each encapsulates explanation makes more sense. first off, hierarchy lists scope given pattern applicable, or appropriate pattern use encapsulate level of detail, depending on side of table start at. as can see table, strategy pattern object hides details of algorithm's implementation, use of different strategy object perform same functionality in different way. each strategy object might optimized particular factor or operate on othe...

iphone - Mimicking xcode's build process through xcodebuild -

i'm looking build + run iphone xcode project totally outside of xcode. currently i'm using xcodebuild build project - seems build cleanly: https://gist.github.com/8eadfb1acca4d101624b unfortunately doesn't seem replicate same build done xcode. rebuilding leads bunch of syntax errors. are there other flags should passing xcodebuild? maybe have problem shared precompiled headers? like, building different versions of project on same machine. try stating "clean build" (or clean install, whatever want do) build actions @ end of xcodebuild call.

c# - Need a regular expression for detecting simple math expressions -

i'm going validate simple math expressions such these: a = 1 + 2 b = 2.2 = b + 5.5 = b - -5.5 = -1 + 2 = -2.4 = 3.5 / 0.2 + 1 = 3 * -2.1 note: operator precedence not important! i try following expressions got nothing!!! for digits: ^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$ operators: [-]|[+]|[*]|[/] variables: [a-z]+|[a-z]+ i put these expressions in c# string variables , used .net regex.matches(...) find matches. got nothing! this not great job regular expressions. if want evaluate true mathematical expression not able come regex can handle cases. carl norum said similar discussion why can't parse html regex .

c++ - Create a vector of pointers to abstract objects -

i'm sure there's better way this. i'm trying create class hashtable given size @ instantiation, can't given size @ design time, can't use array internal representation of table, far know. so here's i'm trying do: #include <vector> #include <iostream> #include "nodes.h" using namespace std; template <class t> class hashtable{ protected: vector<* tablenode<t>> mytable; //other protected methods go here public: hashtable(int size){ mytable = vector<* tablenode<t>>(size,null); } //the rest of class }; from i've seen, vector best data structure use here, because let me give size in constructor, , lets me use mytable[index] style notation access contents. however, vs2010 doesn't use of vector<* tablenode<t>> , can't blame it. so, how create array or vector or whatever of pointers tablenode<t> elements? move asterisk around: vect...

php - Picking up ZF2, is it worth it now? -

i've been web developer past 8 years (although i'd consider second half of time real experience) in past year i've done couple of zend framework based business applications , i've been able comfortable it. now have been offered position leading start-up on technical side, i'm pretty excited given freedom make crucial decisions , encourage use new technologies make our product 'cutting edge'. so question more experienced guys are: worth picking zf2? transition of learning new ways easy? how coding style change? can 1 start current available version , rely future releases compatible? benefits of zf2 vs 1 great enough justify investing time adopting when faced job such mine? there more important questions should asking? thanks, advice appreciated :) update zend framework 2 stable released http://framework.zend.com/blog/zend-framework-2-0-0-stable-released.html most important feature of zf2 namespacing. there effort in autoloading , faste...

android - Run Hierarchy Viewer on W7(doesn't work) -

i working on android. try inside terminal execute java -jar hierarchyviewer.java and have error 11:46:48 e/adb: failed adb version: cannot run program "adb": createp rocess error=2, system cannot find file specified i can run hierarchyviewer.jar /tools/lib (double click) can see graphic interface not show anything, cannot see tree , stuff. using windows 7, 64 bit , executing emulator and/or device before running hierarchyviewer. http://developer.android.com/guide/developing/tools/hierarchy-viewer.html try add path of android sdk path environment variable.

php - What's the most efficient way to sort through emails with zend_mail? -

i'm sorting through emails looking specific instances of strings , taking long. time down half second per email, , it's taking 2-2.5 seconds per email. i'm worried i'm doing dumb that's slowing down - mysql or zend_email. code checks user's inbox specific phrase "chocolate", returns values jquery ajax function. loops through ten times (in version, checks 10 emails). if see decrease loading time, appreciated. initially, thought not including libraries helpful, libraries without email opening functions lightning fast. i'm sure i'm doing dumb , amateurish (maybe few things). please point them out if possible. here's code... <?php $storage = new zend_mail_storage_imap($imap); $x=0; while($x<10) { $flags = $storage->getmessage($i)->getflags(); if(!empty($flags['\seen'])) { $read=1; } else ...

c - How is negative zero used in this context? -

struct in_addr ipv4; ipv4.s_addr = (uint32_t)(-0) that's strange, arithmetic implemented through two's complement don't have negative representation of 0 . in one's complement version negative 0 instead stored 0xffffffff have 255.255.255.255 when converted ipv4 address after cast unsigned int. while in normal architecture using -0 cast unsigned int should give 0x00000000 .

ruby on rails - Windows Gem Installation -

i'm newbie ruby on rails. had quick question installing gems. i'm using windows 7 64 bit machine ruby 1.9.2 , rails 3.0 , i'm trying install gravatar_image_tag gem . gem install gravatar_image_tag after run says succcessful. when try this: gravatar_image_tag -v it says 'gravatar_image_tag' not recognized internal or external command, operable program or batch file' when looked ruby192/bin file there batch files rails, annotate etc etc work fine there's not batch file gravatar_image_tag. i wondering i'm going wrong this. thanks in advance. not gems executable command line. best way see if gem installed (as version) run: gem list

javascript - PHP to JSON on client side -

i'm using rob monies 'jquery week calendar' build calendar application. i have mssql db table named 'dates' , following fields: id start end title i query db in php , pass results javascript, javascript render events in browser. the javascript needs receive event details in json format per following example: {"id":1,"start": 2010-10-09t13:00:00,"end":2010-10-09t14:00:00,"title":"lunch mike"}, {"id":2,"start": 2010-10-10t13:00:00,"end": 2010-10-10t14:00:00, "title":"dev meeting"} so far, keep things simple i've returned 1 row db @ time, - need application able render multiple events, stored in database. i've tried using json_encode() put values var , pass them javascript var called db_events - if return db_events in alert box on client side see following; {"id":1, "start":2010-10-09t13:00:00, "end":2010-10-09t1...

sql - There is a way to use a calculated field in the where clause? -

there way use calculated field in clause ? i want like select a, b, a+b total ( select 7 a, 8 b dual union select 8 a, 8 b dual union select 0 a, 0 b dual ) total <> 0 ; but ora-00904: "total": invalid identifier. so have use select a, b, a+b total ( select 7 a, 8 b dual union select 8 a, 8 b dual union select 0 a, 0 b dual ) a+b <> 0 ; logically , select clause 1 of last parts of query evaluated, aliases , derived columns not available. (except order by , logically happens last.) using derived table away around this: select * (select a, b, a+b total ( select 7 a, 8 b dual union select 8 a, 8 b dual union select 0 a, 0 b dual) ) total <> 0 ;

c# - Implementing IComparable<> in a sealed struct for comparison in a generic function -

i have c# .net 2.0 cf application i'm validating return value object. cannot modify structure or function returns it. /// structure returned function object under test public struct sometype { int a; int b; char c; string d; public static sometype empty { { return new sometype(); } } } /// pretend function in object under test static sometype functionundertest() { return sometype.empty; } since may have many functions returning many different types, wanted use generic comparison function. open modification. static bool compare<t>(validationtypes validatecond, t actualvalue, t expectedvalue) t : system.icomparable<t> { switch (validatecond) { case validationtypes.equal: return actualvalue.compareto(expectedvalue) == 0; case validationtypes.notequal: return actualvalue.compareto(expectedvalue) != 0; case validationtypes.lessthan: return actualvalue.compareto(exp...

javascript - Pass along & sign with href to php page help -

i have this: browse_cat.php?cat_gr='mopeds &amp; traktors'"> the browse_cat.php contains fetch above " category ": $cat=$_get['cat_gr']; echo $cat; this echo outputs first word " mopeds ". wont change if replace &amp ; & . what problem here? the adress bar when enter browse_cat.php shows: browse_cat.php?cat_gr='mopeds%20&%20traktors' thanks take @ urlencode() , urldecode() . also, remove single quotes around query string.

javascript - Append #hashtag to link in HTML on the fly -

i have nav, each link in nav appends hashtag on existing url when clicked, live filtering, etc. use of jquery. i want append same current hashtag series of links within div further down page. for example, i've clicked "work" , url looks like: http://www.domain.com/page.html#work i have series of links in page: <div id="links"> <ul> <li><a href="http://www.domain.com/link1">link1</a></li> <li><a href="http://www.domain.com/link2">link2</a></li> <li><a href="http://www.domain.com/link3">link3</a></li> <li><a href="http://www.domain.com/link4">link4</a></li> </ul> </div> these links within div#links need updated on fly append #work on url's when clicked hashtag appended. is possible? make sense? you should attach click event handler links in #nav , change links in #li...

licensing - Free, Then Open-Source Upon Death? -

i've been quite surprised free software models (after discovering postcard ware), thought might worth asking. i have application i'm going release free software. however, in case not maintain it, or unable maintain it, released open source. there kind of license this? [please use comments , not answers tell me why bad idea.] thanks! ask yourself: if don't have problem give away software free (as in speech, not in beer) @ end of day, why not start right now? fear others take code , publish competing (although free) software? forks happen while project still under maintainance. expect people start fiddling code @ point stopped it. do think go trouble find out whether can take software free or not based on crude terms being "unable" maintain it. how people around globe find out death, example? taking risk of getting sued or beneficiary or not being able use work anymore? i recommend release software under gpl3 start on. keep control of proje...

django - How to update content popularity scoring such as Hacker News algorithm? -

i'm using customized version of hacker news popularity algorithm social site (items number of likes , comments). algorithm works don't know how update item scorings correctly (i'm storing score in item model meta data). now i'm updating scores on every new , comment items listed during past 9 days. slow , resource heavy i'm looking better way keep scores date. problem every item needs new score when 1 changes keep time decay. better way this? i'm using django project. ok. have done using different apps: first, need install either "dokterbob/django-popularity" on github or "thornomad/django-hitcount" track how link visited. second, need count how many votes (likes or favorites) object receives. purpose, can try "brosner/django-voting", "apgwoz/django-favorites". now have use piece of code -- django-populars put them together. recommend looking this code first of see how works understand how put needed ...

Which programming languages allow default values for method parameters? -

i'm curious languages allow this: method foo(string bar = "beh"){ } if call foo this: foo(); bar set "beh", if call this: foo("baz"); bar set "baz". php: function foo($var = "foo") { print $var; } foo(); // outputs "foo" foo("bar"); // outputs "bar" python : def myfun(var = "foo"): print var ruby : def foo(var="foo") print var end groovy: def foo(var="foo") { print var }

interprocess - Talking to unmanaged process from .NET -

i'm creating process .net using process.start. new process legacy app, written in c/c++. communicate it, need equivalent of postthreadmessage primary thread. i'd happy use p/invoke call postthreadmessage, can't see how find primary thread. process object has collection of threads, doc says first item in collection need not primary thread. thread objects don't seem have indication of whether they're primary. , while @ thread collection after creating process, that's no guarantee there one. so, there way me determine process' primary thread .net, or need resort using win32's createprocess? thanks, bob if process has window, can use getwindowthreadprocessid api gui thread, primary thread (use process.mainwindowhandle window handle). another option enumerate threads ( process.threads ) , pick first 1 started, based on starttime : process process = process.start(...); process.waitforinputidle(); processthread primarythread = process...

javascript - I need to validate free flow textbox value matches value from database table -

i need validate given name field in asp.net form. user name: alex brandon in database, have users table user_name column. i need validate on lost focus of user name form field, exists in users table , valid else show alert. does has ready solution this? do want in javascript, or planning on trip server? if it's trip server (via asp.net ajax or postback) you'd have to. select * users user_name=@name and set name parameter textbox value... note unless care case, may want uppercase 2 names comparison.

java - Program With Plugins: GPL With LGPL? -

i have 2 distinct projects: the program want release under gpl license. the plugin api: plugins written using interfaces in api, , program uses api communicate plugins. want release plugin api lgpl license. one problem not want plugins have reveal source. "infected" gpl license? compiled against api, , wouldn't need source program compile. another problem there's talk of "static-linking" lgpl: program , api written in java. matter? anyway, basic question: make sense release program gpl, , public api lgpl? if writing application scratch, can license want. if want make exception gpl plugins, there precedent. gpl linking exception (such classpath exception) you're looking for.

c++ - How to print to console when using Qt -

i'm using qt4 , c++ making programs in computer graphics. need able print variables in console @ run-time, not debugging, cout doesn't seem work if add libraries. there way this? if enough print stderr , can use following streams intended debugging: //qinfo qt5.5+ only. qinfo() << "c++ style info message"; qinfo( "c style info message" ); qdebug() << "c++ style debug message"; qdebug( "c style debug message" ); qwarning() << "c++ style warning message"; qwarning( "c style warning message" ); qcritical() << "c++ style critical error message"; qcritical( "c style critical error message" ); // qfatal not have c++ style method. qfatal( "c style fatal error message" ); though pointed out in comments, bear in mind qdebug messages removed if qt_no_debug_output defined if need stdout try (as kyle strand has pointed out): qtextstream& qstdout()...

azure - Data provider class for sql database -

i need write data provider class pull data sql database use in webpage display bing map. have link provide tutorial on how this? i have little experience using db provide dynamic data web page appreciated. database sql azure databse. you need research data access in .net , orm technologies .net. question deals similar concepts. simple data access layer note: there nothing "special" need apply standard .net data technologies azure sql.

Connecting to MongoDB from MATLAB -

i'm trying use mongodb matlab. although there no supported driver matlab, there 1 java. fortunately able use connect db, etc. downloaded latest (2.1) version of jar-file , install javaaddpath. tried follow java tutorial . here code javaaddpath('c:\matlab\myjavaclasses\mongo-2.1.jar') import com.mongodb.mongo; import com.mongodb.db; import com.mongodb.dbcollection; import com.mongodb.basicdbobject; import com.mongodb.dbobject; import com.mongodb.dbcursor; m = mongo(); % connect local db db = m.getdb('test'); % db object colls = db.getcollectionnames(); % collection names coll = db.getcollection('things'); % dbcollection object doc = basicdbobject(); doc.put('name', 'mongodb'); doc.put('type', 'database'); doc.put('count', 1); info = basicdbobject(); info.put('x', 203); info.put('y', 102); doc.put('info', info); coll.insert(doc); here stacked. coll supposed dbcollection object, o...

c++ - How to bring another window forward that is not owned by the program -

i'm struggling find way of bringing forward programs window. for example, use findwindow find handle of notepad. try bring window forward using setwindowpos(hwnd, 0,0, 0, 0, 0, swp_showwindow|swp_nosize|swp_nomove); but doesnt work!! showwindow doesnt either! can please , maybe show me snippet of code? thanks dunno if same thing or not, @ point in windows development microsoft added too-clever-by-half "anti-popup" code prevent program not have focus un-minimizing windows... instead, window's entry in programs-bar blink. perhaps there similar logic preventing non-foreground program bringing window forward? in case, here code try, might or might not help: // check see if foreground thread dword foregroundthreadid = getwindowthreadprocessid(getforegroundwindow(), null); dword ourthreadid = getcurrentthreadid(); // if not, attach our thread's 'input' foreground thread's if (foregroundthreadid != ourthreadid) attachthreadinp...

iphone - lifetime of [NSMutableDictionary dictionaryWithCapacity:n] -

i thought object returned nsmutabledictionary dictionarywithcapacity: released when autorelease pool in main.m drained. instead, when assign instance member in -init, find object lasts long -init call. what managing release of object returned nsmutabledictionary dictionarywithcapacity: ? to further mystify going on here, find when assign object of custom class created convenience constructor instance member in init, instance still "alive" in (for example) touchbegan: ... generally speaking, apis 1 return autorelease d instances. that mean when autorelease pool drains, object destructed. if don't manage autorelease pool yourself, should destructed when next return message queue (assuming you're on ui thread). internally, os pushes , pops autorelease pool around each event calls code. so, if have -touchbegan , there new pool pushed before -touchbegan gets called, , popped -touchbegan returns. if that's not want, you'll have retain yo...

How to detect a link within div in jQuery? -

if clicks on link within div class "foo" want list items within div show. how can this? here's failed attempt: $('div > li').hide(); $('div.foo > a').click(function(event) { $('div.foo > li').show(); event.preventdefault(); }); <ul> <div class="foo"> <a href="#">animals +</a> <li>cat</li> <li>dog</li> <li>rabbit</li> </div> </ul> you have problem html. it should this, <div class="foo"> <a href="#">animals +</a> <ul> <li>cat</li> <li>dog</li> <li>rabbit</li> </ul> </div> then in jquery, this, $('div.foo > ul').hide(); $('div.foo > a').click(function(event) { $(this).next('ul').show(); event.prevent...

java - How to enter a directory as an argument in Eclipse -

basically, have directory files in it. in run configurations trying put directory arguement so: \(workspacename\directory . then, following code should create list of files in directory: string directory = args[1]; file folder = new file(directory); file[] allfiles = folder.listfiles(); arraylist<file> properfiles = null; (file file: allfiles) { if(file.getname().endswith(".dat")){ properfiles.add(file); } } the problem i'm facing reason allfiles null. i'll take guess @ problem might be: if argument relative path (as opposed absolute path, staring "/" or "c:/" example), keep in mind files relative working directory of application. so new file(directory) relative wherever application started. in eclipse default working directory in project. if project in top level of workspace, workspacename/project . you can try printing out folder.getabsolutepath() , folder.exists() , folder.isdirectory() diagnose proble...

c# - How can I change the name of a windows service? -

i have windows service application developed in c#. same service needs run different config files. run on these on same machine need change name of service. can create multiple copies of solution, not sure how change names of services. thanks in win service class derives servicebase , there property inherited can set called servicename . make app.config, add setting service name , have win service class assign property accordingly. way each service name unique long change setting in app.config.

iphone sdk 3.0 - ipad: Image loading and Memory management problem & crash of the app -

i having 60 different images coming webservice.and storing in nsmutablearray. now when load image first time , each image consume 0.5 1.5 mb of space of ipad. have multiple images memory consumption reaches high , application gets crashed. i showing image in image view clicking on button. can 1 suggest me how menage such memory issue application not crashed. thanks in advance. i store image apps cache & read them cache when need them. nsstring *cachesdirectorypath = [nssearchpathfordirectoriesindomains(nscachesdirectory, nsuserdomainmask, yes) objectatindex:0]; nslog(@"cachesdirectorypath: %@", cachesdirectorypath); or save heartache & use asihttprequest - http://allseeing-i.com/asihttprequest/ & bit more caching thrown in.

How to optimize Lucene.Net indexing -

i need index around 10gb of data. each of "documents" pretty small, think basic info product, 20 fields of data, few words. 1 column indexed, rest stored. i'm grabbing data text files, part pretty fast. current indexing speed 40mb per hour. i've heard other people have achieved 100x faster this. smaller files (around 20mb) indexing goes quite fast (5 minutes). however, when have loop through of data files (about 50 files totalling 10gb), time goes on growth of index seems slow down lot. ideas on how can speed indexing, or optimal indexing speed is? on side note, i've noticed api in .net port not seem contain of same methods original in java... update--here snippets of indexing c# code: first set thing up: directory = fsdirectory.getdirectory(@txtindexfolder.text, true); iwriter = new indexwriter(directory, analyzer, true); iwriter.setmaxfieldlength(25000); iwriter.setmergefactor(1000); ...

php - why can't we access values on server side in POST request? -

i tried send request jquery ajax contenttype 'text/plain'. unable access values on server side. accessing values using $_post array in php file. why happening. jquery ajax code: $.ajax({ type: "post", data: {o_pass:o_pass,n_pass:n_pass}, url: "changepass", success: function(response) { alert(response); } }); server side: $old_pass = $_post['o_pass']; $new_pass = $_post['n_pass']; because post requests should have content type of application/x-www-form-urlencoded or multipart/form-data server knows dealing with. what reason sending request plain text?

java - Single DAO & generic CRUD methods (JPA/Hibernate + Spring) -

following previous question, dao , service layers (jpa/hibernate + spring) , decided use single dao data layer (at least @ beginning) in application using jpa/hibernate, spring , wicket. use of generic crud methods proposed, i'm not sure how implement using jpa. please give me example or share link regarding this? here example interface: public interface genericdao<t, pk extends serializable> { t create(t t); t read(pk id); t update(t t); void delete(t t); } and implementation: public class genericdaojpaimpl<t, pk extends serializable> implements genericdao<t, pk> { protected class<t> entityclass; @persistencecontext protected entitymanager entitymanager; public genericdaojpaimpl() { parameterizedtype genericsuperclass = (parameterizedtype) getclass() .getgenericsuperclass(); this.entityclass = (class<t>) genericsuperclass .getactualtypearguments()[0]; ...

regex - C# Regular Expressions for Matching "ABAB", "AABB", "ABB", "AAB", "ABAC" and "ABCB" -

i'm frustrated composing regular expressions matching "abab", "aabb", "abb", "aab", "abac" , "abcb". let's take "abab" example, following string matched: abab bcbc 1212 xyxy 9090 0909 which means regex should match string 1st , 3rd characters same, , 2nd , 4th same, 1st , 2nd should not same (3rd , 4th should not same, of course). do make myself clear? thanks. peter abab pattern (\w)(\w(?<!\1))\1\2 (\w) match word character (digit, letter...) , capture match backreference 1 (\w...) match word character (digit, letter...) , capture match backreference 2 (?<!\1) assert impossible match regex matched capturing group number 1 match ending @ position ( negative lookbehind ) \1 match same text matched capturing group number 1 \2 match same text matched capturing group number 2 others patterns aabb ==> (\w)\1(\w(?<!\1))\2 abb ==> (\w)(\w(?<!\1))\2 aa...

combobox - Can I navigate into and out of a wpf combo box using arrow keys instead of tab? -

i have wpf usercontrol containing combobox , textbox in row. way move between components tab between them, able switch combobox textbox using left , right arrow keys. it not easy slapping eventhandler on keyup event. void combokeyup( object sender, keyeventargs e ) { if( e.key == key.right) { e.handled = true; textbox.focus(); } } ...because combo change value despite event being reported handled. is there way doesn't simultaneously break up/down selection of items in combo box? i have created combobox textboxes: <combobox width="100" height="25" previewkeydown="comboboxpreviewkeydown"> <combobox.items> <textbox text="item 1"/> <textbox text="item 2"/> <textbox text="item 3"/> </combobox.items> </combobox> then added handler: private void comboboxpreviewkeydown(object sender, keyeventargs e) { ...

ruby metaprogramming - getting method names and parameter info for a class -

i want class methods in object. please see following example have class "user.rb" class user def say_name end def walk(p1) end def run(p1, p2) end end and wrote following code require 'user.rb' = user.new arr = a.public_methods(all = false) above code return method name, question want method name parameters def def run(p1, p2) end i want method name ("run") , parameter names (p1, p2) or parameter count (2) can me, in advance cheers sameera user.new.method(:run).arity # => 2

android - Need help editing values in Hashmap to be loaded in a listview -

i able value of "quantity" in list when use on click using code: public void onitemclick(adapterview parent, view view, int position, long id) { object o = list.get(position); hashmap<?, ?> fullobject = (hashmap<?, ?>)o; string = (string) fullobject.get("quantity"); } now want change value of "quantity" update in list. help? lot now want change value of "quantity" fullobject.put("quantity", whatever); then update in list call notifydatasetchanged() on adapter, should reflect data change in ui.