Posts

Showing posts from August, 2010

python equivalent to java guava Preconditions -

does python have equivalent java preconditions library. e.g. in java, can check parameters this: public void dummymethod(cat a, dog b) { preconditions.checknotnull(a, "a can not null."); preconditions.checknotnull(b, "b can not null."); /** logic **/ } if or b null, java throws runtime exception, how python, what's best practice here python? while can use assert verify conditions, best practice in python document behaviour of function, , let fail if preconditions not met. for example, if reading file, like: def read_from_file(filename): f = open(filename, 'ru') # allow ioerror if file doesn't exist / invalid permissions rather testing failure cases first.

list - Java: Fastest structure to store and retrieve large number of strings -

i need create java structure store large number of string . need add new strings , check if string present... order of strings not important. i don't know many java datatypes typical list , set , map , so... fastest datatype scenario? may treeset or there other i'm missing? it depends on kind of access need. sequential: linkedlist<string> random: arraylist<string> check presence: hashset<string> (this 1 looking according reqs) check presence , sorted traversal: treeset<string>

In Django, how can I access a parameter in a template? -

from view i'm doing following: return render(request, 'yabe/login.html', {'error': true}) in template i'm trying {% if error %} <div class="error">authentication error. please try again</div> {% endif %} but it's not working if you're using django.shortcuts.render should work. problem might have contextmanager overriding context variable. try this: your view: from django.shortcuts import render def your_view(request): ... return render(request, 'yabe/login.html', {'errorusedjusthere': true}) your template: {% if errorusedjusthere %} <div class="error">authentication error. please try again</div> {% endif %} extra. use django debug toolbar see variables set in context.

WordPress Multiple Loops Confusion -

i have multiple loops want display on wordpress blog. categories follows: top-story (1 per page) small-story (1 per page) normal (1 per page) quickfill (2 per page) i've got 4 loops display these. i'm trying display amount of posts per page , once they've been displayed, don't show them again on page, don't want show duplicates. my loops follows. seem getting duplicates , when i'm trying them remove duplicates tend remove without knowing how. top story - 1st loop <?php global $do_not_duplicate; $do_not_duplicate = array(); $paged = max(1, get_query_var('paged')); $my_query = new wp_query('category_name=top-story&posts_per_page=1&paged='.$paged); while ($my_query->have_posts()) : $my_query->the_post(); $do_not_duplicate[] = $post->id; ?> // content <?php endwhile; ?> small-story - 2nd loop <?php $my_query = new wp_query('c

sharepoint crawl rule to exclude AllItems.aspx , but get an item/document in search resu lts if queried in the search box -

i followed blog tips 1 and created crawl rule http://.*forms/allitems.aspx , ran full crawl. no longer results allitems.aspx. however, if there document name something.doc in document library , no longer gets pulled in search results. i think desire basic functionality, user should not see allitems.aspx in search results should item/document names entered in search box. please let me know if missing anything. have put in 24 hours...googled max could. it seems index reset required. here's steps did: 1. add following crawl rule exclude: *://*allitems.aspx. 2. index reset. 3. full crawl.

javascript - TinyMCE Full Screen Command Not Working -

according find on net, put tinymce editor full screen mood automatically need this. oninit: function () { tinymce.get('editingarea').execcommand('mcefullscreen'); } however it's not working me. any ideas may doing wrong? js fiddle example : http://jsfiddle.net/g3k5m/1/ it turns out problem occuring because using latest version. tinymce 4. i switched 3.x , tried out. works perfectly. so i'm going switch 3.8 version until 4 stabilized , these features readily available there.

d3.js - Drawing map with d3js from openstreetmap geojson -

hy i'm trying draw svg d3.v3.js geojson. fetch geojson openstreetmap(my test data: http://pastebin.com/4gqne42i ) , try render svg. my js code: var path, vis, xy, jdata; xy = d3.geo.mercator().translate([0, 0]).scale(200); path = d3.geo.path().projection(xy); vis = d3.select("body").append("svg").attr("width", 960).attr("height", 600); //22.json name of file contains geojson data d3.json("22.json", function(error, json) { jdata = json; if(error!=null) console.log(error); return vis.append("svg:g") .selectall("path") .data(json.coordinates) .enter().append("path") .attr("d", path); }); and somehow svg result this: <svg width="960" height="600"> <g> <path></path> </g> </svg> i know projection not good, think svg should have nodes.

