Posts

Showing posts from January, 2013

how to wrap an existing java application into a servelet? -

assume have java file, how can wrap serverlet? there tutorial or procedure can follow? well, @ level of detail, no. what java program do? if it's gui program, you're more or less out of luck -- servlet text based. if it's text based program generates output, can hack way load application , run appropriate static main. even then, truth servlet model, based on being web application, pretty different environment -- may able reuse parts of java application have rewrite substantial bit make work.

c# - Forcing eager-loading for a navigation property -

i'm using ef code first , have navigation property called category want eager loaded in every call: public class product { ... public category category { get; set; } } to have include in every call i'll on product var results = p in db.products.include("category") select p; is there way have category property eager loaded, therefore generation sql join, in every call without having include every time? thank you you can use helper method proposed @jeroenh not solve situation example want load order ordered products , categories. ef doesn't have automatic eager loading configuration example available in linq-to-sql. must use include (either directly or helper construction).

dependency injection - Enterprise Library - Get value from ParameterValue Expression -

i trying convert enterprise library typeregistration constructorparameters collection of key/value pair (a hashtable or idictionary in general). the constructorparameters property ienumerableof(parametervalue) problem how extract values each parametervalue object. every parametervalue object contains type , expression. for ex. if parametervalue contains: "eventloggingenabled = false" can key (which eventloggingenabled) using expression.member.name can't find way value (which "false"). any thoughts? have looked @ implementation of unitycontainerconfigurator? if don't want use unity, can see how type registration stuff handled there , adapt windsor api. you don't need code raw parametervalue class , poke through lambda expressions. there 3 subclasses: constantparametervalue containerresolvedparameter containerresolvedenumerableparameter the constantparametervalue gives value directly .value property. containerresolvedparame

Comments on table, dynamic controls, C# and asp.net -

imagine table , button add new rows table. on each click button, new row inserted @ end of table. button event functioning follows: first of all, points out reference row copy. whatever controls , text inside referenced row copied datatable. since datatable cannot hold controls converting them strings , saving them that. at end, datatable stored within cache. finally, on each page_init event re-create table using data inside datatable. works fine. however, i'm curious. since have 3 5 tables in page , of them stored in different cache different datatable, , of them re-created during page-cycle events, may cause problems in future? way, please note once user leaves page cache deleted. i did not want paste whole code here since it's bit long , may alienate people reading question. can give statistics can make comments on it. the class i've written 118 lines long. during process of recreation of table, there 3 nested for/foreach loops, not long (the average lo

.net - How to count the number of code lines in a C# solution, without comments and empty lines, and other redundant stuff, etc? -

Image
by redundant stuff, mean namespaces, know necessary if there 10k of them, doesn't add valuable info table. could done using linq? no need reinvent wheel. take @ visual studio code metrics powertool 11.0 overview the code metrics powertool command line utility calculates code metrics managed code , saves them xml file. tool enables teams collect , report code metrics part of build process. code metrics calculated are: • maintainability index • cyclomatic complexity • depth of inheritance • class coupling • lines of code (loc) i know said don't have ultimate, wanted show you're missing. for else, there's sourcemonitor

c# - open the save as dialogue box -

i have file in .pdf format website. if left click on link, open adobe reader , open file. what want when left click, opens dialogue box asks want to save file. i know can right clicking , choosing save as, there way one simple left click downlaod it? im sure there sort of hack accomplish feature installed browser when adobe reader installed on machine. keeping consistent users best approach. not bother trying make left click open save dialog. users accustomed behavior , know how save pdf thier local hard disk consistency key here.

datetime - How can I store the current timestamp in SQLite as ticks? -

i have sqlite database store dates ticks. not using default iso8601 format. let's have table defined follows: create table testdate (lastmodifiedtime datetime) using sql, wish insert current date , time. if execute of below statements, end getting date , time stored string , not in ticks. insert testdate (lastmodifiedtime) values(current_timestamp) insert testdate (lastmodifiedtime) values(datetime('now')) i have looked @ sqlite documenation , not seem find option obtain current timestamp in ticks. i can of course define parameter in c# , store value system.datetime. result in datetime getting stored database in ticks. what able insert , update current timestamp directly within sql statement. how this? edit: the reason want data stored ticks in database, dates stored in same format stored ado.net data provider, , when data queried using ado.net provider correctly retrieved system.datatime .net type. this particular oddity of sqlite caused me ang

c++ - How to setup Cmake to generate header-only projects? -

the title : want setup headers-only c++ (or c) library projects, can't find clean way. after searches i've found can't setup normal library using add_library because requires compilable source file. way use add_custom_target instead, way : # headers (using search instead of explicit filenames example) file( glob_recurse xsd_headers *.hxx ) add_custom_target( libsxsd sources ${xsd_headers} ) but don't seem work here can't see sources in project generated in vs2010. don't know if it's bug or if i'm doing wrong or if there prefered way this, if have simple solution, please guest. update: cmake include library target called interface ideal header-only projects. feature in master branch. reference . using command add_custom_target propose works me (vs2010). files neatly listed within project has drawback can't define "additional include directories" custom target. instead, use following: add_library(header_only_ta

javascript - socket.io custom emit event not working -

i used npm install socket.io. server running fine not capturing custom emitted events client. the documentation on socket.io not date, example socket.io-node package not exist in npm repo git page says. so i'm wondering if functionality gone in base socket.io install or if doing wrong. my code follows: server: client.on('checkin', function (name) { ... }); client: socket.emit('checkin',name); is there more need doing? socket.io 0.7 released today (see this link ), , events used @penguinbroker in it's example code working now.

