Posts

Showing posts from February, 2015

c++ - Does resizing an STL vector erase/invalidate its previous contents? -

it doesn't appear (sample program), can sure? // resizing stl vector erase/invalidate it's previous contents? #include <stdio.h> #include <vector> using namespace std ; void print( vector<int>& t ) { for( int = 0 ; < t.size() ; i++ ) printf( "%d ", t[i] ) ; puts(""); } int main() { vector<int> t ; t.resize( 12,9999 ) ; print(t) ; t.resize( 15, 10000 ) ; print(t) ; } resizing stl vector may require reallocating underlying storage. may cause number of elements destroyed , recreated, , all iterators invalidated. accessing invalidated iterator common source of errors when using stl. the contents of each element same, unless copy constructor doesn't work. int main(int argc, char *argv[]) { int data[] = { 1, 2, 3 }; std::vector vec(data, data + 3); // vector contains 1, 2, 3 std::vector::iterator = vec.begin(); cout << *i << endl; // prints 1 int

javascript - Can I drop the the helper of a draggable into a sortable instead of the original item? -

for example, when drag draggable sortable, there helper different original draggable item. can drop helper item sortable instead of original draggable item? you can use dropable plugin anywhere in combination draggable plugin drag items location b. location b can using sortable plugin. => drop items in sortable you can find here example of 2 plugins working together: http://jqueryui.com/demos/draggable/#sortable

c++ - Why is running attached to the debugger so slow? -

what going on causes debug build slower attached debugger compared unattached? both same exe running. edit: of answers concentrate on breakpoints. i'm still running mud without breakpoints, outputdebugstring, or in watch window. debug crt, runtime stack checks, , debug heap? if isn't outputdebugstring or piles , piles of breakpoints slowing down, try these: windows debug heap - process gets debug heap if running under debugger, no questions asked. disable when running under visual studio debugger, visit debugging page of project properties , add _no_debug_heap=1 environment. (the windows debug heap separate thing crt debug heap. release build windows debug heap too, if runs under debugger.) the program loads lots of dlls have symbols. when dll loaded, visual studio tries find symbols it. if there symbols available, can take time. there's not can except rearrange program loads dlls less often. check calls isdebuggerpresent - can introduce arbitrary

java - How to close main frame when open new one -

