Posts

Showing posts from June, 2011

How can I draw image with rounded corners in Cairo/Gtk? -

how can draw image rounded corners in cairo/gtk? in language. ok, it's realy simple. here vala code: private void draw_rounded_path(context ctx, double x, double y, double width, double height, double radius) { double degrees = m_pi / 180.0; ctx.new_sub_path(); ctx.arc(x + width - radius, y + radius, radius, -90 * degrees, 0 * degrees); ctx.arc(x + width - radius, y + height - radius, radius, 0 * degrees, 90 * degrees); ctx.arc(x + radius, y + height - radius, radius, 90 * degrees, 180 * degrees); ctx.arc(x + radius, y + radius, radius, 180 * degrees, 270 * degrees); ctx.close_path(); } and example of expose_event: public override bool expose_event(gdk.eventexpose event) { //base.expose_event(event); context ctx = gdk.cairo_create(this.window); draw_rounded_path(ctx, allocation.x, allocation.y, allocation.width, allocation.height, 5); if(pixbuf != null) { gdk.cairo_set_source_pixbuf(ctx, pixbuf, ...

msbuild - devenv VS aspnet_compiler -

if use aspnet_compiler publish asp.net mvc web site, same tasks devenv do? or pre-compiling minimize startup delay? i.e. requirnment able compile , publish asp.net web site. in case, should use devenv first build web site, , use aspnet_compiler pre-compile , copy files on (publish)? or if use aspnet_compiler building (compiling) of source , reference projects relevent dlls? your responses highly appreciated. lot. i don't know if ther such thing aspnet_compiler. have @ part of 'visual c# -> asp.net web application' project file: <import project="$(msbuildbinpath)\microsoft.csharp.targets" /> <import project="$(msbuildextensionspath32)\microsoft\visualstudio\v10.\webapplications\microsoft.webapplication.targets" /> first line standard c# target. second, more interesting asp.net specyfic. if content find definition of of publish target , looking for. for building , publishing project can use (or publish if there p...

php - mysql sorting single field in multi orders -