python - Convert structured array to regular NumPy array -

the answer obvious think, don't see @ moment. how can convert record array regular ndarray? suppose have following simple structured array: x = np.array([(1.0, 4.0,), (2.0, -1.0)], dtype=[('f0', '<f8'), ('f1', '<f8')]) then want convert to: array([[ 1., 4.], [ 2., -1.]]) i tried asarray , astype , didn't work. update (solved: float32 (f4) instead of float64 (f8)) ok, tried solution of robert ( x.view(np.float64).reshape(x.shape + (-1,)) ), , simple array works perfectly. array wanted convert gives strange outcome: data = np.array([ (0.014793682843446732, 0.006681123282760382, 0.0, 0.0, 0.0, 0.0008984912419691682, 0.0, 0.013475529849529266, 0.0, 0.0), (0.014793682843446732, 0.006681123282760382, 0.0, 0.0, 0.0, 0.0008984912419691682, 0.0, 0.013475529849529266, 0.0, 0.0), (0.014776384457945824, 0.006656022742390633, 0.0, 0.0, 0.0, 0.0008901208057068288, 0.0, 0.013350814580917358, 0.0, 0.0), (

regex - vbscript regular expression into an array -

with code below trying pull each url extract using regular expression array can call later along count of urls. not sure how grab of them. set objxmlhttp = createobject("microsoft.xmlhttp") call objxmlhttp.open("get", "website", false) objxmlhttp.send() strhtml = objxmlhttp.responsetext dim objregexp set objregexp = new regexp objregexp.ignorecase = true objregexp.global = true objregexp.pattern = "<a\s+href=""(http://.*?)""[^>]+>(\s*\n|.+?\s*)</a>" dim objmatch each objmatch in objregexp.execute(strhtml) objmatch.submatches(0) next set objxmlhttp = nothing i tested fake string, regexp results seemed bit wonky changed (grabbed here ). results of 1st match (you capture 2?) placed in matches array: dim objregexp set objregexp = new regexp objregexp.ignorecase = true objregexp.global = true objregexp.pattern = ""((https?:\/\/|www.)([-\w.]+)+(:\d+)?(\/([\w\/_.]*(\?\s+)?)?)?)"&

wolfram mathematica - Arbitrarily Deep Nested Pattern Matching -

is there way create mathematica pattern matches expressions heads may arbitrarily deep, i.e. f[___][___][___]... ? the suggested solution there seems no built-in construct pattern-test nested heads automatically. can achieve goal writing function would, given (sub)expression of form f[___]...[___] , efficiently determine f (which, slight abuse of terminology, may call symbolic head expression). here code: clearall[shead]; setattributes[shead, holdallcomplete]; shead[expr_] := scan[return, unevaluated[expr], {-1}, heads -> true]; here how can used (i use same set of tests @sasha): in[105]:= cases[{f[1], g[f[1]], f[1, 2, 3][1], f[1][2][3][4]}, x_ /; shead[x] === f] out[105]= {f[1], f[1, 2, 3][1], f[1][2][3][4]} the pattern syntax if prefer use syntax suggested @sasha, version clear[headpattern]; headpattern[head_] := _?(function[null, shead[#] === head, holdfirst]); in[108]:= cases[{f[1], g[f[1]], f[1, 2, 3][1], f[1][2][3][4]}, headpattern[f]] out[108

c# - Improving azure blob storage querying speed -

we have blob storage thousands of files under same azure container. our file naming convention this: storagename\team\subteam\filename i'm writing tool displays files each particular subteam. code gets list of blobs container , each of tries match correct team\subteam (see below sample code). this works extremely slow (because need go through files see if match particular subteam). there way improve speed of query? can think of optimizations such "find first file matches team looking , keep track when find different team quit early" assume bloblist sorted , wouldn't fix worst case scenario. unfortunately splitting files under different containers not option @ time. here sample code: ienumerable<ilistblobitem> blobs = blobcontainer.listblobs( new blobrequestoptions() { useflatbloblisting = true, bloblistingdetails = bloblistingdetails.metadata }).oftype<cloudblob>(); foreach (var blob in blobs) { var cloudy =

iphone - how to show large dataset on UITableView -

i have array of posts in size 100000 or more. want show in alphabetical order (in user can navigate alphabet easily), best way this? doing tableview 100000 entries think won't idea.. looking suggestions this. i'm not sure there way present 100,000 records on iphone or ipad. guess question ask user need access volume of data @ 1 time on types of devices? if not, think resolve either filters (to limit results in paginated grid) or decent search algorithm. cheers!

sql - Backup database and remove sensitive data -

i'm looking @ backup routine allows our production database backed sensitive data stripped out of columns within database exported our testing server. the routine should require least human intervention , simple customisable sql script without taking production database offline. database server sql server 2008. i've run similar requirements before, , sure solution know of use copy of production database. can mask/delete data on copy , run backups there. yes it's ugly , waste of resources, date haven't found solid alternative particular problem. as copy method, have options: replication scheduled db copy backup/restore production so while admit solution pretty cringe-worthy, can automated , serve purposes. if can find productive uses database copy don't require deleted information (e.g. reports, testing, development) can less-than-terrible solution. can nice security boon have out-of-date version of production database sensitive data remov

sql - Oracle : Alternative of REGEXP_LIKE function in Oracle 8i -

i have sql uses regexp_like function in clause, need equivalent of function run in oracle 8i. the regex this: where regexp_like(parm, '^[pmf][[:digit:]]+[_].*') thanks in advance. you try where substr(parm,1,1) in ('p','m','f') , substr(parm,2,1) between '0' , '9' , substr(ltrim(substr(parm,2),'0123456789'),1,1) = '_' first character p, m or f. second character digit second character onwards, stripping digits left, should start underscore ps. please shoot 8i database. not 8i out of support, 9i , 10g out of support (or @ least in 'degraded, please stop using them' level of support).

iphone - memory leak - application exited with signal 9 -

i have application dealing many data structures, uiimageviews, videos, creating bit map context , on. every time application crashing on continuous usage long time. application crashing memory warning --> application exited abnormally signal 9. may reason. signal 9 means. i think due memory issue. app using lot of memory due app killed..

c# - How to change HttpRuntime settings (eg WaitChangeNotification) at runtime? -

it easy set settings in web.config typing them xml file. however, set settings @ runtime. specifically want set system.web/httpruntime/waitchangenotification setting. i've tried this, throws error says configuration readonly. var section = httpcontext.current.getsection("system.web/httpruntime") system.web.configuration.httpruntimesection; section.waitchangenotification = 6; it's not idea, entirely possible using reflection. here code example of injecting soap extension web services section of app config: // turn read field non-readonly webservicessection wss = webservicessection.current; soapextensiontypeelement e = new soapextensiontypeelement(typeof (traceextension), 1, prioritygroup.high); fieldinfo readonlyfield = typeof(system.configuration.configurationelementcollection).getfield("breadonly", bindingflags.nonpublic | bindingflags.instance); readonlyfield.setvalue(wss.soapextensiontypes, false); // bind web services section of

Request for member 'pData' with BOOL value TRUE is not a structure or union-Objective C -

i not use pdata[4096] pass other function main. data.m ------ @implementation data static int msgid; static char pdata[4096]="\0"; + (void)initialize { //some initialisations msgid =123; } -(void)swapendian:(uint8_t*)pdata withboolvalue:(bool)bisalreadylittleendian { nslog("%s %s",pdata,bisalreadylittleendian); } @end main.m ------- [dat swapendian:dat.pdata withboolvalue:true]; i getting pdata undeclared. pdata declared static inside data implementation tried dat.pdata pass main.but when getting request member 'pdata' bool value true not structure or union. it difficult determine code supposed do, here how create objective-c object holds integer identifier , 4096-character array. please note sort of thing discouraged. unless have specific reason using int , char[] , identifier should nsinteger , data should nsdata or nsstring object. i have used of "standard" naming conventions. if writing cocoa code, helps drink

html - Is it a bad practice to have nested forms? -

possible duplicate: can nest html forms? is bad practice have this?: <form method="post"> <form method="post"> </form> </form> yes. so. , won't work properly. restructure page make sure doesn't have nested..

How do I check for multiple exceptions in Python? -

dnasequence = "laksjfklsajdfklsajfklasjfklsad" while true: lmerlength = input("please enter length of l-mers of universal array :") try: if len(dnasequence) >= lmerlength > 0: break except syntaxerror: pass #this not working. how check multiple exceptions in python? except nameerror: pass print "error: please check input. entered invalid input." here how check multiple exceptions. try: .............. except (syntaxerror, nameerror, ...): .............. finally: .............

visual c++ - Getting LNK2001 Unresolved external smymbol __forceCRTManifestCUR error -

i using vc++ 6.0 ide building , compiling application. i getting error while compilation. error:- lnk2001 unresolved external smymbol __forcecrtmanifestcur fatal error lnk 1120: 1 unresolved external. --------version , configuration-------- os - windows server 2008 vc++ - 6.0 installed on pc --------other installation are------ visual studio 2008 microsoft sdk 5.0 are c:\program files\microsoft visual studio\vc98\include and c:\program files\microsoft visual studio 9.0\vc\include conflicting.. please in issue..

About Android button event -

hi new in android application development.i practicing android development while.here trying do: in screen there 2 spinner named "to" , "from" , 2 edit text button named "amount" , "result".i want following: when clear button clicked reset “to” , “from” default values , clear “amount” , “result”. can have idea?it helpful if code. thanks. this crude code, haven't tested, wrote on top of head, there can errors , assumed layout ids. need figure out. public class spinnerexample extends activity { private string array_spinner[]; private spinner tospinner; private spinner fromspinner; private button btnclear; private edittext etamount; private edittext etresult; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); array_spinner=new string[3]; array_spinner[0]="1"; array_spinner[1]="2"; array_spinner[2]=&

Extjs scrolling a panel to a position -

hi have panel , want scroll particular postiton in panel how do it var tabs= new ext.panel({ id:id, title:text, autoscroll:true, iconcls:'windowicon', closable:true, closeaction:'hide' }); set scrolltop property of panel's body number of pixels want scroll down: // scroll body down 100 pixels. tabs.body.dom.scrolltop = 100;

c++ - c#/wpf OpenMP inside external dll -

i have c++ lib, 'glue' lib in managed c++ , c#/wpf app importing 'glue' lib. works fine till add some #pragma omp parallel when compile c++ lib / glue lib , c#/wpf app fine - no warnings/errors. when trie launch c# app crashes - doesnt crashes when executing parallel code - crashes during loading of app - says: a first chance exception of type 'system.windows.markup.xamlparseexception' occurred in presentationframework.dll additional information: nie można utworzyć wystąpienia „window1” zdefiniowanego w zestawie „fastnn-speedtest, version=1.0.0.0, culture=neutral, publickeytoken=null”. obiekt docelowy wywołania zgłosił wyjątek. błąd w pliku znaczników „fastnn-speedtest;component/window1.xaml”. i know it's in polish c# app can't load dll uses openmp code - how can make work? of course in c++ project switched on "enable openmp" .net doesn’t care dll does—one using openmp shouldn’t different. have required vcomp*

.net - Is it possible to set one side of Margin or Padding as to not override the default style? -

i've set default styles basic elements in wpf act default styles application, allows controls such buttons carry similar , feel without having adjust manually when defined, means needs changed once. a snippet of resource dictionary looks follows: <resourcedictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <style targettype="button"> <setter property="margin" value="4"/> <setter property="minwidth" value="75"/> <setter property="padding" value="10,2"/> </style> </resourcedictionary> notice here i'm setting margin 4 sides. great provides gap between buttons without interface needing explicitly define it. want know how can single button, remove gap on 1 side without needing define "4" other sides allow butt ag

Drupal 7 Index pdf files in search -

does know of way include pdf documents in search drupal 7? i can't find achieve this. the apache solr attachments module this, has development (not stable) release drupal 7.

sql - Convert text into number in MySQL query -

is possible convert text number within mysql query? have column identifier consists name , number in format of "name-number". column has varchar type. want sort rows according number (rows same name) column sorted according character order, i.e. name-1 name-11 name-12 name-2 if cut of number, can convert 'varchar' number 'real' number , use sort rows? obtained following order. name-1 name-2 name-11 name-12 i cannot represent number separate column. edited 2011-05-11 9:32 i have found following solution ... order column * 1 . if name not contain numbers save use solution? this should work: select field,convert(substring_index(field,'-',-1),unsigned integer) num table order num;

c# - LINQ to SQL running direct SQL for a scalar value -

i trying execute following raw sql linq has no proper support datediff : var str = @"select isnull(avg(datediff(day, addeddate, presentdate)), 0) days dummytable"; using linq sql, i'm trying output of above statement using: var numberofdays = math.round(db.executequery<double>(str).firstordefault()); this give me error: specified cast not valid. what doing wrong? thanks in advance! your code must change to: var numberofdays = db.executequery<int>(str).firstordefault()); you think why? tell you: return type of datediff in int.so return type of avg int. return type of isnull int too. references : datediff avg isnull try convert type of second expression first expression.

javascript - Strange behavior of select/dropdown's onchange() JS event when using 'Next' on Mobile Safari Dropdown list item select box -

this hard 1 articulate , new mobile web development please bear me: on webpage, have 3 nested dropdown lists (area, town, street). nested in, each dropdown's items modified when selection in dropdown above changes. e.g selecting area changes town , street lists , selecting town changes street list. i use xmlhttprequests in onchange() javascript event of dropdowns fetch , populate other downdowns. works fine on android , desktop browsers. on mobile safari , when drowdown touched, list shown user can select items. in addition selection box has "previous/next/autofill/done" buttons navigate other form elements. so user touches first dropdown, selects value , presses next button. causes 2 problems: first , on action first dropdown's oncange() event not triggered reliably! fires not. if after selecting area, user touches somewhere else on webpage or presses "done" button onchange() fired , towns , streets populated normally. second , ele

sql - Compare two rows in AND condition -

just having problem using , operator in sql returns 0 result set. i have following table structure: idcompany, cloudid, cloudkey, idsearchfield, type, uservalue now execute following statement: select * filter_view (idsearchfield = 4 , compareresearch(uservalue,200) = true) , (idsearchfield = 6 , compareresearch(uservalue,1) = true) compareresearch ist function casts uservalue , compares other value , returns true if value equal or greater. uservalue stored string (that's decision made 6 years ago) okay, 0 resultset because both criterias in braces () , combined , 1 row can have 1 idsearchfield , therefor 1 of criterias won't match. how around this? need , comparison, won't work out way. i hope problem obvious :-) if you've recognised both conditions can't ever both true, in way can , comparison correct one? select * filter_view (idsearchfield = 4 , compareresearch(uservalue,200) = true) or (idsearchfield = 6 , comp

android - Stopping event listener of tableviewrow in Titanium -

when user click on tableviewrow, alert box 'row' occur. , inside tableviewrow, contains view contains image view. alert box 'label' popout when user click on image. problem when user click on image, not alert box 'label' popup, alert box 'row' too. how can avoid alert box 'row' popping out when user click on image? alert box 'row' appear when user click on tableviewrow other image. thanks.. var row = titanium.ui.createtableviewrow({ classname:'rowclass', }); var u_image = titanium.ui.createimageview({ image: 'image.jpg', top:10, left:4, height:36, width:36, }); row.add(u_image); regdata.push(row); u_image.addeventlistener('click', function(e){ alert('label'); }); row.addeventlistener('click', function(e){ alert('row'); }); ti 1.6, android 2.2 create image view id var u_image = titanium.ui.createimageview({ image: 'image.jpg', id: &qu

plot - How can I display numbers with higher precision in a MATLAB data cursor? -

Image
i have problem precision loss. imported set of values csv file matlab 7 using following code: function importfile(filetoread1) %#importfile(filetoread1) %# imports data specified file %# filetoread1: file read delimiter = ','; headerlines = 0; %# import file rawdata1 = importdata(filetoread1, delimiter, headerlines); %# simple files (such csv or jpeg files), importdata might %# return simple array. if so, generate structure output %# matches import wizard. [~,name] = fileparts(filetoread1); newdata1.(genvarname(name)) = rawdata1; %# create new variables in base workspace fields. vars = fieldnames(newdata1); = 1:length(vars) assignin('base', vars{i}, newdata1.(vars{i})); end this basic script takes specified file: > 14,-0.15893555 > 15,-0.24221802 > 16,0.18478394 and converts second column to: 14 -0,158935550000000 15 -0,242218020000000 16 0,184783940000000 however, if select point data cursor displays 3 or 4 digits of precision:

How to refuse the repetition of viewer's number counter. (in Rails) -

i want count number of post viewer in rails community project,of course want refuse repetition.but can't find efficient way.what think make table record every viewer's id of every post.i found stack overflow's viewer's counter great,but don't know how work. i need help,thank you.

shell - problem in scripting -

when executing on command line: awk 'begin{ofs=fs=","}$3~/^353/{print}' axem10_20110510100219_59.dat_353 >log it executes vey nicely without taking time , instantly gives me output file. but when including in shell script : #!/usr/bin/ksh in *.dat_353 awk 'begin{ofs=fs=","}$3~/^353/{print}' ${i} > ${i}_changed >/dev/null done exit the script generating 0 byte files. may know problem here? remove >/dev/null because stdout being redirected to.

image - PHP imagecopyresampled problem with ratio, resizing and cropping -

okey writing image upload want force images 795x440px. can rezised have keep aspect ratio can cropped also. the new images comes out in right size, cropped image original file has wrong ratio, tried diffrent ways can't right. the image testing right now, original file http://image.bayimg.com/jaiflaada.jpg the result cropping http://image.bayimg.com/jaifmaada.jpg how right, image gets best size , crops rest? list($width, $height) = getimagesize($save_dir); $prop = (795 / $width); $height = floor($height * $prop); $new_image = imagecreatetruecolor(795, 440); $bgcolor = imagecolorallocate($new_image, 255,255,255) or die("couldn't allocate color"); imagefill($new_image , 0,0 , $bgcolor) or die("couldnt fill color"); imagecopyresampled($new_image,$source_image,0,0,0,0,795,440,795,$height); imagejpeg($new_image,$new_directory,100); i that: public function cropimage($nw, $nh, $source, $stype, $dest) { list($w, $h) = getimage

How to know if keyboard (dis)appears in Android? -

i have edittext , want give more lines when keyboard appears. looking "onkeyboardappearslistener" can't find it. think must exist, perhaps in different way... you have @override onconfigurationchanged able handle runtime changes: @override public void onconfigurationchanged(configuration newconfig) { super.onconfigurationchanged(newconfig); // checks whether hardware or on-screen keyboard available if (newconfig.keyboardhidden == configuration.keyboardhidden_no) { toast.maketext(this, "keyboard visible", toast.length_short).show(); } else if (newconfig.keyboardhidden == configuration.keyboardhidden_yes) { toast.maketext(this, "keyboard hidden", toast.length_short).show(); } } example taken here . take here keyboard related (among others) fields might want use. edit (rivierakid): changed take account of hard or on-screen keyboard.

python - numpy: boolean indexing and memory usage -

consider following numpy code: a[start:end] = b[mask] here: a , b 2d arrays same number of columns; start , end scalars; mask 1d boolean array; (end - start) == sum(mask) . in principle, above operation can carried out using o(1) temporary storage, copying elements of b directly a . is happens in practice, or numpy construct temporary array b[mask] ? if latter, there way avoid rewriting statement? using boolean arrays index fancy indexing, numpy needs make copy. write cython extension deal it, if getting memory problems.

Image Manipulation in Android app -

can me on one? want image manipulation in android app brightness , contrast. ideas ? i posted example of how greyscale image in android . code used starting point basic image manipulation. suggest check out colormatrix class

php - Send Push notification when product was approved on appstore only -

we have application, sells "downloadable" products. scenario is: add product our backend (powered on php , symfony) add product apple store , wait when approved sell it. it works charm. but i'd implement push notification, when new product added our store. problem don't know if produc approved , available on apple side. may confuse user, when sees notification 1 new product, unavailable , user doesn't see on application. is there way approved , available product list apple? hey, try parsing emails, app store when new product approved. make notification date , won't miss user

php - Adding a target to link tags, as long as the href attribute doesn't contain a certain word -

i created function: <?php function target_links( $html ) { $pattern = "/<(a)([^>]+)>/i"; $replacement = "<\\1 target=\"_blank\"\\2>"; $new_str = preg_replace($pattern,$replacement,str_replace('target="_blank"','',$html)); return $new_str; } ?> the goal add target="_blank" link tags. now problem need skip link tags href attribute contains specific word, can't seem find proper combination. can guys me? i'm not sure "not failing because of broken html", if can domdocument accept html, try like: <?php $dom = new domdocument(); $dom->loadhtml('<html> <a href="...protected...">some link</a> <a href="...change me...">some link</a> </html>'); $xpath = new domxpath($dom); foreach ($xpath->query('//a[not(contains(@href, "prote

applet - Problems with deployment, advice needed for a web-based java application -

i have developed command-line (read: no gui) java application crunches through numbers based on given dataset , series of parameters; , spits out series of html files resultant reports. these reports hold large amount of data in tables, in order give users easy , quick overview of results, utilized jung2 library , created nice graph. here's gets interesting; since graph interactive should deployed after application has run , files generated, whenever user wants view reports. decided go applet based deployment, not happy current setup due following reasons: i want make software simple use possible (my users won't tech-savvy, , tech-intimidated in cases). distribute 1 jar only, forced me put applet else needs in package in same jar main application. the applet , main application need communicate results, create xml-based report used hold information. long files on local machine , not moved around works fine. unfortunately need files moved around. user should able take &

iphone - Retrieve the url of an image taken on the fly and saved in the gallery, how? -

i allow user choose image gallery or take photo camera. save image path in both cases can use display image in second moment. when user select image gallery, can use - (void)imagepickercontroller:(uiimagepickercontroller *)picker didfinishpickingmediawithinfo:(nsdictionary *)info { if([[info valueforkey:@"uiimagepickercontrollermediatype"] isequaltostring:@"public.image"]) { nsurl *imageurl = [info valueforkey:@"uiimagepickercontrollerreferenceurl"]; } } instead, if user takes photo on fly, save in photo roll with: uiimage *image = [info objectforkey:@"uiimagepickercontrolleroriginalimage"]; uiimagewritetosavedphotosalbum(image, self, @selector(image:didfinishsavingwitherror:contextinfo:), nil); after saving it, retrieve corresponding nsurl user had selected it. how do? edit my problem isn't image chosen gallery. succeed in retrieving url using uiimagepickercontrollerreferenceurl path. problem when

actionscript - How to create Flex Wobble Effect for a component (VBox/HBox etc...) -

can tell me how can create wobbling effect using flex 3? need effect show in ubuntu when see alert or move folder. thank you. not sure if there built in flex handle "wobble" effect specifically, can combine flex move , bounce effects create kind of "wobble": <?xml version="1.0"?> <fx:declarations> <s:bounce id="bounceeasing"/> <s:elastic id="elasticeasing"/> <s:move id="moveright" target="{myimage}" xby="500" duration="2000" easer="{elasticeasing}"/> <s:move id="moveleft" target="{myimage}" xby="-500" duration="2000" easer="{bounceeasing}"/> </fx:declarations> <s:image id="myimage" source="@embed(source='assets/logo.jpg')"/> <s:button label="move r

java - Multidimensional Arrays to store multiple data types -

i know php little. , java little. i creating small application search text in text area , store result in array. the array in php this. array( "searchedtext" => "the text searched", "positionsfound" => array(12,25,26,......), "frequencies" => 23 //this total words found divided total words ); but, java not support array multiple data types. in above array, second element "positionfound" of variable length. later on need iterate through array , create file including above mentioned elements. please guide me java support objects. have define class like class mydata { string searchedtext; set<integer> positionsfound; int frequencies; } list<mydata> mydatalist = new arraylist<mydata>(); // or mydata[] mydataarray = new mydata[number]; and can use structure hold data. there other methods helpful such constructors , tostring() , suggest use ide generate those.

How to discover OpenID IDP, then authenticate with OpenID Provider in PHP -

i've been looking @ implementing openid authentication 1 of websites , want find best possible solution make easy possible users sign / in. through long searches on google found few sites have covered in quite bit of detail; usability research on federated login written google, feel pretty trustworthy design patterns best use scenario. now in coming implement have found little php support logins done in manner; user has type in email address , of openid details found automagically. should compatible google apps addresses. google provided link great example of in action http://www.puffypoodles.com/lso2 although source code available download, it's written in java, i'm far familiar with! so wondering if had found php implementation functioned in manner. php-openid seems bloated, lightopenid looks great, doesn't support functionality. thanks i'd point out lightopenid comes example provider script might use base.

java - How to force instantiation of static fields -

i quite surprised of output of following code: country class public class country { private static map<string, country> countries = new hashmap<string, country>(); private final string name; @suppresswarnings("leakingthisinconstructor") protected country(string name) { this.name = name; register(this); } /** country name */ public static country getcountry(string name) { return countries.get(name); } /** register country map */ public static void register(country country) { countries.put(country.name, country); } @override public string tostring() { return name; } /** countries in europe */ public static class europecountry extends country { public static final europecountry spain = new europecountry("spain"); public static final europecountry france = new europecountry("france"); protected europecount

c++ - Delete raw pointer argument to boost::bind -

lets have heap allocated a* , want pass argument boost::bind . boost::bind saved later processing in stl container of boost::functions 's. i want ensure a* destroyed @ destruction of stl container. to demostrate: a* pa = new a(); // time later container.push_back(boost::bind(&someclass::handlea, this, pa); // time later container destroyed => pa destroyed how can done? edit maybe want not realistic. i have raw pointer , function receives raw pointer. call delayed means of boost::bind . @ point want automatic memory management in case boost::bind want executed. i'm lazy, want use "ready" smart-pointer solution. std::auto_ptr looks candidate, ... auto_ptr<a> pautoa(pa); container.push_back(boost::bind(&someclass::handlea, this, pautoa); doesn't compile (see here ) auto_ptr<a> pautoa(pa); container.push_back(boost::bind(&someclass::handlea, this, boost::ref(pautoa)); pautoa destroyed, deleting underlying pa.

onclick - Reload previous visited page in javascript -

i have web page whithin have display image, when clicked on image, image poped-in. , then, there close button after viewing photo. now, add the event onclick 1 function allow me refresh/reload page. have sequence ( close popin ==> page ==> reload page) am not in js, in javascript. there several ways can this, here more info. a call window.location.reload() job.

Silverlight open uri link being blocked by browser -

the problem simple annoying. have button , click event opens link htmlpage.window.navigate(uri, "_blank"); but keeps being blocked browser. searched lot. seems using method no 1 mentioned new tab/windows being blocked. should do? update problem solved. seems navigate outside web pages, hyperlinkbutton should used. not blocked browser. "to enable user navigation other web pages, can use hyperlinkbutton control , set navigateuri property external resource , set targetname property open new browser window." --- msdn, silverlight - external navigation <hyperlinkbutton navigateuri="http://www.microsoft.com" content="go microsoft" targetname="_blank" /> ps. htmlpage.popupwindow blocked browser. seems me htmlpage.window.navigate , htmlpage.popupwindow useless without user manually disable block. have considered system.windows.browser.htmlpage.popupwindow(uri, "_blank", null) in silverlight 3 , 4?

javascript - Not interpret html in iframe but get the information from the html -

in order reduce time of executing, decide not show table in iframe client cant see it. have copy contents of table update table in main page (which can seen client). the principle that, the iframe shouldn't interpret html, through function written javascript, copy updated table main page. we've thought commenting html out in iframe, it'll complicated not element document.getelementbyid(id) . , we'll have parser html. similar things? is document you're requesting on same domain "main page"? if so, can request second document via ajax , use regular expression extract element it. done without rendering additional content dom. once have table element extracted ajax response, can add main page dom.

Merge with kiln (mercurial ) -

what best way merge in kiln repository. we have 3 repositories 1.7.5 1.7.6 main-dev so fix bug in older version (1.7.5). fix merge version 1.7.6, repository , in our main-dev repository.. how mercurial (kiln) kiln doesn't provide functionality allows merge via kiln's web ui. need ordinary mercurial merge locally , push merged changsets kiln. there plenty of posts how merge changesets in mercurial, including ones on kiln stackexchange: kiln branch , merge how-to hginit - merging mercurial wiki - merge mercurial best practice on dev + stable branch merge

c# - Using WebBrowser Control - Hiding all the HTMLElements apart from one Div -

i'm using webbrowser control load page. want hide html elements in page apart particular div (and children). i've id of particular div. how can hide other elements? edit i'm creating webbrowser instance dynamically. want navigate url , take screen shot of page partially (a particular div). want hide other elements in page , take screenshot. i used jquery hide elements apart div , children. referred this post script , called script in webbrowser using invokescript(). worked perfectly.

cocoa touch - Text field text drawn at bottom instead of centre -

i'm working on iphone app , i've problem: text in text field drawn @ bottom. can 1 me display centered? use following instruction: textfield.contentverticalalignment = uicontrolcontentverticalalignmentcenter;

android - How to clear previous activity stack and Exit Application on back button? -

friends, i have 3 activities a,b,c a home screen. activities launched follow a->b->c if come home screen using backbutton want clear activity stack/previous activities history , should exit application. any 1 guide me how achieve this? very simple: use intent.setflags(intent.flag_activity_clear_top); on intent used start activity a.

how to change, in CSS files, src attribute for images dynamically at deploy? (ASP.NET Web Forms) -

i creating asp.net web forms website , need optimze loading time of website. 1 of methods make images load dfferent servers. for images exposed through aspx pages or user controls use utility transforms relative link of resourses absolut one, linking preferred server resource. i need able same thing images loaded css files, meaning each image going loaded css file need change src attribute prefered one. know tool this, or solution can apply problem ??? there couple of options: transform css files @ build time , serve them static files make css files dynamic , let asp.net populate paths images based on existing setting there number of ways of doing either of above. here links might give ideas: making dynamic css content asp.net less- dynamic stylesheet language or use asp.net theming support have 2 themes, 1 development , 1 production. though i'm not sure that's great option.

SEO friendly url gives a "A potentially dangerous Request.Path" on IIS -

i'm creating seo friendly url has product names, might have not-so-url friendly characters, eg: www.foo.com/some-friend/product-name-bla-%numbers-maybe/1234567 i'm interested in last id number, iis redirects fault page on of of urls. i not wish disable request.path check. my question - how sanitize urls not bother iis (preferably in c#) ? asp.net has httputility lets escape illegal characters in url or html string. httputility.urlencode(yourstring); even though going need id @ end of url data database, idea check if seo friendly part of url identical original url. if whatever reason has changed should 301 permanent redirect original in order avoid creating duplicate content. also setting canonical meta tag prevent issue.

svn - Weird delete on merge in Subversion -

i have subversion repository trunk , branch. when try merge trunk branch (no matter if use tortoisesvn or commandline svn), directory , included file become marked deletion. in merge log there no incoming delete file. if run svn status now, shows me like d + path/to/directory d + path/to/directory/file edit: Álvaro g. vicario pointed out, + indicates "history scheduled commit" -- mean in situation? now scared, (because discovered accident) might have had data loss on similar merge in past without noticing. can give me hint on might have happened here? if unsure, recommend start again , tortoisesvn. assuming didn't commit merge yet, find branch working copy and: right click on working copy root , revert . right click on working copy root , check modifications . remove unversioned items if any. right click... , merge . pick "merge range of revisions" , next . pick trunk @ "url merge from". hit show log , highlight revis

Dealing with XML in PHP -

i'm working project has me working xml lot. have take xml response , decrypt each text node , various tasks data. problem i'm having taking response , processing each text node. using xmltoarray library, , worked fine change xml array , loop through array , decrypt values. of xml response i'm dealing have repeated tags , xmltoarray library return last values. is there way can take xml response , process text nodes , putting values array has similar structure response? thanks in advance. i use simplexml . here's small example of using it. loads , parses xml http://www.w3schools.com/xml/plant_catalog.xml , outputs values of "common" , "price" tags of each "plant" tag. $xml = simplexml_load_file('http://www.w3schools.com/xml/plant_catalog.xml'); foreach ( $xml->plant $plantnode ) { echo $plantnode->common, ' - ', $plantnode->price, "\n"; } if have problems adapting needs, give exam

Simple question about iterating 2 arrays in objective-c -

i'm iterating nsarray in objective-c with: for (id object in array1) { ... } i have array2, , need access same index of current array1. should use statement ? thanks you have several options: use c-style loop dan suggested keep track of current index in separate variable in fast-enumeration approach: int index = 0; (id object in array1) { id object2 = [array2 objectatindex:index]; ... ++index; } use enumerateobjectsusingblock: method (os 4.0+): [array1 enumerateobjectsusingblock:^(id obj, nsuinteger idx, bool *stop){ id obj2 = [array2 objectatindex:idx]; ... }];

Best way to initialize (empty) array in PHP -

in other languages (as3 example), has been noted initializing new array faster if done var foo = [] rather var foo = new array() reasons of object creation , instantiation. wonder whether there equivalences in php? class foo { private $arr = array(); // there / better way? } in ecmascript implementations (for instance, actionscript or javascript), array() constructor function , [] part of array literal grammar. both optimized , executed in different ways, literal grammar not being dogged overhead of calling function. php, on other hand, has language constructs may functions aren't treated such. even php 5.4, supports [] alternative, there no difference in overhead because, far compiler/parser concerned, synonymous. // before 5.4, write $array = array( "foo" => "bar", "bar" => "foo", ); // of php 5.4, following synonymous above $array = [ "foo" => "bar", "bar"

django - both forms in formset need to be selected -

i have formset have 2 forms. forms: class presclinicform(forms.form): _names = list(presclinic.objects.values_list('pres_clinic_id', 'pres_clinic_name')) _names.append(["new", u'nova entrada']) pres_name = forms.choicefield(widget=radioselect(), choices=_names, label= "", required=true) presclinicformset = formset_factory(presclinicform, extra=2) views: if request.method == 'post': formset1 = presclinicformset(request.post, request.files, prefix='pres_clinic') if formset1.is_valid(): choice = formset1.cleaned_data return render_to_response('template.html', {'options': options}) template: <form method="post" action=""> <div> {{ formset1.management_form}} {% form in formset1.forms %} {{ form }} {% endfor %} <input type="submit" value="guardar" /> &

unity3d - Attachment points -

i use models designed in blender, , need add attachment points special effects. mark point in hand of model (modified hand animations of course) can apply glow when needed. know how apply glow 3d point, need way point. how do that? there's couple ways sort of thing, approach best because it's easy tech artists interface (alls needs special name on object). can have top level character script scan children , objects naming convention specify. foreach(transform child in gameobject.getcomponentsinchildren<transform>()) { if( child.name == "attachmentpointorwhatever" ) { myeffectsobject.transform.parent = child; myeffectsobject.transform.localposition = vector3.zero; } } this works because unity update bones' positions based on imported animation, effects object follow along point imported animation. as far creating animation, i'm coming maya , 3ds max, idea should same blender: add bones attachment points , make

visual studio - How to close executereader in asp.net? -

i using more 1 repeater on same page. when use execute reader 2nd repeater gives exception there execute reader running.. close it. put executereader(commandbehavior.closeconnection) give error command behaviour doesn't exists... idea issue? you need explicitly close datareader if specify commandbehavior , not you. http://msdn.microsoft.com/en-us/library/y6wy5a0f.aspx

C++ Template friend odd behavior -

i'm seeing can't explain in following code. under vs6, vs9, , gcc t2::foo2() gives error: 'bar' : cannot access protected member declared in class 'c1'. if remove c1::bar(), compiles , runs correctly, though t2 still accessing protected c1b:bar(), think same problem. note, in t2::foo2() cast 'pt1' 't1*' , fine, still not explain why c1b::bar() allowed, c1::bar() not. template<class s> class t2; template<class t> class t1 { //template<class t> friend class t2; --> doesn't compile under vs6 friend class t2<t>; protected: virtual void bar() { printf("t1\n"); } }; template<class s> class t2 { public: void foo1(t1<s> *pt1) { pt1->bar(); } // --> ok, makes sense, works either way void foo2(s *pt1) { pt1->bar(); } // --> fails compile if c1::bar() defined, works c1b::foo() ??? }; class c1 : public t1<c1> { protected:

osx - libtiff for C using Snow Leopard. Storage size of TIFF isn't know -

i have built , installed tiff-4.0.0beta6 on mac computer running snow leopard. followed tutorial @ http://www.kyngchaos.com/macosx/build/libtiff . install went fine there issues tiff data type. for exmaple, when compile following simple code: #include "tiffio.h" main() { tiff* tif = tiffopen("foo.tif", "r"); tiffclose(tif); } i error message: hlrg-labs-imac:metrics ben$ gcc main.c undefined symbols: "_tiffopen", referenced from: _main in cciewewr.o "_tiffclose", referenced from: _main in cciewewr.o ld: symbol(s) not found collect2: ld returned 1 exit status when compile code: #include "tiffio.h" main() { tiff tif; } i compilation error: hlrg-labs-imac:metrics ben$ gcc main.c main.c: in function ‘main’: main.c:5: error: storage size of ‘tif’ isn’t known any suggestions on appreciated. thanks. when compile need include -ltiff switch. example: gcc main.c -ltiff -o m