ive created 2 frames main frame home , second 1 selectie on home there button open frame selectie, want when click button main frame home wil dissapear , selectie shown. code button ive make in other package , dont want in same class main (home) code home: package view; import java.awt.borderlayout; import java.awt.color; import java.awt.container; import java.awt.dimension; import java.awt.toolkit; import java.awt.event.actionlistener; import java.io.file; import javax.swing.icon; import javax.swing.imageicon; import javax.swing.jbutton; import javax.swing.jdialog; import javax.swing.jframe; import javax.swing.jlabel; import javax.swing.jpanel; import controller.homecontroller; import music.playsound; public class home extends jframe { private jlabel label, label1, label2; private jpanel panel; private jbutton logo, logo1, logo2, logo3, logo4, logo5, selectie; private container window = getcontentpane(); private homecontroller controller; publ

css - Attach an image to any word -

i'd attach images specific words cannot find right css selector so. i have portion of site displays data it's pulled database, adding classes or id's words not option me. i need css display background image wherever word (or in case, name) found on page. for example, in following (which pulled database): <td class="data1"><font face="verdana, arial, helvetica, sans-serif" size="1">patrick</font></td> i add background image name patrick found. i tried variations of, td[.table1 *='parick'] { background-image:url(../images/accept.png); but didn't me anywhere. , since it's not in <span> or <div> or link, can't figure out. if have ideas or jquery workaround, please let me know. thanks! if can guarantee names appear text nodes in elements, can use simple jquery selector... $(':contains("patrick")').addclass('name'); jsfiddle . if

Asp.net MVC 3 Validation exclude some field validation in TryUpdateModel -

i using asp.net mvc razor , data annotation validators model: public class person { public int id { get; set; } [required] public string firstname { get; set; } [required] public string lastname { get; set; } } firstname , lastname requerd. want edit firstname. methode is: public actionresult edit([bind(include = "firstname")]person person) { var p = getperson(); if (tryupdatemodel(p)) { //save changes; } } but tryupdatemodel return false. because lastname invalid. how can prevent check validation of lastname in tryupdatemodel? note: the code simplified. real code complex i have use requierd 2 property i dont want use different model class i found nice solution. must remove unused field modelstate. modelstate.isvalid return true. first need create new attribute class: public class validateonlyincomingvaluesattribute : actionfilterattribute { public override void onactionexecuting(action

web services - Efficient C++ software stack for web development -

what c++ software stack developers use create custom fast, responsive , not resource hungry web services? i'd recommend take on cppcms: http://cppcms.com it exactly fits situation had described: performance-oriented (preferably web service) software stack for c++ web development. it should have low memory footprint work on unix (freebsd) , linux systems perform under high server load , able handle many requests great efficiency [as plan use in virtual environment] resources extent limited. so far have come across staff wsf, boost, poco libraries. latter 2 used implement custom web server... the problem web server 2% of web development there stuff handle: web templates sessions cache forms security-security-security - far being trivial and more, why need web frameworks.

mysql - Do I really have to create a temp table? -

just wondering if knows neater way of doing following without creating , dropping table? create temporary table temp_table select table_one.col1 table_one join table_two on (table_two.col1 = table_one.col1 ) table_one.col2 = $arg1 , table_two.col2= $arg2; update table_two set col3 = $arg3 col1 in ( select col1 temp_table ); drop table temp_table; you join in update statement. update table_two, table_one set table_two.col3 = $arg3 table_two.col1=table_one.col1 , table_one.col2 = $arg1 , table_two.col2= $arg2;

knockout.js - KnockoutJS - Updating ViewModel OnChange of textbox value instead of OnBlur Options -

i'm pretty new knockoutjs , love i've seen far. currently, when observable property of view model bound text property of text box (input type=text), viewmodel gets updated on blur event of textbox. there way update view model on change event of textbox? tried creating custom binding handler on wiring change event handler on text box in "init", somehow did not work. correct achieve goal? or there easier way? you can use 'value' binding , add valueupdate binding attribute specify when update control: see here: http://knockoutjs.com/documentation/value-binding.html <p>your value: <input data-bind="value: somevalue, valueupdate: 'afterkeydown'" /></p> <p>you have typed: <span data-bind="text: somevalue"></span></p> <!-- updates in real-time --> <script type="text/javascript"> var viewmodel = { somevalue: ko.observable("edit me") }

c# - Is there a way to apply an attribute to a method that executes first? -

without using library postsharp, there way set custom attribute can have logic in when attached method, execute prior entering method? no; attributed not intended inject code. tools postsharp around smoke , mirrors, without that: no. option might decorator pattern, perhaps dynamically implementing interface (not trivial means). however, adding utility method-call top of method(s) much simpler, , presumably fine since if have access add attributes have access add method-call. or put way: tools postsharp exist precicely because doesn't exist out-of-the-box. // poor man's aspect oriented programming public void foo() { someutility.dosomething(); // real code } in cases, subclassing may useful, if subclass done @ runtime (meta-programming): class youwritethisatruntimewithtypebuilder : yourtype { public override void foo() { someutility.dosomething(); base.foo(); } }

Rails 3 - Solr doesn't search an items -

in photo model have following simple rule: searchable string :note end and try search string solr (simultaneously in 2 tables). output of solr query in terminal (the first 1 articles , second 1 photos ): solr request (4.8ms) [ path=# parameters={data: fq=type%3a article&q=searched_string&fl=%2a+score&qf=title+content&deftype=dismax&start=0&rows=30 , method: post, params: {:wt=>:ruby}, query: wt=ruby, headers: {"content-type"=>"application/x-www-form-urlencoded; charset=utf-8"}, path: select, uri: http://localhost:8982/solr/select?wt=ruby , open_timeout: , read_timeout: } ] and this solr request (4.4ms) [ path=# parameters={data: fq=type%3a photo&q=asgasg&fl=%2a+score&deftype=dismax&start=0&rows=30 , method: post, params: {:wt=>:ruby}, query: wt=ruby, headers: {"content-type"=>"application/x-www-form-urlencoded; charset=utf-8"}, path: select

Python Daemons - Program Structure and Exception Control -

i've been doing amateur coding in python while , feel quite comfortable it. though i've been writing first daemon , trying come terms how programs should flow. with past programs, exceptions handled aborting program, perhaps after minor cleaning up. consideration had give program structure effective handling of non-exception input. in effect, "garbage in, nothing out". in daemon, there outside loop never ends , sleep statement within control interval @ things happen. processing of valid input data easy i'm struggling understand best practice dealing exceptions. exception may occur within several levels of nested functions , each needs return parent, must, in turn, return parent until control returns outer-most loop. each function must capable of handling exception condition, not subordinates. i apologise vagueness of question i'm wondering if offer me general pointers how these exceptions should handled. should looking @ spawning sub-processes ca

python dynamically select rows from mysql -

i have table address . table getting new row inserts, appox 1 row per second. lets called process1. in parallel, need iterate on select * address results inserted till via process1. process2. should wait process1 insert new rows if reaches end, ie, there no more rows process (iterate) in address . both process1 , 2 long. several hours or maybe days. how should process2 in python? add timestamp column , select rows newer timestamp latest processed.

ios - Ignore multiple button taps after first one on iPhone webapp using jQuery Mobile? -

assume button in html5 webapp built jquery mobile. if taps button a, call foo(). foo() should called once if user double taps button a. we tried using event.preventdefault(), didn't stop second tap invoking foo(). event.stopimmediatepropagation() might work, stops other methods further stack , may not lead clean code maintenance. other suggestions? maintaining tracking variable seems awfully ugly solution , undesirable. you can set flag , check if it's ok run foo() function or unbind event time don't want user able use , re-bind event handler after delay (just couple options). here's do. use timeout exclude subsequent events: $(document).delegate('#my-page-id', 'pageinit', function () { //setup flag determine if it's ok run event handler var okflag = true; //bind event handler element in question `click` event $('#my-button-id').bind('click', function () { //check see if flag set `tru

sql - Creating SP specific to a database? -

every time create stored procedure defaulting "master" database. how make sp specific database "uploads"? create procedure testinsert2 insert [uploads].dbo.[aspnet_uploads] (userid, filename, username) values ('test1', 'test2', 'test3') you need in context of database. use uploads; go create procedure dbo.testinsert2 begin set nocount on; insert dbo.[aspnet_uploads](userid, filename, username) values('test1', 'test2', 'test3'); end go

c# - Resizing array performance? -

i'm wondering if resizing byte arrays can take big hit on performance. i'm adding data class , if class contains data type need add existing byte array, means i'll need resize it. problem there data types have adding in bulk means there multiple array resizes occurring. would make huge impact on performance? class can performance critical. if does, might have design-overhaul. if resizing required should use list<byte> instead. arrays cannot resized have create new array , copy old content new array before adding additional content (this array.resize if that's referring to). list<t> using array internally optimize resizing don't have deal it. essentially once internal array full , new content added, list<t> double internal array size, hence resizing should in fact occur - if resize array directly on other hand either have employ similar strategy , keep "size counter" or take resize performance cost on content addit

java - How to reference a position in a Set? -

how can reference position within set? array: array[5]; i developing android soundboard has favorites tab. favorites tab uses listview . when user adds favorite, text of button added set. have setup contextmenu list view allow user delete item long pressing, , pushing delete. context menu passes position of list view triggered context menu , trying delete position. you cannot. set s have no notion of order, concrete implementations may. however, sets implement toarray() , and if set makes guarantees order elements returned iterator, method must return elements in same order. what's underlying data structure?

objective c - Core Data Integer changing value? -

i have problem core data storing integer (i chose int16 because have maximum of 6 signs). my model holds entity: 'expense' attribute in question is: @property (nonatomic, retain) nsnumber * month; it automatically implemented nsnumber xcode (editor > createmanagedmodelsubclass) month holds short identifier every month. example 201203 //would march of 2012 i store new entities snippet: [newexpense setvalue:monthnumber forkey:@"month"]; which works fine. monthnumber has right value before store it. i retrieve objects fetching method , store them in array called allexpenses . array count true , have right amount of entities in it. now this: nsmutablearray *thismonthexpenses = [[nsmutablearray alloc]init ]; (expense *entity in allexpenses) { int tempmonth = [[entity month]intvalue]; if (tempmonth == month) { [thismonthexpenses addobject:entity]; } } to filter out right entities belong current month. month // int

XHTML rendering timeline different from HTML in WebKit? -

Image
i'm working on project went xhtml html xhtml , there definite behavioral changes going regards page rendering before css loads , scripts read styles reading them before css loads. can shed light on why following happening , can done it? basically, have page following structure: <body> <!-- content source --> <link href="http://a.example.com/style.css" /> <header>...</header> <!-- content source b --> <link href="http://b.example.com/style.css" /> <div>...</div> <!-- content source --> <footer>...</footer> <script src="http://a.example.com/script.js"> /* e.g. */ alert($('header').offset().height); </script> </body> when in html rendering mode, page blocks rendering @ expected points. when hit source css, rendering pauses (blank screen); when hit source b css, rendering pauses (header visi

python - BeautifulSoup KeyError Issue -

i know keyerrors common beautifulsoup and, before yell rtfm @ me, have done extensive reading in both python documentation , beautifulsoup documentation. that's aside, still haven't clue what's going on keyerrors. here's program i'm trying run , consistently results in keyerror on last element of urls list. i come c++ background, let know, need use beautifulsoup work, doing in c++ imaginable nightmare! the idea return list of urls in website contain on pages links url. here's got far: import urllib beautifulsoup import beautifulsoup urls = [] locations = [] urls.append("http://www.tuftsalumni.org") def print_links (link): if (link.startswith('/') or link.startswith('http://www.tuftsalumni')): if (link.startswith('/')): link = "starting_website" + link print (link) htmlsource = urllib.urlopen(link).read(200000) soup = beautifulsoup(htmlsource) item

opengl - How do I shift the hue of a LWJGL texture? -

i trying photoshop-like hue shift on texture. my code this: glcolor4f(0.0f, 1.0f, 1.0f, 1.0f); //bind texture, draw quad, etc. here picture describing happens: i can't post images yet, here's link.

c# - Compiling application using new DLL but running using old DLL -

i have application uses(does not implement) interface in separate dll. mades changes interface. application, however, not use of new features in interface. my question is: ok run application using old dll if have compiled application using new dll( new changes). it should fine under right circumstances. i had try out sure...but, in fact seem work out alright. created interface in dll, referenced in application , used reflection check methods on interface in dll. then, modified interface, recompiled both dll , application, , application able retrieve methods on interface of either old, or new dll.

Add a CSS border on hover without moving the element -

possible duplicate: css hover border makes inline elements adjust slightly i have row applying background highlight on hover. .jobs .item:hover { background: #e1e1e1; border-top: 1px solid #d0d0d0; } however, border adds 1px additional element, makes 'move'. how compensate above movement here (without using background image)? you make border exist having same color background (or transparent if don't need support older versions of ie (< 7). .jobs .item { background: #eee; border-top: 1px solid #eee; } .jobs .item:hover { background: #e1e1e1; border-top: 1px solid #d0d0d0; }

flex - Functions called in incorrect sequence, or earlier call was unsuccessful -

in application, i did trace statements of file for example if(oldfile.parent.tostring()!=file.parent.tostring()) there other file print statements , , seems encounter error stated below. error not appear every time. example ran application 20 times, encounter error once. error: error #2037: functions called in incorrect sequence, or earlier call unsuccessful. @ error$/throwerror() @ flash.filesystem::file/resolvecomponents() @ flash.filesystem::file/get parent() may not checking existence of file before calling it. refer link might full.

javascript - Use a cookie value in a getJson call -

i want use getjson call this" $.getjson("cfc/getmember.cfc?method=getuser&returnformat=json&queryformat=column",{"memberid":userid}, function(res,code) the userid stored cookie - thought i'd use: function checkcookie(){ var userid=getcookie("uid"); } now (as i'm sure cal tell) i'm new javascript might problem - i'm after advice on how use cookie value in getjson call. thanks! simon assuming getcookie() function defined , correctly retrieves cookies, need define userid before make call $.getjson: var userid=getcookie("uid"); $.getjson("cfc/getmember.cfc?method=getuser&returnformat=json&queryformat=column", {"memberid":userid}, function(res,code) {});

c# - How to execute javascript in specifci time in .cs? -

if have script : <script type="text/javascript" src="//www.gmodules.com/ig/ifr?url=http://hosting.gmodules.com/ig/gadgets/file/100080069921643878012/facebook.xml&amp;up_usenewfb_p=1&amp;up_showpopup2_p=true&amp;synd=open&amp;w=320&amp;h=500&amp;title=facebook&amp;border=%23ffffff%7c3px%2c1px+solid+%23999999&amp;output=js"></script> and wanna execute script in specific time in .cs code how this? string rowtesthide = @"<script type="text/javascript" src="//www.gmodules.com/ig/ifr?url=http://hosting.gmodules.com/ig/gadgets/file/100080069921643878012/facebook.xml&amp;up_usenewfb_p=1&amp;up_showpopup2_p=true&amp;synd=open&amp;w=320&amp;h=500&amp;title=facebook&amp; border=%23ffffff%7c3px%2c1px+solid+%23999999&amp;output=js"></script>"; clientscript.registerstartupscript(this.gettype(),"rowtest", rowtesthide);

android - Virtual keyboard does not open when dynamically inserting an EditText view into a Listview -

i'm struggeling issue drives crazy. found comparable issues in forums, not quite same one. hope has brilliant idea how solve this. or tell me i'm doing wrong. ;-) the setup: i have listview. following xml code represents child elements: <?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android = "http://schemas.android.com/apk/res/android" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:id = "@+id/container"> <edittext android:id = "@+id/child" android:layout_width = "300dp" android:layout_height = "wrap_content" /> </linearlayout> it linearlayout in turn has edittext view inside. following code adds 1 child list. since edittext view smaller linearlayout embedded, testing i've attached click listener empty space of (first) child

java - Incomplete content (buffer) of webpage -

i want read content of webpage following methods, 60-70 percent of it. i've tried 2 different methods read webpage, both same result. tried different urls. no errors or timeouts. what doing wrong ? url url = new url(uri.tostring()); httpurlconnection urlconnection = (httpurlconnection) url.openconnection(); try { inputstream in = new bufferedinputstream(urlconnection.getinputstream()); bufferedreader br = new bufferedreader(new inputstreamreader(in)); stringbuilder sb = new stringbuilder(); string line = null; while ((line = br.readline()) != null) { sb.append(line + "\n"); } br.close(); this.content = sb.tostring(); } { urlconnection.disconnect(); } and httpget = new httpget(uri); httpclient defaulthttp = new defaulthttpclient(httpparameters); httpresponse response = defaulthttp.execute(get); statusline st

Can't update Eclipse -

when want update eclipse following error: some sites not found. see error log more detail. unable connect repository http://download.eclipse.org/eclipse/updates/3.7/content.xml connection timed out: connect unable connect repository http://download.eclipse.org/releases/indigo/content.xml connection timed out: connect the available software sites are: http://download.eclipse.org/releases/indigo , http://download.eclipse.org/eclipse/updates/3.7 the version of eclipse 3.7.2 i have set proxy with window -> preferences general -> network connection there filled in proxy , can update eclipse without problems.

html - Does my ASP.NET cache store on server or browser -

in asp.net, if use: $<%@outputcache duration="3" varybyparam="*" %> or cache.insert("names", mydataset); does store cache on browser or server? know they're 2 different methods caching , there several more i'm trying find out when cache stored on client browser or on server , can find pros , cons between cache being store on either of them. this: <%@outputcache duration="3" varybyparam="*" %> may cached @ both, server or client because default location value of outputcache directive any . see here reference. now, this: cache.insert("names", mydataset); will cached on server side in application cache.

import - how can I access a .java file from another project and package? -

i have 2 projects d:\project_a\src... d:\project_b\src... now want access java file project_b via project_a. i appreciate if solution not involve clicking in ide, because should ide independent. ie.: package project_a import project_b.src.test.meow.wuff.myclass myclass x = new myclass(); you can build jar file first project , add build path of second project. can use code first project. more information can found here.

How can I set read only access to ssh git server? -

i have git repo on server can push/pull through ssh fine like: git clone ssh://user@domain.com/repositories/myrepo.git it prompts me public key passcode , i'm able fetch or push changes it, wondering if there way set people can clone read access don't have enter ssh credentials. thanks in advance! not through ssh; unless wanted distribute public log in with, , terrible idea. the way got functionality on our gitolite use git-daemon; need open new port, can specify per-repository ones serve, , can specify read-only. users clone git protocol i.e. git clone git://domain.com/repositories/myrepo.git another way set repository shared on web server directly; user access on standard http. the page on git community book here overview, along man pages git-daemon .

scheduled tasks - How to schedule a MySQL query? -

can schedule task run @ specified interval in mysql? i have inventory mysql database. structure follows: table_1 fields: itmcode, avgcost table_2 fields: itmcode(fk table_1(itmcode)), quantity the basis of report when want inventory valuation details item wise past date. the avgcost , quantity fields changed when new purchase posted system. can run query see current stock valuation, want able see stock valuation @ previous date well. how do that? quantity, can add sales , deduct purchases backwards current date until whatever date report requires, avgcost current since gets updated each time purchase posted. i wondering if automatic daily dump executed, similar this: select itmcode, quantity, avgcost, (avgcost * quantity) ttlval table_1 join table_2 on table_1.itmcode = table_2.itmcode is task possible schedule directly in mysql or there other solution? you have 2 basic options (at least): 1, take @ event scheduler first create ta

ios - Share validation code among different UITextFields -

maybe it's simple question can't figure out right way it. i have uitextfield . since need validate text inserted within text field, i'm using uitextfielddelegate method - (bool)textfield:(uitextfield *)textfield shouldchangecharactersinrange:(nsrange)range replacementstring:(nsstring *)string following: - (bool)textfield:(uitextfield *)textfield shouldchangecharactersinrange:(nsrange)range replacementstring:(nsstring *)string { // validation here // return yes or no depending on previous validation } since have text fields (they not belong same controller validation performed) , don't want duplicate text fields validation code, how can achieve elegant way centralize similar validation? don't know if subclassing right way, in case need use same delegation method (the 1 listed above) in different parts of same app. thank in advance. this depends on how information validation code requires. if arguments of textfield:shouldchangecharactersin

Point belong to Sprite in Flex -

how can know if point contained inside of sprite in flex? for example: // example point var a:point = new point(5,5); // example sprite var s:sprite = new sprite(); s.graphics.linestyle(1,0x000000,1); s.graphics.moveto(0,0); s.graphics.lineto(100,100); the point a belong sprite s because position inside of it. there function know it? i want kind of sprites, use math formulas calculate linear or quadratic equations (line, circle, rectangle, etc) not valid me. thanks in advance you can use function hittestpoint(x, y) on sprite

.net - Posting Arabic Characters in Twitter using Twitter API in C# using OAuth -

i trying post arabic characters twitter using twitter api, not work in default format, string arabicenglish = "عربي/عربىhello"; i used string tweet = httputility.urlencode(arabenglish); but not work, used library converts &# 1593;&# 1585;&# 1576;&# 1610;/&# 1593;&# 1585;&# 1576;&# 1609;hello this works fine, if message gets long, overlimits twitter 140 limit. so let me know whats best way send arabic, , count 1 arabic char = 1 english char, , workable on twitter. i not sure right link guy talking same thing you've asked. check here . here link might interest you.

How do I wrap an element's contents in another element in jQuery -

i have simple tag html <ul> <li>something1</li> <li>something2</li> <li>something3</li> <li>something4</li> </ul> how make if use jquery? <ul> <li><a href="#">something1</a></li> <li><a href="#">something2</a></li> <li><a href="#">something3</a></li> <li><a href="#">something4</a></li> </ul> wich 1-4 defined? i'd suggest reading through jquery api : $('li').wrapinner('<a href="#"></a>');

Data sovereignty vs Azure hosting options -

i'm learning azure forgive me naivety. work federal government hesitant have applications , data hosted in country. local company offer "azure" services? i.e. software developers in government department build applications , deploy them azure cloud, ensuring data stays within country? or have @ non-microsoft cloud provider? data , compute reside in datacenter specify. blobs, tables , queues backed automatically paired data center: san antonio <--> chicago dublin <--> amsterdam hong kong <--> singapore you can opt-out of cross-datacenter data backup if data sovereignty becomes issue. once opted-out, data in specified data center, , you'd need handle dr on own (by possibly backing data on-premises storage). aside 6 datacenters, fujitsu runs windows azure data center in japan. see this press release more info.

Android: allow portrait and landscape for tablets, but force portrait on phone? -

i tablets able display in portrait , landscape (sw600dp or greater), phones restricted portrait only. can't find way conditionally choose orientation. suggestions? here's way using resources , size qualifiers . put bool resource in res/values bools.xml or whatever (file names don't matter here): <?xml version="1.0" encoding="utf-8"?> <resources> <bool name="portrait_only">true</bool> </resources> put 1 in res/values-sw600dp , res/values-xlarge: <?xml version="1.0" encoding="utf-8"?> <resources> <bool name="portrait_only">false</bool> </resources> see this supplemental answer adding these directories , files in android studio. then, in oncreate method of activities can this: if(getresources().getboolean(r.bool.portrait_only)){ setrequestedorientation(activityinfo.screen_orienta

Android: add custom fonts to system -

i know how use custom font in app, want adding custom fonts system-wide, adding new font on windows. if there's no official way, module of android source code should read? have change android source code , build support custom fonts. here steps add custom font android build-in system: + copy custom font .ttf frameworks/base/data/fonts + modify framworks/base/data/fonts/android.mk add custom font list of 'font_src_files' font_src_files := \ roboto-regular.ttf \ .... androidclock_solid.ttf \ <custom_font>.ttf \ + modify frameworks/base/data/fonts/fonts.mk add custom font list of product_packages product_packages := \ droidsansfallback.ttf \ ... androidclock_solid.ttf \ <custom_font>.ttf \ + rebuild note: check if custom font exists in out/target/product/generic/system/fonts or not. if yes, custom font have included in system. if no, recheck modification.

extjs - Ext JS 4: Filtering a TreeStore -

i posted on sencha forums here didn't responses (other own answer, post soon), going repost here , see if anymore help. i've been racking brain on how filter treestore in 4.0.7. i've tried following: the model ext.define('model', { extend: 'ext.data.model', fields: [ {name: 'text', type: 'string'}, {name: 'leaf', type: 'bool'}, {name: 'expanded', type: 'bool'}, {name: 'id', type: 'string'} ], hasmany: {model: 'model', name: 'children'} }); the store ext.define('mystore', { extend: 'ext.data.treestore', model: 'model', storeid: 'treestore', root: { text: 'root', children: [{ text: 'leaf1', id: 'leaf1', children: [{ text: 'child1', id: 'child1', leaf: true },{ text: 'child2', id: 'c

c# mvc expression to html -

alright, here's deal. able create custom dropdown box system.linq.expressions.expression in c#. know there helpers, dropdownlistfor , i'm not sure how make 1 scratch, or how pull values etc expression. essentially why i'm doing if use dropdownlistfor 'select' <option> based on it's value , want 'select' option based on it's text instead. if has idea how instead, great. this have far public static mvchtmlstring validatededitabledropdownlistfor<tmodel,tproperty>( htmlhelper<tmodel> htmlhelper, expression<func<tmodel, tproperty>> expression, selectlist list, string defaultoption, object attribs) { //basically puts strings html template<div>{0}{1}</div> etc. return getvalidatedhtml( htmlhelper.labelfor(expression).tostring() , htmlhelper.dropdownlistfor(expression , list , defaultoption , attribs).tostring() ,htmlhelper.getvalida

php - IMAP IDLE monitoring service with http callback? -

i have small web app polls imap mailbox (via php's imap module) every minute via cronjob. i'd make more realtime, maximum 1 minute lag unacceptable in cases. is there service out there connect imap mailbox, use imap idle monitor messages, post exhaustive message data (headers, content) url? sort of twilio incoming phone calls? i don't know of service describe, suggest turning script have daemon. if wanted, using pcntl extension . instead, utilize class has set , ready go: http://kevin.vanzonneveld.net/techblog/article/create_daemons_in_php/ using class, can create "daemonized" version of script easily: require_once "system/daemon.php"; // include class system_daemon::setoption("appname", "mydaemon"); // minimum configuration system_daemon::start(); // spawn deamon! (sample code page daemon class)

html - <p> tag not working in <div> -

i trying add word "invitations" top right of page aligned "back photos" link. however, when add new <div> start <p> paragraph not align page @ once apply css. i have uploaded page having trouble: http://ashliamabile.com/invitations.html this worked me: html: <div id="backtophotos"> <a href="print.html"><img src="images/backprint.png" border="0"></a> <p class="title">invitations</p> </div> css: /*drop width property , set div position:relative */ #backtophotos { height: 20px; /* removed width */ background-repeat: no-repeat; margin: 0 0 0 100px; position: relative; /* set positon relative */ } /* set title p position absolute , remove margins: */ .title { position: absolute; right: 0; top: 0; margin: 0; } the above works because div width "set" outer div, need worry top right corner i

iphone - Why does UIImageview show a blurry image? -

i testing app in 2 devices. 1 ios 4.3, , other has ios 5. app built in ios 4.3. why images blurry when run in ios? do need take care when apps run on ios 5? you may facing issue of anti-aliasing applied when view's frame fractional (particularly origin, rest adjusted accordingly). use cgrectintegral recalculate uiimageview frame. this similar question (not of uiimages) reason seems similar.

html - CSS auto-increment block width -

i've been trying learn basic css/html making myself static web page. @ bottom of page want show few 32x32 image icons of websites go to. i want display them inline , put them in center of page. right have 3 icons created block of width 96 (= 32x3) , center container block. however think there's chance i'll need add more icons list, means every time new icon added, need recalculate width of container block. i'm wondering if there rule in css save me doing that? for example text-align: center text field regardless of how many words put in there. there similar image blocks? thanks much! update as in cbp's answer, text-align works img tags. pointing out! however (sorry not having made clear before), didn't use <img> rather <a> css setting background images. guess 2 follow-up questions: 1) text-align: center still apply here? 2) preferable use <a> (with css background-image) on raw html <img> ? advantage use either?

c# - asp.net mvc 3 model binding dropdown -

i have view form. on form have textboxes , 2 dropdownlists. this viewmodel. public class newapplicationviewmodel { public applicationdata application { get; set; } //selectlists public selectlist questionnaires { get; set; } public selectlist jobs { get; set; } } the applicatoindata class looks this public class applicationdata { [hiddeninput(displayvalue = false)] public guid id { get; set; } [required] public applicantdata applicant { get; set; } [required] public questionnairedata questionnaire { get; set; } [required] public jobdata job { get; set; } public string pdf { get; set; } } the "questionnaire" , te "job" have selected dropdownlists. how can bind selected value in dropdown object in "applicationdata"? complete, controller action hande form submit. [httppost] public actionresult newapplication([bind(prefix="application")]applicationdata model) {

java - Automatic conversion of `for (int i=0;i<list.size();i++)` to enhanced for / for-each loops? Find enhance-able for loops? -

i refactored small part of large project grown on years have methods accept collection list required. this, had rewrite code à la for (int i=0; < somelist.size(); i++) { sometype element = somelist.get(i); somemethod(element); // ... more code not using // or just: somemethod(/*other args */ somelist.get(i)); } to for (sometype element: somelist) { somemethod(element); // ... more code not using } since there many more occurrences of pattern, wonder whether there way automatically convert old-style loop enhanced one, or @ least report loops can converted? ( pmd:avoidarrayloops - using sonar code analysis - similar arrays, few false positives) i imagine regular expression might help, not consider myself well-versed enough handle part of establishing loop variable used in get method of list size checked in termination expression. if using eclipse: menu window > preferences , java > code style > clean up . edit profile ta

Replace string with regex in javascript -

i have following text inside javascript string variable: here text page.title = "info åäö"; here more text i need target following , placed in javascript variable (including quotes): page.title = "info åäö"; so can manipulate this: page.title = " other info 123"; and replace , put string looks this: here som text page.title = "some other info 123"; here more text the "page.title =" same last semicolon, string between quotes, like: "info åäö"; can vary so how can best target , change string string? this tried: strfind = /page.title = [a-z]+/; strhtml_value = here text page.title = "info åäö"; here more text strtobereplace = strhtml_value.match(strfind)[1] alert(' strtobereplace ' + strtobereplace); // = page.title = "info åäö"; strnewvalue = page.title = "some other info 123"; strhtml_value = strhtml_value.replace(strtobereplace, strnewvalue);

google app engine - Can I save an item to Datastore with 0 write operations on indexes? -

the number of datastore write operations takes persist entity 1 + number of indexes . what if update existing entity , indexed fields not changed. how many write operations take? possible save existing item 1 write op. if indexes not affected? the short answer no. if want search field, needs indexed, , have pay per write. on each entity write, entire entity written, , datastore doesn't know whether changed indexed field or not. if you're worried costs, can create fields not indexed. unindexed fields not add write ops. however, can't search unindexed fields: http://code.google.com/appengine/docs/python/datastore/queries.html#unindexed_properties you can manually set property unindexed, write entity, , set indexed again afterwards. practically useless , bunch of effort, , not you're looking for. sounds want use old index, technique blow away index, , particular entity won't indexed (and won't turn in search results), while others of same k

asp.net - How to get Selected Date on Infragistic WebMonthCalendar Control on client side -

hi im using infragistic first time, set selection mode multi , want concatenate selected dates in hidden field , use client side event handle function webmonthcalendar1_selectionchanged(sender, eventargs) { ///<summary> /// ///</summary> ///<param name="sender" type="infragistics.web.ui.webmonthcalendar"></param> ///<param name="eventargs" type="infragistics.web.ui.calendarselectionchangedeventargs"></param> var days = sender.get_selecteddate; alert(sender); //add code handle event here. } but return function definition text not sleected date, please kindly me how can select perticular date . not expert in javascript, call should be var days = sender.get_selecteddate(); note parenthesis @ end.

javascript - Lesscss Mixins with guards. Syntax Error -

i write css lesscss using on client side (with compiler less.js). there examples guards usage in documentation, don't work me. can't understand, why... code example goes here: @import "common-functions.less"; // variables @minheaderwidth: auto; @maxheaderwidth: 1200px; @minbuttonswidth: 50px; @maxbuttonswidth: 75px; // mixins guards .applyheaderstyles(@headerwidth, @buttonswidth) when (ispixel(@headerwidth)) { .my-headerelement { width: @headerwidth; } } .applyheaderstyles(@headerwidth, @buttonswidth) when not (ispixel(@headerwidth)) { .my-headerelement { width: @headerwidth; margin: 0 @buttonswidth; } } // use .applyheaderwidth in @media queries @media screen , (min-width: 1050px) { .applyheaderstyles(@maxheaderwidth, @maxbuttonswidth); .my-buttonelement {width: @maxbuttonswidth;} } @media screen , (max-width: 1049px) { .applyheaderstyles(@minheaderwidth, @minbuttonswidth); .my-buttonelement {width

Python - splitting a log and searching for something specific -

i have assignment , wondering if help. part of question required analyse system log. log contains information such time , date, if root access attempted , ip address attempt came from. my question is: how loop through log , pull out ip addresses. myfile = open('syslog','r') line in myfile.readlines(): list_of_line = line.split(' ') so here i've split list how can loop through trying locate ip address. have used locations isn't practical looks 1 address. want search through , find addresses mean looking strings length e.g. xxx.xxx.xx.xx ip address , specify looking numeric values. edit- jan 10 09:32:07 j4-be03 sshd[3876]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=218.241.173.35 user=root jan 10 09:32:09 j4-be03 sshd[3876]: failed password root 218.241.173.35 port 47084 ssh2 jan 10 09:32:17 j4-be03 sshd[3879]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhos

django - prepopulated field and function() -

as per understanding, pre-populated fields shouldn't include foriegnkey. thought of workaround. in model .. defined function name getname() def getname(self): t1 = str(self.team_one) t2 = str(self.team_two) t1t2 = t1 + ' vs ' + t2 return t1t2 and thought of calling in admin .. how doing it. prepopulated_fields = { 'name': ('getname()',)} it should solve problem, django says. exception type: improperlyconfigured exception value: 'fixtureadmin.prepopulated_fields['name'][0]' refers field 'getname' missing model 'fixture'. is there work around it, or should drop idea? //mouse prepopulated_fields slugs; it's not generalized way give field default value. you'll have write own javascript this. following should trick: $('#id_team_one, #id_team_two').change(function(){ var $team1 = $('#id_team_one'); var $team2 = $('#id_team_two'); if ($t

c# - Getting table name within mstest unit test with data from Microsoft Test Manager -

i have test methods decorated datasource attribute like: [datasource(provider_invariant_name, connection_string, "test case#", dataaccessmethod.sequential), testmethod] with test case number in mtm replacing "test case#". i'm trying number within unit test testcontext.datarow.table.tablename "table1". can tell me how real value? unless i'm wrong, "testcase#" cannot replaced mtm, propably have manually added in datasource attributes. this value constant . why don't add constant variable testclass , use on both datasourceattribute , testmethod ? edit can access datasourceattribute directly: [testclass] public class testclass { public datasourceattribute datasource { { return (datasourceattribute)attribute.getcustomattribute(typeof(testclass). getmethod("testmethod"), typeof(datasourceattribute)); } } [datasource(provider_

asp.net membership - How do I use the built-in password encryption in the MembershipProvider? -

i writing custom membershipprovider. of course want encrypt password user creates. presume .net has encrypts passwords. , how use it? size of string output? have written membership providers before, has been verify user valid. first time need add user registration , login. i sure not using right search terms, google has not shown me of value me. first of shouldn't encrypt passwords. should hash them (there's forever going debate this). for hashing passwords use hmacsha1 . example when create user , before store password: hmacsha1 hash = new hmacsha1(); hash.key = youkey; // use machine key encodedpassword = convert.tobase64string(hash.computehash(encoding.unicode.getbytes(password))); and store value in database. can compare entered password hashing , comparing hashed values. of course need specify password hashed in config file: <membership defaultprovider="sqlprovider" userisonlinetimewindow="20"> <providers> &

Wake Up Sequential Workflow Service -

Image
i need able "wake up" sequential workflow service - , concept worked in state machine i'm not understanding why doesn't work in sequence. below picture of workflow. this workflow used orchestration of other workflow services. literally needs run forever - need ability shut down softly. had same type of thing implemented in state machine, delay trigger 1 transition , receive trigger another. long first mentioned transition wasn't running able receive take message , transition final state. here want do, can see, set boolean value false indicating while loop should exit , workflow terminate. please me understand why isn't working. thanks all! edited diagnostic output 32: activity [1] "main sequence" scheduled child activity [4] "while" 33: activity [4] "while" executing { variables continuerunning: true } 34: activity [4] "while" scheduled child activity [6] "visualbasicvalue<boolean>&

c# - Mono getting node position in TreeView -

i need node position in gtk.treeview . i'm able row , user changed, have hardcore column, there way how it? here's code: private void artistnamecell_edited (object o, gtk.editedargs args) { gtk.treeiter iter; musicliststore.getiter (out iter, new gtk.treepath (args.path)); song song = (song) musicliststore.getvalue (iter, 0); song.artist = args.newtext; } it's here http://www.mono-project.com/gtksharp_treeview_tutorial , it's editable text cells section. in code select column number 0:-/, need whatever column user clicks. respectively exact node position node[row,column] , have node[iter,0] . i ran sample program gtkdemo comes mono framework on windows (the samples directory), , edit treeview editable cells samples, paste code handles event, private void textcelledited(object o, editedargs args) { treepath path = new treepath(args.path); treeiter iter; store.getiter(out iter,path); int = path.indices[0]; item foo = (item)articles[