http - Java get the default proxy -

is there way "behind-the-scenes" proxy in java? 1 specified http.proxyhost , http.proxyport . if do: url url = new url("http://google.com"); httpurlconnection con = (httpurlconnection) url.openconnection(); it automatically connects through values set above. can specify proxy ( httpurlconnection con = (httpurlconnection) url.openconnection(proxy.no_proxy); ). how can specify default proxy? for example, have method , want open connection "default proxy" (which same thing proxy.no_proxy if http.proxyhost , http.proxyport aren't set)? use (httpurlconnection) ((proxy == null) ? url.openconnection() : url.openconnection(proxy)) but there away do (httpurlconnection) url.openconnection(proxy == null ? [the default proxy] : proxy) i tried getting default proxy with public static proxy getcurrenthttpproxy(proxy defaultproxy) { string proxyhost = system.getproperty("http.proxyhost"); string proxyport = system.getprop

oracle11g - Converting integer value from a db column to text in oracle -

i have requirement in db. 1).table abc, column: check_amount number number(18,4) . contains check amount eg. 3000.50 paid employee. now cheque issued , check contains check_amount in number in text form.for eg.check have: pay <emplyee_name> ****$3000.50**** ****three thousand dollars , fifty cents**** i have generate text using db column value , display on check. can me out, how can achieve in oracle 11g ? hint:i have heard of julien format, not working. suggestions appreciated. from nalin since julian format works whole numbers, can separate decimal parts , apply julian format trick separated numbers. here's simple demo. declare x number (8, 2) := 1253.5; y number; z number; begin y := floor (x); z := 100 * (x - y); dbms_output.put_line (to_char (to_date (y, 'j'), 'jsp')); if (z > 0) dbms_output.put_line (to_char (to_date (z, 'j'), 'jsp')); end if; exception when oth

My requirement is to read the data from google spreadsheet, then format (apply some styles) to the data, add some images to the data and fin -

google app script: looking customized pdf report using google app script. requirement follows read data google spreadsheet (not in spreadsheet, required) , display table. prepare report merging above spreadsheet data , additional data (headers, images). apply styles data. add images data. convert pdf. please me.

c++ - Access violation reading in FeatureDetector OpenCV 2.4.5 -

i tried sample codes matching many images in opencv 2.4.5 , modified code. found error code: unhandled exception @ 0x585a7090 in testing.exe: 0xc0000005: access violation reading location 0x00000000. its fault @ featuredetector->detect(queryimage, querykeypoints) . i can't find solution problem. please me. #include <opencv2\highgui\highgui.hpp> #include <opencv2\features2d\features2d.hpp> #include <opencv2\contrib\contrib.hpp> #include <iostream> #include <fstream> #include <conio.h> #include <string> using namespace std; using namespace cv; static void readtrainfilenames(const string& filename, string& dirname, vector<string>& trainfilenames); static bool readimages(const string& queryimagename, mat& queryimage); static bool readtrainimages(const string& trainfilename, vector<mat>& trainimages, vector<string>& trainimagenames); static void detectkeypoints(const mat& q

c++ - How can I create another thread in the v8 -

i want set timeout v8::script::run. unfortunately,i have little experience v8. understood need use startpreemtion + loker + terminateexception. consequently, v8::script::run should in separate thread. calculation , control of execution time should in main thread. how can create thread in v8?. please me understand how it. here example of code it, function of thread doesn't start. v8::local<v8::value> v8executestring( v8::handle<v8::string> source, v8::handle<v8::string> filename ) { // compiling script // ... // end compiling script dword start_tick = ::gettickcount(); v8::locker::startpreemption( 1 ); { v8::unlocker unlocker; boost::thread* th = new boost::thread( [&] () { v8::locker locker; v8::handlescope handle_scope; // running script // v8::script::run() // end running script }); } // calculation , control of execution time

php - nusoap wsdl connection error but in telnet test everything is OK -