hi trying sort field multiple orders example here table 1st rule sort status. in following order: active, inactive, merged, promo a, promo b, promo c, promo d, defunct once sorted within each of these categories 2nd rule in following order: traditional, native, salvation, amm, nav 3rd rule sort state within these categories alphabetical a-z if cannot in mysql can in php? sort function i need idea or trick how can -- ---------------------------- -- table structure `users` -- ---------------------------- drop table if exists `users`; create table `users` ( `user_id` int(11) not null auto_increment, `name` varchar(255) default null, `status` varchar(255) default null, `category` varchar(255) default null, `state` varchar(255) default null, primary key (`user_id`) ) engine=myisam auto_increment=11 default charset=utf8; -- ---------------------------- -- records of users -- ---------------------------- insert users values ('1', 'testing', '...

vb.net - Error with code? -

hi can tell me why following dose not work: (p.s dont want file append upon clicking abutton upon clicking checkbox. private sub checkbox1_checkedchanged(byval sender system.object, byval e system.eventargs) handles checkbox1.checkedchanged dim file_name string = "c:\rxf\log.txt" 'adding items autocad 2006... if checkbox1.checkstate = checkstate.checked dim objwriter new system.io.streamwriter(file_name, true) objwriter.writeline("module: 4fnv-67-5h") objwriter.close() end if end sub end class not reproducible, exact code posted. works fine me, creating text file in specified location if 1 not exist , appending specified text end of file. the thing suggest wrapping streamwriter object in using statement ensure dispose method gets called, if exception thrown (which more when you're doing disk i/o). so, existing code change to: private sub checkbox1_checkedchanged(byval sender system.obje...

c++ - Regex and Boost. Not working on a simple regex -

below following code #include <iostream> #include <stdlib.h> #include <boost/regex.hpp> #include <string> using namespace std; using namespace boost; int main() { std::string s = "hello name bob"; boost::regex re("name"); boost::cmatch matches; try{ // if (boost::regex_match(s.begin(), s.end(), re)) if (boost::regex_match(s.c_str(), matches, re)){ cout << matches.size(); // matches[0] contains original string. matches[n] // contains sub_match object each matching // subexpression (int = 1; < matches.size(); i++){ // sub_match::first , sub_match::second iterators // refer first , 1 past last chars of // matching subexpression string match(matches[i].first, matches[i].second); cout << "\tmatches[" << << "] = " <...

c++ - Can my code use a 'T' or 'const T &' specialization, whichever is available? -

we working inhouse library features stringbuilder class used turn list of variablevalue objects string. variablevalue objects can constructed arbitrary types (by specializing convertvariable template function). here's code describes scenario: struct variablevalue { // construct 'variablevalue' object, variant type can represent values of // 1 of 4 types: string, number (integer), boolean , floating point. explicit variablevalue( const std::string &serializeddata ); // getters, typesafe; yield exception when calling wrong getter. const std::string &asstring() const; bool asboolean() const; // .. // convert variablevalue object string static std::string converttostring( const variablevalue &v ); }; // template specialized user types can casted // variablevalue object template <typename t> variablevalue convertvariable( t v ); // helper class 'concatenate' multiple variablevalue objects single string. class stringbuil...

PHP: Determine whether its a checkbox is checked or not -

my checkbox looks this: <input type="checkbox" name="activate[]" class="setsetting" value="<?php echo $row["id"]; ?>"> and have foreach: $activate = $_post['activate']; foreach($activate $a){ echo $a ."<br>"; } works fine value out of. how can determine if checkbox has been checked? $activate = $_post['activate']; foreach($activate $a){ $query_email = mysql_query("select id lp_email_settings order id asc"); while($ro = mysql_fetch_row($query_email)){ $getusersettings = mysql_query("select * users_email_settings uid = '$user' , esetting = '$ro[0]'"); if($ro[0] == $a){ if(mysql_num_rows($getusersettings) != 1){ mysql_query("insert users_email_settings (uid, esetting) values ($user, $ro[0])"); } ...

Exercises for Sql Server 2005 -

i new sql server 2005 , planning learn ssis, ssrs , ssas. before going deep want master fundamentals of sql server 2005. novice did best , installed these database adventureworks adventureworksdw now best resource can master fundamentals? need exercises on these databases because understand sql math "the more practice more learn". also, please recommend me other database if need install. i not recommend w3schools learning sql. i've found examples simple beginner , think bored pretty quickly. suggestion before trying learn ssas, ssis, ssrs, learn fundamentals of sql server rdbms. end, books start learning. suggest getting can itzik ben-gan , mcts self-paced training kit (exam 70-433): microsoft sql server 2008 - database development: microsoft sql server 2008 database development (if anything, organizing things want learn about. think great book , served me when studying mcts exam. there sql 2005 version.) don't forget books online (sql server...

webview in android -

i using webview control in android show html content. face problem in webview have fix height thats why if html content contains less data wasted space. there solution solve problem how can show same content html has in webview without wasted space please help. following xml used draw webview right? in give fix height webview. if not giving fix height show 1 line data scroll. <linearlayout android:id="@+id/llweb" android:layout_width="fill_parent" android:scrollbars="vertical" android:background="@android:color/transparent" android:layout_height="500dip"> <webview android:id="@+id/hellowebview" android:layout_width="fill_parent" android:background="@android:color/transparent" android:layout_height="500dip"/> </linearlayout> thanks use "fill_parent" attribute height , width in webview.

java - Code inside thread slower than outside thread..? -

i'm trying alter code can work multithreading. stumbled upon performance loss when putting runnable around code . for clarification: original code, let's call it //dosomething got runnable around this: runnable r = new runnable() { public void run() { //dosomething } } then submit runnable chachedthreadpool executorservice. first step towards multithreading code, see if code runs fast 1 thread original code. however, not case. //dosomething executes in 2 seconds, runnable executes in 2.5 seconds. need mention other code, say, //dosomethingelse , inside runnable had no performance loss compared original //dosomethingelse . my guess //dosomething has operations not fast when working in thread, don't know or what, in aspect difference //dosomethingelse . could use of final int[]/float[] arrays makes runnable slower? //dosomethingelse code used finals, //dosomething uses more. thing think of. unfortunately, //dosomething code qu...

java - I don't understand the program -

i wanted program list contents available in directory. found nice code in java2's.com, http://www.java2s.com/code/java/file-input-output/listingthedirectorycontents.htm and here code, import java.io.file; import java.util.arrays; public class dir { static int indentlevel = -1; static void listpath(file path) { file files[]; indentlevel++; files = path.listfiles(); arrays.sort(files); (int = 0, n = files.length; < n; i++) { (int indent = 0; indent < indentlevel; indent++) { system.out.print(" "); } system.out.println(files[i].tostring()); if (files[i].isdirectory()) { listpath(files[i]); } } indentlevel--; } public static void main(string args[]) { listpath(new file(".\\code")); } } what don't understand variable n in first for loop. if not defined anywhere, why program not showing error? int i, n; would declare 2 ints. in code ...

c# - .NET Compact Framework - multiline text in items -

is there free available listview based control .net cf allows multiline text in items/rows? regards the sdf (community edition free) has listbox2, can owner-drawn. here's example shows multi-line, including different fonts on each line image in item too.

javascript - Is there a way of obtaining all library objects within an instance of JS? -

is there method in can iterate through objects exist within instance of javascript, regardless of javascript engine being used? i'm not interested in iterating through dom of web page. want know if there way can iterate through standard library objects (array, math, date, etc.) additional libraries may specific various browsers. no... , yes. window object global object in browser. contains native members of global scope, plus functions , properties provided dom. native objects math, array , date non-enumerable members of global object, means can't iterate on them using for...in loop. covers "no" part — there's no way of obtaining these objects through iteration in many browsers. however, ecmascript 5th edition implementations (ie 9, chrome 7, firefox 4) can use object.getownpropertynames() array of property names specific object. instance, console.log(object.getownpropertnames(window)); will give list of members of global window obje...

url - Show hyperlinks in javascript alert -

is possible show hyperlinks in javascript alerts? mean, if like alert("<a href='http://stackoverflow.com'>link</a>"); the alert show plain text "link". is possibile show clickable url? thanks not possible. use "custom" alert dialog, have plenty jquery plugins this.

asp.net - Why HttpContext.Current.Session is null in Global.asax? -

i'm using vs2010 , created simple asp. web forms application, using development server test it. try store user data - queried sql server - in session, since don't want access database in every request. i'm using 'application_authenticaterequest' , 'session_start' methods. first round: authenticaterequest called. following code ran: public static void initialize(string login_name, bool force_refresh) { httpsessionstate session = httpcontext.current.session; object o = session == null ? null : session["employee_data"]; if (force_refresh || o == null || o.gettype() != typeof(employee) || (o employee).login_name!= login_name) { _current = uimanager.getemployee(login_name); if (session != null) { session["employee_data"] = _current; } } else { _current = (employee)o; } } the _current variable private static field published throu...

SQLAlchemy ORDER BY DESCENDING? -

how can use order descending in sqlalchemy query following? this query works, returns them in ascending order: query = (model.session.query(model.entry) .join(model.classificationitem) .join(model.enumerationvalue) .filter_by(id=c.row.id) .order_by(model.entry.amount) # this row :) ) if try: .order_by(desc(model.entry.amount)) then get: nameerror: global name 'desc' not defined . just fyi, can specify things column attributes. instance, might have done: .order_by(model.entry.amount.desc()) this handy since can use on other places such in relation definition, etc.

android - BitmapFactory.decodeByteArray doesn't keep color information when pixel is fully transparent -

i use bitmapfactory.decodebytearray generate bitmap png image. use bitmap.getpixels retrive pixel data. problem when pixel set transparent, color data seams discarded. 0x0000ff00 being returned 0x00000000. if create image code has transparent pixels make copy, render canvas, use canvas.drawcolor(0xff000000, mode.dst_atop) , correct color values getpixels , add alpha values got first getpixels call. can't since color information seams gone. there way make sure color information stored when generating bitmap png file using bitmapfactory? try setting bitmapfactory.options.indither = false, should trick. took wisdom here.

c++ - interactive binary decoder to structs -

i have looked bit unable find figured might have been has been created. i looking application read in binary file, allow inputing of types of patterns/rules in someway expected (like set of messages each of header + data) , deserialize data text format based on patterns/rules (e.g., binary file set of m messages header contains type of struct , number of bytes struct's serialization takes directly serialized file). specifically, lets know ahead of time have file contains sequence of serialized c structs (or c++ classes) prepended header indicating struct in serialized in next n bytes (where n contained in header). i know how write c/c++ code go through , deserialize data (provided know types ahead of time) wondering if there exists type of application facilitate process if not entirely sure of format/structs ahead of time (other hexeditor). graphical see dynamic effect of changing structs/rules/patterns optimal if exists. boost::serialization quite similar this...

asp.net - Programmatic accessing a control from base to derived? -

in recent post, expressed need access properties body using declarative syntax, see contentplaceholder replacing attributes? i thought first suggestion solved problem. but, syntax confuses editor not acceptable. my hypothesis workable solution make change in code. derive class system.web.ui.page extended functionality. however, want designer able still use declarative syntax set body tag. in other words, i not want have change code in aspx web pages except derive base i want able set these properties using declarative syntax, merely adding tag in derived page i'm not sure how go doing because doesn't fit oop paradigm , i'm not sure changes need made. initial hypothesis, i can use findcontrol in base see if placeholder has been added. but, not sure @ point in page processing lifecycle can use findcontrol. need set body before renders able grab declarative code. i hope i'm trying accomplish clear(?) basically, want able edit user defined tag in as...

ruby on rails - OmniAuth + Pulling Tweets, FB Places, etc -

i'm using omniauth + devise allow users register using facebook/twitter/gowalla/etc attached normal user accounts. when user logs in using of these, or account, social networks attached in authentications table. i need able pull content of these providers, such tweets or facebook places checkings, etc. understand need use different gem, plugin, whatever getting config need work gems (and make requests) confusing me. i need able access provider config items in omniauth.rb have api keys , secret keys, etc, need able grab tokens oauth stuff make requests. other gems https://github.com/jrallison/authlogic_oauth seem store oauth_token, oauth_secret , oauth_token, omniauth not. as can tell new ruby, rails , oauth, turning out challenging application. needed. sorted! added token , secret authentications table described in http://railscasts.com/episodes/236-omniauth-part-2 changed authentication.build line take 2 more parameters: authentications.build( :provi...

Is it possible to sandbox and run C++ or C# code that's entered in a textfield in a browser? -

i'm diving web development after ten years of desktop development , i'm experimenting testing concepts. wondering if it's possible sandbox , run c++ code that's entered in textfield in browser? that, mean run c++ or c# code on backend webserver , return analysis of code. clear, don't mean run c++ or c# code that's intended generate kind of markup, blackbox test c++ or c# block of code that's entered. how invoke compiler, depending on web server you're using? how sandbox code prevent malicious behavior? if we're considering 1 of c variants, blacklisting/whitelisting specific functions , libraries prevent malicious behavior? or blacklist long , limiting allow fair amount of code run? these high-level questions i'm asking because i'm having hard time finding direction, i'm going continue researching them right now. in advance help! you might find the codepad page interesting.

android - AsyncTask and Looper.prepare() error -

i have following code class overlaytask extends asynctask<void, void, void> { @override public void onpreexecute() { if (sites != null) { mymapview.getoverlays().remove(sites); mymapview.invalidate(); sites = null; } } @override public void doinbackground(void... unused) { grabshipswithlocation(); return (null); } @override public void onpostexecute(void unused) { mymapview.getoverlays().add(sites); mymapview.invalidate(); isloading = false; } } that seems work fine on few test devices seeing lot of errors appearing on dev console. can't seem work out why , put looper.prepare(). needed? java.lang.exceptionininitializererror @ com.test.appname.findermain$1.gotlocation(findermain.java:286) @ com.test.appname.mylocation$getlastlocation.run(mylocation.java:89) @ java.util.timer$timerimpl.run(timer.java:289) caused by: java.lang.run...

How to check if a user has permission to a SharePoint site collection -

what best way check if user has permission site collection/site? i'm using following spsecurity.runwithelevatedprivileges( () => {using (var site = new spsite(nodeurl)) { using (var web = site.openweb()) { retvalue= web.doesuserhavepermissions( context.user.identity.name, spbasepermissions.open); } } }); this doesn't seem working properly. if user never added site works. if user added , removed doesuserhavepermission(.. spbasepermission.open) still returns true, when user tries access site sharepoint throws access denied page. after little more digging found user account still in web.allusers list, has no roles assigned. use checkpermissions instead of doesuserhavepermissions . see ...

android - how to fill in scroll view from file or database or any data source? -

i want bind data xml file? how can i'm using layout xml file define scrollview ?? if i've understood question right, want read layout file , insert scrollview. you want take layoutinflater task. example doing activity. layoutinflater inflater = (layoutinflater)context.getsystemservice(context.layout_inflater_service); scrollview sv = findviewbyid(r.id.id_of_scrollview); inflater.inflate(r.layout.id_of_layoutfile_to_include, sv); edit: after having read comment realise misunderstood question. scrollview not view want binding data, scrollview specialized framelayout, , therefore allows 1 child. your looking view listview (which adds scrolling automatically) another solution use layout in scrollview , dynamically (from code) add views. linearlayout ll = findviewbyid(r.id.id_of_linearlayout); //loop data , build view each data entry , add ll.addview(yourview);

Is there a way to encode object constructors with the JSON Perl Module? -

all, i'm using json perl module encode json. i'd resulting json include lines this: { "startdate": new date(2010,11,15,0,0), "astring" : "string data", "anumber" : 1234 } in order create that, have perl hashref this: { startdate => see below, astring => "string data", anumber => 1234, } here's problem: can't figure out how coerce json module printing unquoted strings, can include new date(...) instantiation call. i've tried creating perl module to_json method, output still gets quoted. does out there have suggestions on how can encourage json print unquoted strings? json not meant encode objects that. encodes simple data structures arrays , hashes. if want use deserialized data populate blessed object, need add layer on top. for moose objects, plugin moosex::storage built expressly purpose.

Mercurial plug in for Delphi -

is there project or project in progress creating mercurial plug in delphi xe? failing that, can learn more creating one? delphi xe has svn support , integration open source project, can it's code here i read somewhere made generic it's not tied svn, add svn support because it's more popular , starting point. also uwe schuster blog (who developed version insight delphi xe), both git or mercurial support planned. q: there support git or mercurial? a: support both planned , first tests have been done in past months, don’t have timeframe. (remember have full time job, work on version insight in free time , it’s not thing)

Passing a constant value to a stored procedure mapping in Entity Framework -

i'm working on creating entity framework model our database tables, , part, things going pretty well. however, i'm running bit of issue mapping stored procedures. see, homebuilt orm our company has been using tends use 1 sproc inserting , updating, , differentiats operations passing bit valued parameter called @isinsert (i know, don't me started). entity framework seems expect separate sprocs inserting , updating, figure have tell ef "pass true parameter when you're using insert, false if it's update". however, @ least according designer ui, doesn't seem give me option mapping other fields on entity object. there way pass constant value (boolean true or false ) sproc mapping in ef4? your best bet may use context.executestorequery(query) , keep how before.

dictionary - Sentiment Analysis Dictionaries -

i wondering if knew obtain dictionaries of positive , negative words. i'm looking sentiment analysis , crucial part of it. the sentiment lexicon , @ university of pittsburgh might after. it's lexicon of 8,000 words positive/neutral/negative sentiment. it's described in more detail in this paper , released under gpl.

iphone - UILocalNotification custom sound -

i have been searching solution hours.. absolutely 0 luck. i set local notification: uilocalnotification *notif = [[cls alloc] init]; [datecomp setday:j+1]; [datecomp sethour:[[time objectatindex:0] integervalue]+offset]; [datecomp setminute:[[time objectatindex:1] integervalue]]; nslog(@"year: %i, month: %i, day: %i, time:%i:%i\n",[datecomp year], [datecomp month], [datecomp day], [datecomp hour], [datecomp minute]); notif.firedate = [gregorian datefromcomponents:datecomp]; notif.timezone = [nstimezone defaulttimezone]; notif.alertbody = [names objectatindex: k]; notif.soundname = @"fireburn.caf"; notice sound name... i tried put 10 sounds (aiff, wav, caf...etc), notification pops default sound :/ i have "fireburn.caf" file in resources folder. why not playing sound????? thanks. answer: nothing wrong code.. it's stupid iphone didn't cancel old notifications made default sound - _ -; when cle...

android - How to get a button's height to match another element's height? -

Image
i want put button next edittext , want heights match. for example, built in android browser: the go button same height edittext field. know wrap both these views in parent layout view, , set both of heights fill_parent, , make them match. however, without having give layout static size. rather have edittext take whatever height needs based on font size , have button next match whatever height might be. is possible xml layout? you need make edittext wrap_content on height , have button fill_parent . need have them both wrapped in layout parent. way associated same layout parent. try , see how works, if helps let me know. if doesn't maybe can give code out.

c# - Passing a Func<T, TResult> where TResult is unknown -

note: please re-tag and/or re-name appropriately i have class, fooenumerator , wraps foo , implements ienumerable<fooenumerator> . foo s represent tree-like data structure, fooenumerator s enumerated child nodes of current node. foo vendor supplied data object. fooenumerator implements bunch of custom filtering code. class fooenumerator : ienumerable<fooenumerator> { public foo wrappednode { get; private set; } public string name { { return wrappednode.name; } } public int id { get{ return wrappednode.id; } } public datetime created { get{ return wrappednode.created; } } public fooenumerator(foo wrappednode) { wrappednode = wrappednode; } public ienumerator<fooenumerator> getenumerator() { foreach (foo child in this.getchildren()) if(filteringlogicinhere(child)) yield return new fooenumerator(child); } ... } i want able sort each level of tree given (arb...

Linear program question -

i'm trying prepare midterm , going on problems out of algorithm book can't seem figure out following problem: find necessary , sufficient conditions on reals , b under linear program max: x+y ax + <=1 x, y =>0 (a) infeasible. (b) unbounded. (c) has finite , unique optimal solution. here i've come with: (a), can add constraint: ax+by=>5 i'm not sure b , c.i'm not sure if i'm allowed change constraints i'm given or add new ones. any appreciated. advance. a) i'm not sure if possible unless add constraint did. b) if , b both less or equal 0 problem unbounded c) if , b both larger zero, , not equal each other have unique optimal solution

vb.net - What testing framework do you suggest for .net? -

i'm vb.net programmer. start writing unit & user interface test web application. hear frameworks suggest writing tests? my requirement have able use software team foundation build server , perfect if vendor of framework microsoft. please advice me , write couple words why chosen technology best in opinion. visual studio 2008 , higher (non-express editions), visual studio 2005 team suite, include unit testing features. http://msdn.microsoft.com/en-us/library/ms182409.aspx

How do I build a Drupal's View that shows access information -

i need create views of selection of nodes, of current user may or may not have access to. able is, known access node, print out either link node, or statement letting them know there no access node without conditions met first. i had thought pretty simple matter, on attempting it, don't know how proceed. know how create such views? update: looks might simple matter of using views custom field module indeed, simplest solution found use views custom field module check if user has access node , depending on that, generating output: if (node_access('view', $data->nid)) { //... }

performance - External XML for culture-specific text / Translation mapping -

we building system gets xml data database, uses xslt transform xhtml , @ same time use external xml file retrieve culture-specific labels ( translations our labels ). short question translation/culture-specific system seem logical ? efficient ? any alternative concepts welcome ( in specific context ) detailed question xml data <page id="55" objecttype="christianorthodoxmonument"> <field name="uniquename">some unique name here</field> .. multiple field elements here .. </page> xml culture-labels <christianorthodoxmonument> <uniquename culture-1="Ονομασία" culture-2="unique name" /> <birthdate culture-1="Ημ/νία γέννησης" culture-2="date of birth" /> </christianorthodoxmonument> now in xslt pass cultureid parameter used mapping labels. xslt ( example snippet ) <xsl:param name="cultureid" select="1" /> <xs...

Any engine for Voice to Text conversion? -

i want know voice text conversion. i'm following research project area , i've searched everywhere on internet. sapi using .xml file predefined input keys. doesn't relate project. can convert voice text directly? don't need at-least 60% accuracy. conversion. suggestions ? similar thread here might help: https://stackoverflow.com/questions/2080401/is-there-a-speech-to-text-api-by-google/2080424#2080424

php - Reg exp to replace ampersands but not html entities -

in code below want replace plain ampersands "and" while ignoring ampersands being used part of html entities (ex: ") i've tested expression &(?!([\w\n]{2,7}|#[\d]{1,4});) on @ http://www.gskinner.com/regexr/ , matches want. however, when run code, results blank. $content = "&quot; apples & oranges &quot;"; $content = preg_replace("/&(?!([\w\n]{2,7}|#[\d]{1,4});)/g","and",$content); echo $content; is approach flawed somehow or have syntax issue? remove g flag , should work fine. note seem me you'd expect , ampersand surrounded spaces, following simplified solution: $content = preg_replace("/\s/&\s/"," , ",$content); although realise might allow mistyped text cause encoding errors. if there space missing.

javascript - How can I make a sortable, changeable, addable, removable web-page element? -

i'm creating web-app interface allow users construct sentences clicking on words/phrases. each word of phrase contained in own page element, eg. <div> . div class need allow: dragging different order relative other divs/words (ie. sorting) an x (only visible when hovering over) in top right corner of box remove upon clicking changing of font/text upon click actions be inserted page when user wishes add word for instance, imagine page (quote marks denote element): " hi, name is " [textbox] "i work at..." " and born in " [combobox] the phrase in italics 'inactive' , not part of sentence, if user clicked change " i work at " [textbox] , new div added eg. " and at... " allow further expansion. phrases in bold have close button /clickable action rid of them or make them inactive again. draggable change order. can see need dynamically insert new textboxes , comboboxes accommodate more phrases requiring inpu...

return class from function in c# -

can return class object function in c# return value instead return string or int or ..etc a class object in c# type. can return function: public type foo() { return typeof(string); } public type bar() { return somenonnullvariable.gettype(); }

Locale Setting in Android -

what difference between locales ja , ja_jp in android? have care both? thanks in advance. here definition difference is: http://developer.android.com/reference/java/util/locale.html ja = japanese ja_jp = japanese spoken in japan easy if implement local ja speaking japanese no matter live.

Logging in Eclipse/Android -

i trying log in eclipse in simple test app.i have following: public class test extends activity { /** called when activity first created. */ @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); log.i("fsdsfs","jjjjjj"); } } i have imported log via import android.util.log; , looking in logcat,but see nothing @ all.i clicked on circle around in logcat. what doing wrong here? thanks in ddms, click on devices button (a tiny mobile phone icon) select emulator or device list. , here go. :-)

asp.net - Problem with asmx webmethod that uses Mysql Load Data local infile -

when use following in webmethod: string mysqlspath = server.mappath("applog.txt"); command.commandtext = "load data local infile '" + mysqlspath + "' table numbers fields terminated ',' lines terminated '\n'"; command.executenonquery(); connection.close(); i error load data local infile ---> not find file 'c:\windows\system32\inetsrv\inetpubwwwrootwebservicesapplog.txt' when looking @ error noticed after "inet" dropping "\" between rest of directories, causing , how can fix it? you'll need escape mysqlspath variale first. something trick mysqlspath = mysqlspath.replace(@"\", @"\\"); this convert \ \ c# won't remove it.

iphone - How to tell which MKPinAnnotation has been pressed? -

i have mkmapview , have whole bunch of mkpinannotations being shown , of them have call out feature shows more detail view depending on location is.. how can implement method tells pin has been pressed out of group shows more detail view location? implement mkmapview delegate: - (void) mapview: (mkmapview *) mapview didselectannotationview: (mkannotationview *) view and can whatever need in there. but think after enabling map callout accessory. see mapcallouts sample application http://developer.apple.com/library/ios/#samplecode/mapcallouts/introduction/intro.html#//apple_ref/doc/uid/dts40009746

c++ - Overriding operator -

anybody me constructor overriding.. i have void operator delete(void*) {} void operator delete(void* p, void*) {} in class.. looks overloading(same function name , return type different parameter list) overriding .. how overriding.. anyone explain me these 2 lines function. void operator delete(void*) {} void operator delete(void* p, void*) {} these custom deallocation functions. deallocation function called via delete expression. e.g. yourclass* p = new yourclass(); // allocates memory & calls constructor // ... whatever, delete p; // calls destructor & deallocates memory for class delete expression in last line above first call destructor, , call single void* argument deallocation function class defines, first of 2 functions, if deallocation accessible. however, might deallocation function declared private or protected , purpose of making inaccessible. in first case delete expression outside class' own cod...

iphone - NSOSStatusError -

i try play number of audios in app , working fine upto 3 times. when trying play in 4th time shows error . error domain=nsosstatuserrordomain code=-43 "the operation couldn’t completed. (osstatus error -43.)" .the code nsurl *url = [nsurl fileurlwithpath:[nsstring stringwithformat:@"%@/sun.wav", [[nsbundle mainbundle] resourcepath]]]; nserror *error; audioplayer = [[avaudioplayer alloc] initwithcontentsofurl:url error:&error]; audioplayer.numberofloops = 0; audioplayer.volume=1.0; if (audioplayer == nil) { nslog([error description]); } else [audioplayer play]; anybody figure out before..? looks aren't releasing audioplayer object. fact can play 3 times related number of open files can have in avaudioplayer object. look delegate methods avaudioplayer: specifically - (void)audioplayerdidfinishplaying:(avaudioplayer *...

c# - thread suicide question -

i want kill thread when bad happen. what's suggestion thread suicide? you should never "kill" thread. main program, can abort using thread.abort method, not recommended, , unnecessary. your thread should nothing more method executing long loop. if "really bad" happens, return method , thread end. this enough such loop: private void mythreadloop() { try { while (somecondition) { // lengthy operation } } catch (exception ex) { log.error("something bad happened: ", ex); } } public void start() { thread t = new thread(mythreadloop); t.start() } on other hand, if need main program kill thread (but not "suicide" named it), should signal thread want end, , not abort without knowing going on in background.

javascript - Are jQuery events blocking -

are jquery events blocking? for example calling following method return immediately? $("body").trigger("myeventname", myvalue); my testing seems suggest are. if correct mean can return values custom events? var myresult = $("body").trigger("myeventname", myvalue); clearly doesnt work returns jquery object. can values returned? you can use .triggerhandler() method this, returns whatever last event handler event on selector returns (instead of jquery object chaining), use this: var myresult = $("body").triggerhandler("myeventname", myvalue); you can give try here . check out documentation page list of differences .trigger() .

javascript - Can you set a variable name equal to another variable's value? -

i interested in knowing if possible. one example variable exists. foo = 1; var bar = 'foo'; if('foo' == 1)? is there way that. is there way bar == foo.variablename yes can wouldn't recommend it. s="unicorn" eval("var " + s + " = 'test'") alert(unicorn) but text in question kind of sounds want check if variable exists , possible if (typeof variable == "undefined") alert("it's not defined!");

Writing binary data in a sqlite database Android's ContentResolver -

i'm reading sources android, , read this: outputstream thumbout = mcr.openoutputstream(uri); bitmap.compress(bitmap.compressformat.jpeg, 85, thumbout); thumbout.close(); when trying store bitmap (bitmap) in database (uri uri of row in database). far can understand, openoutputstream allows store binary data in database, path of file placed in db. file placed somewhere in filesystem. correct? question is: how specify exact location of files when stored way? clarification. i suppose correct answer question used path 1 inserted in database.

maven 2 - Setting velocity properties -

i have occurence building maven archetype want #set( $controllerpackage = ${package}\.${artifactid}) i.e. set controllerpackage variable equal result of string concatentaion of following 3 elements ($package,'.',$artifactid) however obvioulsy not correct syntax - lexical error: org.apache.velocity.runtime.parser.tokenmgrerror: lexical error @ line 4, column 40. encountered: "." (46), after : "\" is there way can include period in outputted string? to construct string, use quotes. #set( $controllerpackage = "${package}.${artifactid}" )

solr - How can I use solrj to do a query with spellcheck -

usually , use http method spellcheck query, have use solrj this, pls me solve question , thx. you can specify parameters via: query.setparam("spellcheck", "true"); query.setparam("spellcheck.q", query);

jquery - javascript variable scope -

i have below code, it running output in console is instant: true instant2: false as variable not being overwritten in global scope. how can access variable in global scope? var instant = false; $('document').ready(function(){ chrome.extension.sendrequest({ action: "getstorage", key: "instant" }, function(response) { instant = true; console.log('instant: ', instant); }); console.log('instant2: ', instant); }); it getting overridden, later. function(response) isn't getting executed until after outer function returns.

php - Zend Lucene search related fields? -

i have lot of paired fields (hoursdistance1, cityname1, hoursdistance2, cityname2, hoursdistance3, cityname3, etc.). what query need search lucene scores based on both fields having correct terms instead of 1 of them? i.e. if search city 3 hours here name, how return results hoursdistancen 3 hours here , citynamen without scoring other pairs of fields? you create document each pair. instead of id | hours1 | name1 | hours2 | name2 | ... you have: id | pair_num = 1 | hours | name id | pair_num = 2 | hours | name ... since want search 1 pair @ time, shouldn't need merge results or anything.

iphone - 1 ViewController and 2 XIBs for 2 orientations, how? -

one viewcontroller shared 2 xibs, i.e. there 1 xib horizontal layout , 1 vertical layout. both xibs linked same viewcontroller, i.e.: hiscoreviewcontroller.h hiscoreviewcontroller.m hiscoreviewcontroller-horizontal.xib hiscoreviewcontroller-vertical.xib the question how can (re)load corresponding xib in didrotatefrominterfaceorientation ? thanks! you can use different views in 1 view controller. can change views based on orientation.

android - Change source image for image view when pressed -

i have scroll view lots of image buttons. want change image image button when it's pressed. thing want image remain until image button pressed. that's why couldn't use selector. best practice achieve his? best regards you want this. imagebutton demo_button = (imagebutton)findviewbyid(r.id.firstimage); // when click demo button demo_button.setonclicklistener(new onclicklistener() { public void onclick(view v) { demo_button.setimageresource(r.drawable.secondimage); } } try this. (updated setset set)

c# - Multiple Tooltips to same Control -

i using windows forms application in c# have label having date text 16-12-2010 want display different tooltip when mouse on date/month/year e.g. when cursor on date : today's date tooltip updated: one source of example when vote close question in stackoverflow.com use multiple labels - 1 each part. otherwise you're going need know characters in label mouse on - different font's render differently. that's can-o-worms if ever there one.

c++ - Inline function linkage -

i can't make sense of following behavior: 1 header basic types, , header in use these types in several functions. afterward started constructing classes based on defined types , functions. in function header if leave following signature: void whateverfunction(parameters) the linker points out there multiple definitions of whateverfunction. if change to: inline void whateverfunction(parameters) the linkage problem gone , compiles , links well. know concerning inline replaces every function call it's code other it's pretty dark, question is: how linker treats inline functions in c++? when function in header not inline, multiple definitions of function (e.g. in multiple translation units) violation of odr rules. inline functions default have external linkage. hence, consequence of odr rules (given below), such multiple definitions (e.g. in multiple translation units) okay: $3.2/5- "there can more 1 definition of class type (clause 9), enu...

c# - How do I find the closest array element to an arbitrary (non-member) number? -

seemingly similar questions: " finding closest number in array " (in java) , " find nearest match array of doubles " (actually geography problem). i have (sorted) array of doubles. given arbitrary number (which may or may not exact match 1 of array elements), how can return index of number closest match? for example, using following array: 1.8 2.4 2.7 3.1 4.5 querying 2.5 return index of 1, corresponding value of 2.4. bonus points detecting values lie outside of range of array elements. example, using array listed above, code may decide 4.6 in, 5.9 out. if want try part of question, specifics in hands. array.binarysearch , returns: the index of specified value in specified array, if value found. if value not found , value less 1 or more elements in array, negative number bitwise complement of index of first element larger value. if value not found , value greater of elements in array, negative number bitwise complement of (the index...

c# - Including paramaters only for the purpose of exception reporting in inner functions -

createdocument(string templatepath) { document doc = opendocument(templatepath); picture pic = getlogo(); addlogo(doc, pic, templatepath); } addlogo(document doc, picture logo, string templatepath) { picture placeholder = doc.findlogoplaceholder(); if (placeholder.size != logo.size) { throw new applicationexception( string.format("invalid template {0}, logo size: {1}, required: {2}", templatepath, placeholder.size, logo.size )); } } consider above code example made up. notice reason templatepath passed addlogo method facilitate exception generation. i have in code today needed this, , feels nasty code smell me. i'm not familiar exception handling patterns , don't see better way it. i'm wondering thoughts , if there better pattern dealing situations this. create exception on higher level: createdocument(string templatepath) { document doc = opendocument(templa...

A default flag on a table in rails -

i have simple table/model in rails, vat_rates . administrators need able select one, , 1 of these default rate selected on html form when creating new related items items have vat_rate_id . have added boolean default column vat_rates table. what straight forward, , rails-like way ensure 1 vat_rate can default 1 @ time? i'm not bothered if there no defaults, there no more one. you add custom validation method this , return error if vat_rate selected default already. alternatively can add before_update or after_update callback this set other default values false on update.

c# - Result of addition of two bytes when it cross its limit -

let have got 2 byte variable: byte a= 255; byte b= 121; byte c= (byte) (a + b); console.writeline(c.tostring()); output:120 please explain me how adding values. know crossing size limit of byte don't know operation performs in such situation because not looking chopping result. thanks edit: sorry 120 answer. you overflowing byte storage of 255 starts 0. so: + b integer = 376 your code equivalent to: byte c = (byte)376; that's 1 of reasons why adding 2 bytes returns integer. casting byte should done @ own risk. if want store integer 376 bytes need array: byte[] buffer = bitconverter.getbytes(376); as can see resulting array contains 4 bytes necessary store 32 bit integer.

assembly - Binary subtraction -

say i'm going subtract: 0000 0000 - (-1) that is: (two complement) 0000 0000 - 1111 1111 --------- = ???? ???? whats gonna happen, brain f***ing me right now, went fine before, think overflow thats screwing me up, can give clearance on please :)? take two's complement of subtrahend , add minuend. 0000 0000 - 1111 1111 ... 0000 0000 + 0000 0001 ----------- 0000 0001

android - MySQL db connection -

i have been searching web connection between android simulator , mysql db. i've found can't connect directly can via web server. web server handle request android. i found following code on hello android , don't understand. if run code on simulator, nothing happens; screen stays black. log.i land, in android screen, error log, or somewhere else? can me code? package app.android.ticket; import java.io.bufferedreader; import java.io.inputstream; import java.io.inputstreamreader; import java.util.arraylist; import org.apache.http.httpentity; import org.apache.http.httpresponse; import org.apache.http.namevaluepair; import org.apache.http.client.httpclient; import org.apache.http.client.entity.urlencodedformentity; import org.apache.http.client.methods.httppost; import org.apache.http.impl.client.defaulthttpclient; import org.apache.http.message.basicnamevaluepair; import org.json.jsonarray; import org.json.jsonexception; import org.json.jsonobject; import android...

c# - .NET (non-visual) component -

i need create non-visual component, foocomponent , management controls of type bar resides in form. i have following constraints: the foocomponent can added forms. only 1 foocomponent per form allowed. foocomponent should register form closing event, , when fires , function on bar 's , sent e.cancel value based on returned values. #1 , #2 above should enforced on run-time design time. #3 event registration should made automatically , not foocomponent 's users. i searched google , msdn , read component , componentdesigner classes, didn't find rescue. what should do? (1) control component can added form, use foocomponent constructor passed form, , don't define default constructor. it's called like: foocomponent component = new foocomponent(this); where component created within form itself. not-defining default constructor, this: foocomponent component = new foocomponent(); will not compile. (2) expose foocomponent prop...

.net - Attempted to read or write protected memory -

i having problem mapi class below.(original source http://www.codeproject.com/kb/ip/sendfiletonet.aspx ) when users try send emails using sendmailpopup-method email program opens correctly after mail window closes program crashes message: attempted read or write protected memory. indication other memory corrupt. i suspect that bug caused cleanup method , managed reduce frequency of crashes using int64 store pointers instead of int used in original version. .net unsafe programming knowlege rather limited can me find out causing rest of crashes update: apparently cleanup method not causing exceptions because program crashes when commented out, possible cause mapi32.ddl sendmail method. wrong pointers passed parameters. users using systems 64-bit processors , 32-bit winxp. update: the solutions provided in thread did lower frequency of crashes did not solve problem entirely. solution worked 100 % write small console application using c++ made mapi calls. our .net applica...