i use nusoap connect url, cannot connect , didn't error in $soapclient->geterror() . i can connect url via ssh commant , telnet, url show xml data on browser , seems ok php cannot connect! i think have problem in php.ini configuration ! can me solve problem ? when trying echo $soapclient; content : object(nusoap_client)#25 (50) { ["username"]=> string(0) "" ["password"]=> string(0) "" ["authtype"]=> string(0) "" ["certrequest"]=> array(0) { } ["requestheaders"]=> bool(false) ["responseheaders"]=> string(0) "" ["responseheader"]=> null ["document"]=> string(0) "" ["endpoint"]=> string(60) "https://******?wsdl" ["forceendpoint"]=> string(0) "" ["proxyhost"]=> bool(false) ["proxyport"]=> bool(fal

playframework - Play 2 thread pools : default pool VS Akka Pool with Java -

according documentation, easier way use actor : promise promiseofint = akka.future( new callable() { public integer call() { return ... ; } } ); but doc says java api use same thread pool (play default thread pool). the documentation says there akka pool actors. how can send actor tasks akka thread pool, not block common user actions? able tune akka pool , keep default pool small. thanks, loic the java akka plugin ( play.libs.akka ) forwards scala plugin ( play.api.libs.akka ), in turn starts new actor system based on app's configuration. (that's plugin does.) so configure actorsystem , dispatchers (a dispatcher executioncontext) using normal application.conf file based on akka config key. these dispatchers thread pools documentation referring to. the default thread pool used when import play.api.libs.concurrent.execution.default . scala-only api. in java, executioncontext used automatically touch futures , promises. th

c# - How to show only the active computers in a listview? -

i have listview called lvinformation , want add active computers in remote network. take many seconds when response if it's active. want multithreaded, should add computer listview when it's active , refresh listview . don't know how. i'm using following code , that's working takes many seconds... system.net.networkinformation.ping objping = new system.net.networkinformation.ping(); objping.sendasync(_remotecomputername, null); objping.pingcompleted += new pingcompletedeventhandler(objping_pingcompleted);; private void objping_pingcompleted(object sender, pingcompletedeventargs e) { domaincomputers.add(_remotecomputername); } domaincomputers property , that's binded twoway. you may try this: public partial class mainwindow : window { public mainwindow() { initializecomponent(); } public observablecollection<string> domaincomputers = new observablecollection<string>()

Getting Image Dimentions ONLY from a folder inside another folder which is in Assets saving maximum Memory in Android -

i need image dimensions folder inside folder in assets folder. have tried codes unable save memory i.e don't want load image memory want dimensions of files in folder. here code using not memory efficient don't want load bitmaps. private void getfilenames() { assetmanager assetmanager = mcxt.getassets(); inputstream bitmap; bitmap bit; log.d("jawad"," in function"); // names of files inside "files" folder try { string[] files = assetmanager.list(mfolferpath); log.d("jawad"," length "+files.length); for(int i=0; i<files.length; i++) { if(files[i].contains(".png") ||files[i].contains(".jpg")) { log.d("jawad","" +files[i]); bitmap=assetmanager.open(mfolferpath+"/"+files[i]); bit=bitmapfactory.decodestream(bitmap); log.d("jawad

Django Template not being rendered correctly using Class based views -

i'm django newbie , wanted integrate singly django polls application. have used class based views allow models singly app passed along polls models. the problem is, i'm unable data singly model when data present inside database. for want display access_token , profile id of user profile. here views.py code: (only view in question) class indexview(listview): context_object_name='latest_poll_list' queryset=poll.objects.filter(pub_date__lte=timezone.now) \ .order_by('-pub_date')[:5] template_name='polls/index.html' def get_context_data(self, **kwargs): context = super(indexview, self).get_context_data(**kwargs) context['user_profile'] = userprofile.objects.all() return context this urls.py: urlpatterns = patterns('', url(r'^$', indexview.as_view(), name='index'), url(r'^(?p<pk>\d+)/$', detailview.as_view(

asp.net - How can I set a label form database -

i want set label out database. query: string strquery = "select * contacts user='" + strselecteduser + "'"; sqlcommand command = new sqlcommand(strquery, global.myconn); sqldataadapter da = new sqldataadapter(command); da.fill(global.ds, "tabel"); now want set label lblcontact.text=......[column database = name]....? how do that? please use blow code set label value database. first check query retuning value assign value label text if(global.ds.tables["tabel"].row.count>0) { lblcontact.text=global.ds.tables["tabel"].rows[0]["colomn_name"].tostring(); }

c# - stored Procedure usage in ASP.NET -

i using storedprocedure in sqlserver 2005. stored procedure: create proc usegetasp @partycode nvarchar(50) select * partyregister partycode=@partycode go i trying execute asp.net visual studio 2010. by researching code came know should use cmd.commandtype = commandtype.storedprocedure but unfortunatly commandtype.storedprocedure not there , not working. hence used: cmd.commandtype = sqldatasourcecommandtype.storedprocedure; but not working. shows me red line below [as comes when type invalid]. tooltip shows me error as: commandtype not exists in current context my full code: con.open(); cmd = new sqlcommand("usegetasp",con); //cmd.commandtype =commandtype./*not working*/ cmd.commandtype = sqldatasourcecommandtype.storedprocedure;/*also not working*/ cmd.parameters.addwithvalue("@partycode","0l036"); what mistake? what command should use implementing stored procedure? please me. try this: system.data.commandtyp

objective c - switch for a TabBarView without StoryBoard -

i have connectionviewcontroller , when click on test button, switch tabviewcontroller. in connectionviewcontroller : - (ibaction)testbutton:(id)sender { tabbarviewcontroller *tabbarviewcontroller = [[tabbarviewcontroller alloc] init]; [self presentviewcontroller:tabbarviewcontroller animated:yes completion:nil]; } but when click on test button, tabbarview black, without anything. what fix ? modal segue, not push. thx lot [edit] : solution create custom segue class customsegue.m method : -(void) perform { connectionviewcontroller *src = (connectionviewcontroller*) self.sourceviewcontroller; tabbarviewcontroller *dest = (tabbarviewcontroller*) self.destinationviewcontroller; [uiview transitionwithview:src.navigationcontroller.view duration:0.2 options:uiviewanimationoptiontransitionflipfromleft animations:^{ [src presentviewcontroller:dest animated:yes completion:null]; } completion:null]; } the reaso

c++ - How do I use STL algorithms with ICU's iterators? -

i wonder how use icu library iterators stl. instance, if decided output permutations of string? with std::string looks following: #include <iostream> #include <string> #include <algorithm> using namespace std; static void _usage(const char *executable) { cout << "usage: " << executable << " <string>" << endl; } int main (int argc, char const* argv[]) { if (argc < 2) { cerr << "target string expected" << endl; _usage(argv[0]); return 1; } string s(argv[1]); { cout << s << endl; } while (next_permutation(s.begin(), s.end())); return 0; } i tried same using icu : #include <unicode/unistr.h> #include <unicode/uchriter.h> #include <unicode/ustdio.h> #include <algorithm> #include <string> #include <iostream> using namespace std; static void _usage(const char *executable) {

iphone - How to Create Tab bar programmatically from second viewcontroller -

i developing application contains login page. first page should login page (with view controller). once user has logged in going show view need show tab bar, when user logs out same login screen has shown. how can achieve this? you create tabbarcontroller in appdelegete class.when user login set appdelegete tabbarcontroller rootviewcontroller of window. appdelegate *appdelegate = (appdelegate *) [[uiapplication sharedapplication] delegate]; [appdelegate.window setrootviewcontroller:appdelegate.tabbarcontroller];

graphics - C# Panel is flickering. When I try CreateParams, the situation is much worse -

the title pretty says it. have panel inside of form. have lots of shapes in panel bounce off of each other. more shapes have worse flickering is. after searching on site awhile added constructor this.setstyle(controlstyles.allpaintinginwmpaint | controlstyles.userpaint | controlstyles.doublebuffer, true); then found should add this protected override createparams createparams { { createparams cp = base.createparams; cp.exstyle |= 0x02000000; // turn on ws_ex_composited (child control double-buffering) return cp; } } after added screen flickered worse. it's not fair flickered. of time blank , every once in while shapes flash briefly. code paint shapes looks this. pnl.refresh(); graphics g = pnl.creategraphics(); for(int = 0; < numofshapes; i++) { rectangle myrect = shapelist[i]; g.fillrectangle(new solidbrush(color.black), myrect); } edit: i don't know why can't last bit of code right. sorry that. i'm refreshing pa

Create XML file dynamically in Iphone -

i want create xml file dynamically iphone application. tried using nsxmldocument nsxmldocument not declared in iphone application. please me in doing so. thanks gaurav try open source xml stream writer ios : written in objective-c, single .h. , .m file one @protocol namespaces support , 1 without example: // allocate serializer xmlwriter* xmlwriter = [[xmlwriter alloc]init]; // start writing xml elements [xmlwriter writestartelement:@"root"]; [xmlwriter writecharacters:@"text content root element"]; [xmlwriter writeendelement]; // resulting xml string nsstring* xml = [xmlwriter tostring]; this produces following xml string: <root>text content root element</root>

git extensions - How to create a Git Tag using GitExtensions for Windows? -

Image
i want create tag current version. don't see option in windows context menu... context menu -> gitex browse right click on commit -> create new tag

security - About Java Access Specifier Binding -

in interview, asked me: when java access specifier (public, default, protected, private) bind java code? binding or late binding?? said: binding. said: need security during runtime. how achieved? don't know. please help. , in advance..... 1) answer first question right. type check done @ compile time (early binding). because java statically typed . 2) when questioner talks run-time security, think must talking run-time code security, access resources, alien code access/restrictions, encryption, cryptography, sandbox etc. read this. overall overview. give nice, clear , crisp head-start >> http://docs.oracle.com/javase/7/docs/technotes/guides/security/overview/jsoverview.html and go details, subject subject >> http://docs.oracle.com/javase/7/docs/technotes/guides/security/index.html

c# - Excel AddIn : Hide a datafield in a pivottable -

i'm trying control excel (2010) pivottable vsto (excel addin) in c# (4.0). i've got no problem adding pivotfields (dimensions) , datafields (measures) pivottable. problem can't remove datafield. my datafield pivotfield object. i've tried : mydatafield.hidden = true; mydatafield.displayinreport = false; mydatafield.orientation = xlpivotfieldorientation.xlhidden; // last 1 use remove (dimension) pivotfield every 1 of these lines throws com exception absolutely no information in it. thing have message : "exception de hresult : 0x800a03ec", seems common every vsto exception. if has solution, me lot. ever tried unhide again? can't it... datafieldorderbookamount.orientation = xlpivotfieldorientation.xldatafield always throws me error!

Uploading files greater than 2GB in ASP.NET MVC 3 -

i trying upload video files larger 2gb on asp.net mvc 3 project maximum file upload size asp.net 4.0 seems @ 2gb. there way exceed limitation in asp.net/iis? or approach around this? i using uploadify file upload control. , resources achieving appreciated. cheers according experience there no way upload file on 2gb in single request. there 2gb limitation in iis, , there no workaround. in .net 4.0 , earlier there 2gb (some people 4gb) limitation in asp.net, was fixed in .net 4.5 . fix makes little sense because iis not support file uploads on 2gb. the way upload files on 2gb iis-hosted server break pieces , upload piece piece. here clients can upload breaking file segments: it hit ajax file browser sample webdav browser note these clients require server support put range header. another solution create httplistener-based server. httplistener has less functionality comparing iis not have upload limitations.

(C) Getting the 3 minimum elements of an row in a matrix, and choose one randomly -

i've 8x8 matrix, , after choosing row desire, want 3 minimum elements of it, , choose 1 of 3 randomly. thing i'dont know how handle 3 elements. know how minimum element, following code. int piezas[8][8] = { 0, 2, 2, 5, 3, 2, 1, 1, 0, 4, 5, 2, 4, 3, 0, 0, 0, 4, 2, 2, 1, 2, 3, 2, 0, 3, 1, 5, 1, 2, 3, 4, 2, 5, 6, 5, 3, 1, 2, 7, 8, 2, 0, 0, 0, 2, 1, 1, 1, 2, 2, 1, 1, 6, 3, 4, }; int myrow = 3; // row want analyze int index; int min=0; (index=0;index<8;index++) { printf("%d", piezas[myrow][index] ); if(piezas[myrow][index]<min) min=piezas[myrow][index]; printf("\t\t"); } printf("min: %d", min); the output want have is, if initial matrix is: int piezas[8][8] = { 0, 2, 2, 5, 3, 2, 1, 1, 0, 4, 5, 2, 4, 3, 0, 0, 0, 4, 2, 2, 1, 2, 3, 2, 0, 3, 1, 5, 1, 2, 3, 4, 2, 5, 6, 5, 3, 1, 2, 7, 8, 2, 0, 0, 0, 2, 1, 1, 1, 2, 2, 1, 1, 6, 3, 4, }; and choose row number 3: 0, 3, 1, 5, 1, 2, 3, 4, the algorithm must choose 0, 1,

r - How to suppress correlation table in LME? -

in standard example of lme() function in nlme package of r: fm2 <- lme(distance ~ age + sex, data = orthodont, random = ~ 1) summary(fm2) there appears correlation table: correlation: (intr) age age -0.813 sexfemale -0.372 0.000 which can huge if there many factor combinations involved. is there way suppress output in summary command? know can use print(fm2, cor=f) but not show me rest of usual output example no p-value calculation. looking @ nlme:::print.summary.lme don't see way suppress correlation matrix printing (although create hacked version of function removing if clause beginning if (nrow(x$ttable)>1) ...) perhaps useful able print just summary of fixed-effect parameters ... ? printcoefmat(summary(fm2)$ttable)

iphone - How to animate UITableView header view -

i need animate insertion of tableview header view. want table rows slide down while header view expands frame. far best result got using following code: [self.tableview beginupdates]; [self.tableview settableheaderview:self.someheaderview]; [self.tableview endupdates]; the problem solution header doesn't animated, frame doesn't expand. so effect i'm getting table rows slide down (as want) header view shown, , want expand it's frame animation. any ideas? thanks. have header frame @ cgrectzero , set frame using animation [self.tableview beginupdates]; [self.tableview settableheaderview:self.someheaderview]; [uiview animatewithduration:.5f animations:^{ cgrect theframe = somebigger.frame; someheaderview.frame = theframe; }]; [self.tableview endupdates];

Canon EOS SDK (EDSDK): no operations after starting live view -

i implementing console application (going dll) controls canon eos 600d using edsdk, implemented in c++. i can function work, change properties, take photos, start live view, , download live view content following examples documentation , sample app. however, after start live view, although works fine, cannot send further commands or change further properties on camera. so, example, can't start autofocus or take picture once live view begun, though these commands work fine otherwise. the commands send fine (edssetpropertydata , edssendcommand return 0), nothing happens. in sample, can execute commands after switching live view. gives? i don't know code if have made loop live view maybe can't go out can't access rest of code. if case try launch download of liveview timer able continue execution of code.

c# - Communication Module Automation Testing -

i developed communication protocol module between 2 machine in our product. explicit protocol , not possible use standart protocol wcf or webservices there 2 functionalities module: 1. send notification end point 1 end point 2 2. send request end point 1 end point 2 , receive response end point 2 in end point 1. before doing full integration tests between 2 machines (the other side written in c++) wrote client console , server console simulate manually 2 main funcionalities on local tcp in localhost. what best way automate test in solution build process? tries use unit test framework didnt worked well. when using unit tests framework had run client , server in 2 different threads , didnt go fluently... you use mocking framework such moq in unit tests allow simulate connection endpoint 2. allow test endpoint 1 behaves of possible types of response endpoint 2. example, assert endpoint 1 throws exception if cannot connect endpoint 2.

clojure - Why does this simple main method never return when run by leiningen? -

this piece of code returns immediately: user=> (dorun (pmap + [1 2] [3 4])) nil however, when run same piece of code in main method using lein: (ns practice.core) (defn -main [& args] (dorun (pmap + [1 2] [3 4]))) why never return? interestingly, if replace pmap map , returns normally. you need call shutdown-agents @ end of -main method. (defn -main [& args] (dorun (pmap + [1 2] [3 4])) (shutdown-agents)) this mentioned on http://clojure.org/agents : note use of agents starts pool of non-daemon background threads prevent shutdown of jvm. use shutdown-agents terminate these threads , allow shutdown. pmap uses futures run on agent thread pool.

php - removing the h3 closing tag only after getting the source by file_get_contents -

i using file_get_contents html source of remote page using code below : <?php //get url $url = "remotesite/static/section35.html"; $html = file_get_contents($url); $doc = new domdocument(); // create domdocument libxml_use_internal_errors(true); $doc->loadhtml($html); // load html can add $html $elements = $doc->getelementsbytagname('tbody'); $toremove = array(); // gather list of tbodys remove foreach($elements $el) if((strpos($el->nodevalue, 'desktop') !== false) && !in_array($el->parentnode, $toremove, true)) $toremove[] = $el->parentnode; foreach($elements $el) if((strpos($el->nodevalue, 'recommended') !== false) && !in_array($el->parentnode, $toremove, true)) $toremove[] = $el->parentnode; // remove them foreach($toremove $tbody) $tbody->parentnode->removechild($tbody); echo $doc->s

php - Make uploaded video on youtube publicly -

i m using yii framework , want upload video directly tube website. that,i have used http://yii.hugphp.com/wiki/375/youtube-api-v2-0-browser-based-uploading/ using able upload video giving private access uploaded video.i able play uploaded video else can not view video. how can make video available publicly? if followed file names in tutorial, remove $video->setvideoprivate(); in video.php

r - Keeping zero count combinations when aggregating with data.table -

suppose i've got following data.table : dt <- data.table(id = c(rep(1, 5), rep(2, 4)), sex = c(rep("h", 5), rep("f", 4)), fruit = c("apple", "tomato", "apple", "apple", "orange", "apple", "apple", "tomato", "tomato"), key = "id") id sex fruit 1: 1 h apple 2: 1 h tomato 3: 1 h apple 4: 1 h apple 5: 1 h orange 6: 2 f apple 7: 2 f apple 8: 2 f tomato 9: 2 f tomato each row represents fact (identified it's id , sex ) ate fruit . want count number of times each fruit has been eaten sex . can : dt[ , .n, = c("fruit", "sex")] which gives: fruit sex n 1: apple h 3 2: tomato h 1 3: orange h 1 4: apple f 2 5: tomato f 2 the problem is, doing way i'm losing count of orange sex == "f" , because count 0. there way

c# - File.Open Cross Thread Writing -

is safe open file , write stream across multiple threads? if no implement make safe? no, standard filestream not thread-safe. you should use var safe = stream.synchronized(file.open(...)); create thread-safe wrapper. stream.synchronized() on msdn

java - Easy way to make an SQLite database? -

Image
i working new eclipse adt (android development tools). when used older version, there plugin motorola named motodev studio helped make database quite easily. doesn't seem work anymore new adt. does have alternative making easy sqlite database content, , "converting" java code android? (i've been looking online, can't seem find it) you can use eclipse plugin: https://github.com/sromku/android-sqlite-model-generator-plugin this plugin allow generate java source code android based on sqlite database schema define in json file. create json file describes schema. example here right click on json file -> generate sqlite model... : then, can work database using generated code. example, if define student table few columns, adding new student this: student student = new student(); student.setfirstname("john"); student.setlastname("smith"); student.setage(30); model model = model.getinstance(context); model.createstudent(

mysql - django database delta update -

say want perform following: "update main_post set votes = votes+1 post_id = xxx" such delta update needed deal concurrency issues. or there alternative solve concurrency issue? does django in way support delta update out of box? * answer * use f object in django use f object in django. refer docs

time - Check if line is a timestamp in Python -

i have script runs every 30 minutes on server, , when it's done writes timestamp last line of file. 20+ files in 1 directory. i'm trying write python script check last line of each file , return either "in progress" or "finished at:" message each file depending on if timestamp present or not. how python determine if string timestamp or not? formatted hh:mm:ss, no month/date indications. you try match regular expression: import re if re.match('\d{2}:\d{2}:\d{2}', line): would work if line starts 3 2-digit pairs colons in between; depending on else might find in line enough. another option try , parse it: import time try: time.strptime(line[:8], '%h:%m:%s') except valueerror: print('not timestamp') else: print('found timestamp') this lot stricter; valueerror thrown whenever line not start timestamp can represent valid time value, hour must in range 0-23, minutes in range 0-59 , seconds in

c# - Mapping domain model to view model via AutoMapper or not -

i want use view model display insted of domain model. , want customise property display, how should this? , practice use automapper display? below code sample: public class bookcontroller : basecontroller { private ibookservice bookservice; public bookcontroller(ibookservice bookservice) { this.bookservice = bookservice; } public actionresult details(int id) { var book = bookservice.getbookbyid(id); return view(mapper.map<bookview>(book)); } } public class book { public virtual int id { get; set; } public virtual string name { get; set; } } public class bookview { public int id { get; set; } public string name { get; set; } } if use way, can customise property, below: public actionresult details(int id) { var book = bookservice.getbookbyid(id); return view(new bookview(b