Posts

Showing posts from March, 2015

What is the difference between different for loops in Java? -

java has different for -loops walk through list. example: public void mymethod(list list) { (int = 0; <= list.size(); i++) { ... } } or, can write this: public void mymethod(list list) { (string obj : list) { ... } } or, can use list iterator: public void mymethod(list list) { iterator<string> iterator = list.iterator(); while (iterator.hasnext()) { ... } } which 1 best , prevents nullpointerexception s without more code? your second variant best (and it's equivalent third, less verbose). reason it's superior because you're looping via iterator opposed calling get() multiple times, have first variant. linkedlist s, instance, get() o(n) operation, meaning first snippet o(n 2 ) whereas second o(n) . in case of null , 3 variants throw nullpointerexception ; should check null beforehand (or ensure list can never null ).

multithreading - timeout on ReadLine from StandardOutput stream of process vb.net 2012 -

i have process running. should take 1.5 minutes run.. happens @ readline stuck. processing video file.. need way kill process if goes beyond 3 min mark. have condition handled if process killed.. thought run timer , after 3 minutes kill process readline locks thread.. function running in thread on main program.. if want run timer should done on second thread. console.readline() lock single thread. using system.threading.timer

javascript - DataTables & X-Editable making out of focus items editable -

i have working setup data-tables , x-editable allows user edit data inline in table gets loaded database. once page loads code below fires , makes editable options editable, except seems work first page of results. when click next, change number of results or search, items not on first page don't made editable. assuming because data-tables hides data not on current page removing document flow. how can make sure data in table editable? $(document).ready(function () { $.fn.editable.defaults.mode = 'inline'; $('.locatorid').editable(); $('.title').editable(); $('.latitude').editable(); $('.longitude').editable(); $('.website').editable(); $('.address').editable(); $('.city').editable(); $('.state').editable(); $('.zip').editable(); $('.country').editable(); $('.phone').editable(); }); first, move x-editable setup own function:

c# - How do I remove all HTML tags from a string without knowing which tags are in it? -

this question has answer here: html agility pack - removing unwanted tags without removing content? 5 answers is there easy way remove html tags or html related string? for example: string title = "<b> hulk hogan's celebrity championship wrestling &nbsp;&nbsp;&nbsp;<font color=\"#228b22\">[proj # 206010]</font></b>&nbsp;&nbsp;&nbsp; (reality series, &nbsp;)" the above should be: "hulk hogan's celebrity championship wrestling [proj # 206010] (reality series)" you can use simple regex this: public static string striphtml(string input) { return regex.replace(input, "<.*?>", string.empty); } be aware solution has own flaw. see remove html tags in string more information (especially comments of @mehaase) another solution use html agility pa

dynamics crm 2011 - Multiple operations in a single transaction -

a customer requested interesting thing. they'd have 2 operations - update entity in context and , update other entity carried out simultaneously. in sql, it's pretty straight-forward. 1 can roll-back whole shabang if needed. however, i've never seen done in crm. @ possible?! please note i'm looking solution based on supported approach. simultaneously may not right word, can in same database transaction updating 2nd entity within plugin operating on 1st transaction in pre or post operation event long use iorganizationservice provided in plugin context. throwing kind of exception "bubble up" causing entire transaction rolled (assuming you're not catching , "eating" exception)

qt - QTreeWidgetItem display html -

i have qtreewidgetitem display formatted html.(pyqt) has managed this? htmlstring = r"<b>boldtext:</b>somevalue" item = qtgui.qtreewidgetitem( item, [htmlstring], 0) any appreciated! to answer own question: created widget containing qtextedit , used sethtml() display htmlstring added widget tree: anitem = qtgui.qtreewidgetitem( parentwidgt ) parentwidgt.setitemwidget(anitem, 0, widgcontainingtextedit) cheers!

Disable html/javascripts commands in text fields -

how prevent input in texts fields containing html , javascript code? example: have input text field. if user enters javascript instructions, executed. how can modify <script>alert('aces')</script> so show normal text in field , not alert when try list it? have looked libraries underscore.js (used backbone.js)? it comes escape functions prevents user entered javascript run. http://underscorejs.org/#escape , http://underscorejs.org/#unescape so write: alert(_.escape(userinput)); this becomes more important when add user input dom, security reasons need escape inputs (or allow selection of harmless tags < strong >).

css - Absolute positioning of a <div> -

in following fiddle , trying find out why div checkbox placed bigger content (which image of empty checkbox). trying accomplish same seen on fiddler without overlapping of white background on border of underlying . think problem related css style: .selectable-content label:after { background: white; color: #9fc5e8; content:"\f096"; position:absolute; } you'll have play of bottom values in media queries, white background due default line-height on label. http://jsfiddle.net/xtm9d/11/ added: .selectable-content > label { padding-top: -5px; font-family:'fontawesome'; font-size: 32px; cursor: pointer; line-height:26px; } messed around media queries well.

c - determine the user who run the current process -

this question has answer here: check if user root in c? 2 answers i wonder, how can determine if current process running root or not. after searching on google, found out linux has field called "current" can use determine running particular process. try use current->uid == 0 however, when try compile code error struct task_structâ has no member named âuidâ did wrong? additionally, true if process run root, uid equal zero? thanks for process ,it have 3 kind of user id: 1.actual user id --> of time are, man login , while root process has way change it. use getuid() user id. 2.effective user id -->this id decide access limits. exce function can set id ,and if didn't, user id same actual user id. use geteuid() id 3.saved settings user id --> copyed effective user id exec function. no function

objective c - runtime error ns invalid arguement exception -

i newbie regarding ios programming objective c. don't have experience , help. here output describing error:2013-08-08 17:48:47.957 multmachine[57549:c07] -[viewcontroller play:]: unrecognized selector sent instance 0x7578870 2013-08-08 17:48:47.959 multmachine[57549:c07] * terminating app due uncaught exception 'nsinvalidargumentexception', reason: '-[viewcontroller play:]: unrecognized selector sent instance 0x7578870' // viewcontroller.h // multmachine // // created danny takeuchi on 8/7/13. // copyright (c) 2013 danny takeuchi. rights reserved. // #import <uikit/uikit.h> nsstring *questionlist[100]; @interface viewcontroller : uiviewcontroller @property (weak, nonatomic) iboutlet uibutton *playbutton; @property (weak, nonatomic) iboutlet uilabel *question; @property (weak, nonatomic) iboutlet uitextfield *answer; - (ibaction)preparequestion:(id)sender; - (ibaction)process:(id)sender; @property (weak, nonatomic) iboutlet uibutton *checkanswer;

c - CoreGraphics: Encode RGBA data to PNG -

i trying use c interface of coregraphics & corefoundation save buffer of 32-bit rgba data (as void*) png file. when try finialize cgimagedestinationref , following error message printed console: libpng error: no idats written file as far can tell, cgimageref i'm adding cgimagedestinationref valid. relavent code: void saveimage(const char* szimage, void* data, size_t datasize, size_t width, size_t height) { cfstringref name = cfstringcreatewithcstring(null, szimage, kcfstringencodingascii); cfurlref texture_url = cfurlcreatewithfilesystempath( null, name, kcfurlposixpathstyle, false); cgcolorspaceref colorspace = cgcolorspacecreatedevicergb(); cgdataproviderref dataprovider = cgdataprovidercreatewithdata(null, data, datasize, null); cg

java - If Singletons are bad then how do you store global state for a framework -

if singletons considered bad global state, particularly state can affects main execution of code, how should global state for, say, web framework handled? the immediate things come mind are: base url base file path general configs logging instance etc i cant see other way singleton access these such app() class or similar? load data in place global application. instance, in web applications, can store data in application scope i.e. servletcontext using servletcontextlistener . also, can use framework handles global state per context spring. by way, there cases logging instances (i.e. logger logger ) aren't stored in singleton instances in each class, marked static final . more info related long-never-endind discussion singleton pattern usage: what bad singletons?

ruby - Is there a more efficient way of ensuring my database gets closed? -

i'm using daybreak library, key/value store. i open perform operation this: db = daybreak::db.new $showdatabasename then whatever want, , close this: db.close it seems wasted effort everywhere want use however. seems might more efficient declare class variable in initialize this: def initialize @db = daybreak::db.new $showdatabasename end it means rest of class can use without initializing , closing each time, message reading: daybreak database not closed, state might inconsistent is there better way of doing this, deals both repetition , warning? use block: def use_db(database_name) db = daybreak::db.new(database_name) yield db ensure db.close end use_db($showdatabasename) |db| # db end

date - How to convert iPhone time into seconds? -

i have problem. before explain, let me few things out of way. have progress bar has 604,800 states become full. how many seconds in week, , every second passes, want progress bar change one. me? okay, here problem. since homemade progress bar in seconds, need convert iphone time seconds , display progress bar accordingly. reset @ midnight sunday (changeable day user depending on day last day of week, no difference). example, if 5 o'clock in morning on monday (18,000 seconds after midnight sunday) progress bar on it's 18,000th state. how can accomplish this? believe need first convert [nsdate date]; seconds , add each second passes int resets every week. this confusing, think explained well. can me out? thank you! use - (nstimeinterval)timeintervalsincedate:(nsdate *)anotherdate . in case, like: nsdate *previoussunday = [self previoussunday]; // still need define method. nsdate *now = [nsdate date]; nstimeinterval secondsfromsunday = [now timeintervalsince

c# - Automatic URL Parameter Encoding Failing -

background in homecontroller.cs have: [httpget] public getperson(string name) { return view(new personmodel { ... }); } in global.asax.cs have: public static void registerroutes(routecollection routes) { routes.ignoreroute("{resource}.axd/{*pathinfo}"); routes.maproute( "word", "person/{name}", new { controller = "home", action = "getperson" }); routes.maproute( "default", "{controller}/{action}", new { controller = "home", action = "index" }); } in somepage.cshtml have, effectively, this: @{ var name = "winston s. churchill"; } <a href="@url.action("getperson", "home", new { name })">@name</a> problem if click link winston s. churchill, routed url http://localhost/person/winston%20s.%20churchill , yields standard 404 page: http error 404.0 - not found

jquery - What is the best fix, for mouseleave (over select) bug? -

#childbox { width:200px; height:200px; border:solid thin #900; } <div id="parentbox"> <div id="childbox"> <select> <option>opt1</option> <option>opt2</option> <option>opt3</option> </select> </div> <div id="mesin"></div> <div id="mesout"></div> </div> var = 0, y=0; $('#parentbox').on({ mouseenter:function(e){ //console.log ('in: '); i++; $('#mesin').text('in '+i); }, mouseleave: function(e){ //console.log ('out: '); y++; $('#mesout').text('out '+y); } }, '#childbox'); when mouse enters options fire first 'out' , 'in' again. found prb in ff23 & ie9 (ff crashing) it's working should in chrome 28 & opera 12.16 have j

javascript - Can a variable be produced from an if else statement? -

can change variables value based on if/else statement in javascript? var $nextlink = $this.next().attr('href'), $currentlink = $this.attr('href'); if ($currentlink == $nextlink){ // check if next link same current link var $nextload = $this.eq(2).attr('href'); // if so, next link after next } else {var $nextload = $nextlink;} the code shown in question work. note, though, javascript doesn't have block scope, function scope. is, variables declared inside if or else statement's {} block (or for statement's {} , etc.) visible in surrounding function. in case think that's intend, still js coders find neater declare variable before if/else , set value if/else. neater still in 1 line using ?: conditional (or ternary) operator : var $nextload = $currentlink == $nextlink ? $this.eq(2).attr('href') : $nextlink;

Creating tags using jquery -

first see example http://jsfiddle.net/es5qs/ in example keeping space delimiter creating tags, wanted when type on textbox1 should reflect tags in textbox2 hear code, how can this. <!doctype html> <html> <head> <script src="jquery.min.js"></script> <script src="jquery-ui.js"></script> <script> $(document).ready(function() { $("#textbox").keyup(function() { $("#message").val(this.value); }); }); $(document).ready(function() { //the demo tag array var availabletags = [ {value: 1, label: 'tag1'}, {value: 2, label: 'tag2'}, {value: 3, label: 'tag3'}]; //the text input var input = $("input#text"); //the tagit list var instance = $("<ul class=\"tags\"></ul>"); //store current tags //note: tags here can split of trigger keys // tagit split on trigger keys passed var cu

c# - No Overload for Method. What am i Doing Wrong? -

no overload method. doing wrong? head alread hurts :) //this first class named employee namespace lala { public class employee { public static double grosspay(double weeklysales) //grosspay { return weeklysales * .07; } public static double fedtaxpaid(double grosspay) { return grosspay * .18; } public static double retirementpaid(double grosspay) { return grosspay * .1; } public static double socsecpaid(double grosspay) { return grosspay * .06; } public static double totaldeductions(double socsecpaid, double retirementpaid, double fedtaxpaid) { return socsecpaid + retirementpaid + fedtaxpaid; } public static double takehomepay(double grosspay, double totaldeductions) { return grosspay - totaldeductions; } } } this second class named employeeapp dont know why program doesnt work namespace lala { public class employeeapp { public static string name

c++ - Can not read text file with Qt 5 -

i wrote simple code open plain text file qt 5's qfile seen below; // main.cpp #include <iostream> using std::endl; using std::cout; #include <qcoreapplication> #include <qfile> #include <qiodevice> int main(int argc, char *argv[]) { qcoreapplication a(argc, argv); qfile plainfile("plain.txt"); if(plainfile.open(qiodevice::readonly | qiodevice::text)) { cout << "file opened successfull" << endl; plainfile.close(); } else{ cout << "could not open file." << endl; } return a.exec(); } the output when compiled , run "could not open file". wrong? probably because plain.txt not exist in current working directory or in path. make sure file in working directory or pass absolute path qfile . also see qfile::exists returns.

asp.net - db.Entry.Collection.Query is not eagerly loading all virtual attributes -

i have following scenario (combined in 1 line) var user = db.entry(obj).collection(collection).query().where(/*some condition*/).firstordefault(/*some condition*/); lets assume user object has posts virtual attribute (to eagerly load them) result of previous line loads 1 post user while if did 1 of following : var users = db.entry(obj).collection(collection).query().tolist().where(/*some condition*/).firstordefault(/*some condition*/); //added tolist() after query method //or db.users.where(/*full condition*/).firstordefault() //or db.users.firstordefault(/*full condition*/) all of these loads posts user, i'm missing in first query, , how can eagerly load posts through it? try adding .include(virtualpropertytoeagerload) after .where in first query. see msdn post on using eager loading.

Java - how does reversing byte array with bitwise shift operator work in this example? -

i learning java book - java 7 absolute beginners jay bryant. there particular example on page 164 read , reversed contents of text file, using particular method follows: private static void reversebytearray(byte[] inbytes) { int inlength = inbytes.length; (int = 0; < (inlength >>1); i++) { byte temp = inbytes[i]; inbytes[i] = inbytes[inlength - - 1]; inbytes[inlength - - 1] = temp; } } my question bitwise shift operator in following line (int = 0; < (inlength >>1) ; i++) { -what role in entire operation reverse text contents? i believe understand subsequent code under loop, swap first byte's value last byte's value. if there no bitwise shift operator present, output not reversed. initial: sleep: perchance dream: ay, there's rub; in sleep of death dreams may come when have shuffled off mortal coil, must give pause: there's respect makes calamity of long life output: efil gnol os fo ytimalac sekam tah

android - How to add textVIew to camera Previw -

im developing application using zbar qr code scanner. everthing works fine, want add text camera preview , im unable it. when add text camera preview disappear. there not enought information , id appriciate if me. ! this code of camerapreview.java looks make magic package com.dm.zbar.android.scanner; import android.content.context; import android.hardware.camera; import android.hardware.camera.autofocuscallback; import android.hardware.camera.previewcallback; import android.hardware.camera.size; import android.util.log; import android.view.surfaceholder; import android.view.surfaceview; import android.view.view; import android.view.viewgroup; import android.widget.linearlayout; import android.widget.textview; import java.io.ioexception; import java.util.list; class camerapreview extends viewgroup implements surfaceholder.callback { private final string tag = "camerapreview"; surfaceview msurfaceview; surfaceholder mholder; size mpreviewsize; li

vb.net - There is a sort of limit in "New List(Of String)"? -

i made program witch colors different part of text ( notepad++) have problem. this part of code, in class1 public shared function get_c_html() dim html_words new list(of string) {"<html>", "<title>", "<b>" _ , "</b>", "<u>", "</u>", "<i>", "</i>", "<sub>", "</sub>", "<sup>", "</sup>", "<a href" _ , "</a>", "<body>", "</body>", "<head>", "</head>", "</font>", "<font>", "<div", "</div", "<title>" _ , "</title>", "<img", "/>", "<link", "<br>", "<ul>", "</ul>", "<li>", "</li>" _

c# - How to get the actual path of a referenced .dll file from the current working assembly? -

i have create objects particular class @ runtime, classes should configured in app settings of web.config file, using reflection. the problem is, not able load assembly. since classes in referenced dlls. not able actual path of referenced dll. have tried path, codebase, current directory. can me?? if assembly referenced project, don't need load it. can getting type of class in particular assembly. in general, doing late-binding on own, isn't best of idea. had issues @ our project , it's quite lot of work right. instead use of many different ioc-containers, find assembly , class you. edit: i maybe bit confused, didn't think of earlier. can load assembly it's name. should find assembly in referenced paths or gac. further information can found at msdn

performance - How to swipe the listview -- android -

how swipe using motion event. have customized list view edittext , checkedbox. used swipe particular item of listview using setontouchlistener. ** switch (motionevent.getaction() & motionevent.action_mask) { case motionevent.action_move: // mgr.hidesoftinputfromwindow((ibinder) textview, inputmethodmanager.show_forced); // inputmethodmanager.hidesoftinputfromwindow(activity.getcurrentfocus() .getwindowtoken(), 0); float delta = motionevent.getrawx(); float deltax = motionevent.getrawx() - mdownx; if (math.abs(deltax) > mslop) { // swipe occurred, toast.maketext(getapplicationcontext(), "down", toast.length_short).show(); } break; case motionevent.action_down:

using SQLite database for the very first time in android. how? -

after installing android sdk , eclipse first time using sqlite. should need settings or register in manifest.xml? i unable use sqlite database showing errors like sqlite database db; sqlite in underlines in red , stating (multiple markers @ line - sqlite cannot resolved type - syntax error on token "sqlite", invalid modifiers) and also sqlite cannot resolved type , giving suggestions as- create class sqlite create interface sqlite , other 9 suggestions. what shud do? you need have databasehelper class make easy understand. can manipulate according needs. import android.content.contentvalues; import android.content.context; import android.database.cursor; import android.database.sqlexception; import android.database.sqlite.sqlitedatabase; import android.database.sqlite.sqliteopenhelper; import android.util.log; public class databasehandler { public static final string key_rowid = "_id"; public static final string key_pro

php - Can we use Symfony\Bundle\FrameworkBundle\Test\WebTestCase for symfony 2 console commands testing? -

using symfony\bundle\frameworkbundle\test\webtestcase, easy access container, entity manager etc. can use functional testing automatic manual http requests. can use test symfony2 console commands can have easy access container , services? i want test costum symfony2 console commands uses many services in turn uses doctrine entity manager access data. phpunit documentation suggest extend test class phpunit_extensions_database_testcase , can extend webtestcase instead of test instead test console commands ? i have refereed how test doctrine repositories cookbook how test code interacts database cookbook the console component docs webtestcase meant functional testing web applications. nothing stop using test commands, doesn't feel right (hence question). testing commands remember, command tests (as controller tests) shouldn't complex, code you're putting in there shouldn't complex either. treat commands controllers, make them slim , p

jquery - Title not appearing in firefox -

i found this jsfiddle makes title of object appear in firefox. not familiar jquery, how can modify snippet if have div object , not input? the snippet: <input type="button" value="click me" title="foobar"/> if ($.browser.mozilla) { $("input").each(function() { var input = $(this); var title = this.title; var div = $("<div>"); div.attr({ "class": "disabledbuttondiv", "faketitle": title }); input.wrap(div); this.title = ""; }); } my line: <div class="ttt" title="cancel" id="<?php echo $row2[$c][10]; ?>" onclick="cancelad(this)"></div> i changed input div , class ttt didn't help. simply change jquery code like: if ($.browser.mozilla) { $("div").each(function() { var input = $(this); va

How to change application icon within taskbar Delphi 2010 -

i change icon of application own icon (32x32 16bit ega) using : project > option > applications > load icon the icon within taskbar changed in many border style := bsnone or bssingle or bssizeable or bssizetoolwin or bstoolwindow. icon did not change while use borderstyle := bsdialog. please not tell me use : application.icon.loadfromfile(extractfilepath(application.exename) + '\myicon.ico'); becase want submit 1 exe file only. ps: use embarcadero delphi 2010 the icon of window associated taskbar button. application.mainformontaskbar set true, it's main form icon. when false it's icon of hidden window of application. have different icon on taskbar main form, need mainformontaskbar false, , assign different icon application.icon. seems easy way work around issue. if recall vcl sets 1 size of icon. in experience better job , send wm_seticon messages directly set both small , large icons. as icons reside, link them executable resource

submit - input maxlength field on ajax form submission causes "Uncaught SyntaxError: unexpected token u" -

when submit form includes text field "maxlength" attribute using ajax, javascript error: uncaught syntaxerror: unexpected token u (jquery-1.9.1.min.js:3) if remove maxlength attribute runs fine. my html, stripped down page bare minimum replicate issue: <html> <head> <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <script src="/scripts/jquery.unobtrusive-ajax.js"></script> <script src="/scripts/jquery.validate.js"></script> <script src="/scripts/jquery.validate.unobtrusive.js"></script> </head> <body> <form action="#" data-ajax="true" id="form0" method="post"> <input id="deposit" name="numbervalue" type=&quo

jquery - Trying to center a rotated text inside a floated div -

i'd rotate text centered on div. i trying solution doesn't make me change (position, float , on) on parent divs, , neither deal pixels manually on rotated div (margin, top) . there way ( best practice ) achieve it? i don't mind browser compatibility , looking best way without modifying structure or fixing lengths fiddle: http://jsfiddle.net/w5k4j/29/ <div id="parent"> <div id="unknown"></div> <div id="child"> <h3>click overflowing text i'd v/h center when rotated</h3> </div> </div> stylesheet: #parent { height:300px; width:70px; float:left; border: 1px solid; } #unknown { float:right; height:50px; width:20px; background-color: yellow } #child { float:right; height:100px; width:70px; clear:right; background-color: orange; /*text-align: center;*/ } h3 { /*vertical-align: middle;*/ white-space:

datetime - Transform seconds in time in PHP -

i have example 259201 seconds in variable. how can transform in "normally" time 4 days 00:00:01 ? thank in advance! is simple in php: <?php $secs = "259201"; $days = gmdate("d", $secs); $hoursminssecs = gmdate("h:i:s", $secs); if ($days == 0) { $days = empty($days); } elseif ($days == "1") { $days = "1 day"; } else { $days = $days." days"; } echo $days." - ".$hoursminssecs ?> hopes helps you!

c++ - Iterator Dereferencing -

i using vector in c++, vector<agents> agentlist; why work, (agentlist.begin() )->print(); and not? *(agentlist.begin() ).print(); isn't valid dereference iterator using * ? see operator precedence , . has higher precedence * *(agentlist.begin()).print(); represents as: *((agentlist.begin()).print()); while iterator has no .print() function call, compiler throw out compile error. you need: agentlist.begin()->print(); or (*agentlist.begin()).print();

mysql query to display messages with sender and reciever -

my messaging schema user id name message id messagetitle sender_id receiver_id i want display messagetitle sender , receivers name for example mysql query should display : +--------------+------------+--------------+ | messagetitle | sendername | recievername | +--------------+------------+--------------+ | important | raj | vijay | | solution | vijay | raj | +--------------+------------+--------------+ try following sql solution: select m.messagetitle messagetitle ,u1.name sendername ,u2.name recievername message m inner join user u1 on u1.id = m.sender_id inner join user u2 on u2.id = m.receiver_id sql fiddle demo

pointers - What does 'return *this' mean in C++? -

i'm converting c++ program c#, part has me confused. return *this mean? template< edemocommands msgtype, typename pb_object_type > class cdemomessagepb : public idemomessage, public pb_object_type { (...) virtual ::google::protobuf::message& getprotomsg() { return *this; } } how translate c#? this means pointer object, *this object. returning object ie, *this returns reference object.

node.js - File path completion relative to the current file directory -

is possible have file path completion relative current file directory ? able search file (like command-t or ctrlp) , insert relative path. this nodejs/component development, require other modules of project. (i found example sublime text https://github.com/jfromaniello/sublime-node-require ) thanks edit: i add example illustrate question: . |-- models | `-- user.js `-- views `-- home `-- index.js i'm working on file views/home/index.js , want require models/user.js views/home/index.js var usermodel = require('../../models/user'); is there way in vim path of models/user.js relative views/home/index.js (here in example = '../../models/user' ). filename-completion done working directory. if want things relative current file, can add set autochdir to ~/.vimrc . you can change working directory current window with :lcd %:p:h see :help 'autochdir' , :help :lcd , :help filename-modifiers .

post - Wordpress loop how to get tag slug and be value in query_posts -

what trying is: among posts in category 1 every post has tag now in post under category want call posts category 1 have same tag example cat=1&tag=1 , cat=2&tag=1 here code , it's not working: <?php $t = wp_get_post_tags($post->id); query_posts( 'cat=45&tag=' . $t. '' ); // loop while ( have_posts() ) : the_post(); ?> you have pass tag id in query_posts , wp_get_post_tags() returns array not id best achieve posts tag have pass tag-id <?php $t = wp_get_post_tags($post->id); query_posts( 'cat=45&tag=' . $t[0]->term_id. '' ); // loop while ( have_posts() ) : the_post(); ?> there can multiple tags have loop through $t tag ids please refer manual wp_get_post_tags

nio - Java - how to find out if a directory is being used by another process? -

i want use java 7's watchservice monitor changes directory. seems tries lock folder, , throw exception if fails, not seem provide method of locking before-hand / checking if locked. i need know if directory being used process or not. since can't lock or open stream (because it's directory), i'm looking more intelligent trying modify , sleeping if failed, or try/catch sleep. ideally, blocking call until available. edit: can't seem acquire filelock on folder. when try lock folder, "filenotfoundexception (access denied)". googling suggests can't use object on directory. registration code: watchservice watchservice = path.getfilesystem().newwatchservice() path.register(watchservice, standardwatcheventkinds.entry_create, standardwatcheventkinds.entry_modify, standardwatcheventkinds.entry_delete) failing scenario: let's i'm listening folder f new creation. if sub-folder

deployment - glassfish 4.0 jpa resource -

Image
i try deploy application still deployment errors. created connection pool succesfully (i can create entities tables using jpa tools in eclipse). as can see i've created jdbc resource in glassfish admin panel called sellyourthingres. when use "sellyourthingres" instead of "sellyourthing" in persitance.xml nothing changes , got same errors (with different name of course). choosing jta/jta(default) doesn't change anything. what should do?

c# - Load child object records with filter condition in Entity Framework -

designed data access layer entity framework , sample poco structure of packageinstance object is public class packageinstance { public virtual long packageinstanceid {set;get;} public virtual boolean isdeleted {set;get;} public virtual list<session> sessions {set;get;} } public class session { public virtual long sessionid {set;get;} public virtual long packageinstanceid {set;get;} public virtual boolean isdeleted {set;get;} public virtual list<note> notes {set;get;} } public class note { public virtual long noteid {set;get;} public virtual long sessionid {set;get;} public virtual boolean isdeleted {set;get;} public virtual list<documents> document {set;get;} } i need load packageinstance object along child objects in single method call, instead of loading each object separately. var packageinstancedb = entity.packageinstances.first(p => p.purchasesessionid == purhcasesessionid); //there db call happening her

jQuery ajax error do nothing -

this basic question, , shouldn't hard it's turned out be. i have cms i've developed. using ajax change form parameters. when user selects option has no "special params" want nothing display. right now, have ajax searching file. if file exists, should display in div. if doesn't exist, want nothing displayed. of now, when file doesn't exists div loaded entire page 404 error. don't want display errors, want nothing when file doesn't exist. this have: $.ajax({ url: '../components/com_'+params+'/menu.php', success: function(result){ $('#menuparams').html(result); }, error: function(){ $('#menuparams').html(''); } }); sounds path routed cms failing send http response header. either forgot send 404 in response header in cms or sent text page before tried send header. if case, either fix cms. or check success results 404 error. update in cms when not found, before else gets sent hav

php - Eager Load lists() in Laravel 4 -

in laravel 4 use eager loading manytomany relationship: public function categories() { return $this->belongstomany('category'); } it returns categories this: "categories": [ { "id": 1, "priority": 1, "title": "my category 1", "created_at": "2013-08-10 18:45:08", "updated_at": "2013-08-10 18:45:08" }, { "id": 2, "priority": 2, "title": "my category 2", "created_at": "2013-08-10 18:45:08", "updated_at": "2013-08-10 18:45:08" } ], but need this: "categories": [1,2] // references category id's the query builder has method called "lists" should trick. it's not working in case of eager load??? public f

remote control - Android EditMetadata with RemoteControl Client -

i'm tring create library phonegap give me control remote control client. phonegap side plus structure of new class made don't know how change metadata. i've made function: public void setmetadata() { remotecontrolclient.metadataeditor editor = remotecontrolclient.editmetadata(true) .putstring(mediametadataretriever.metadata_key_album, "ciao"); } but i'm sure i've missed register function. someone can give me help? thanks! for registering // register remote client =========================================== final intent mediabuttonintent = new intent(intent.action_media_button); mediabuttonintent.setcomponent(remotecontrolreceiver); final pendingintent mediapendingintent = pendingintent.getbroadcast( getapplicationcontext(), 0, mediabuttonintent, 0); // create , register remote control client myremotecontrolclient = new remotecontrolclient(mediapendingintent); audiomanager.registerremotecontro

javascript - JQuery Dialog open() killing text selection -

is possible maintain text selection on screen while dialog box opens still? i don't want dialog interfere selections user may have made on page. what happens is if select range of text , activate dialog box, event firing opens dialog seems deselect selected text. is there way around this?

Obscure usages of C++ virtual inheritance -

the virtual inheritance in c++ useful way prevent diamond issue. however, can't seem make work in each , every case. this going hard explain hope i'll manage. let's present problem: a inherits b. , base class of class set called c , class set called d. the problem c set of class have common features focusing around b. what do, isn't possible, class e virtually inherits b, , inherited c. problem is: in case, doesn't virtually inherits b. doesn't work. if virtually inherit b, need use b's constructor in every classes of d. conclusion: in every case there duplicated code. how may out of issue without duplicated code ? okay saying have: b + | v + +----+----+ v v c d and of

java - Robot and keyPress -

what sort of code need passed javafx robot when using keypress method? for example, example below enters 1 , not a , suppose there mapping somewhere. robot robot = com.sun.glass.ui.application.getapplication().createrobot(); robot.keypress(((int) 'a'); note: javafx robot, not awt one. codes defined constants in javafx.scene.input.keycode. with glass robot, can use deprecated method impl_getcode : robot robot = com.sun.glass.ui.application.getapplication().createrobot(); robot.keypress(keycode.a.impl_getcode()); you can use fxrobot, takes keycodes parameters: fxrobot robot = fxrobotfactory.createrobot(scene); robot.keypress(javafx.scene.input.keycode.a);

html - jQuery remove new elements -

i've got html form allows user add more elements form, side of each line of elements, there 'remove' button, button linked jquery call newly added elements aren't removing when button clicked, however, elements hard coded html remove. here code: $("[data-action]").each(function(i,a){ $(a).bind('click',function(){ switch ($(a).attr("data-action")) { case "addqualificationfield": qual_add_current++; var qual_add_html = '<div id="addqualification' + qual_add_current + '" class="controls inline" style="margin-top: 5px;">' + '<label for="addqualificationtype[' + qual_add_current + ']">type:</label> <input type="text" name="addqualificationtype[' + qual_add_current + ']" id="addqualificationtype[' + qual_add_current + ']" placeholder="

django - South letting syncdb do all the job -

when try run syncdb django can create tables , south's tables, creates tables south's , other app should not create, south should. look: patricks-mac-mini:tsm_telecom patrickbassut$ python manage.py syncdb syncing... creating tables ... creating table auth_permission creating table auth_group_permissions creating table auth_group creating table auth_user_groups creating table auth_user_user_permissions creating table auth_user creating table django_content_type creating table django_session creating table django_site creating table south_migrationhistory installed django's auth system, means don't have superusers defined. create 1 now? (yes/no): no installing custom sql ... installing indexes ... installed 0 object(s) 0 fixture(s) synced: > django.contrib.auth > django.contrib.contenttypes > django.contrib.sessions > django.contrib.sites > django.contrib.messages > django.contrib.staticfiles > south not synced (use migrations): - (

Should I Use Tkinter, C or C# to Make a GUI in Python? -

i building quiz program can personalized want add gui it. have seen pieces of software implement c , c# python. should use tkinter make gui or should use c or c#. can please tell me book beginners can use learn tkinter/c/c#. thanks. when writing program, should avoid using multiple languages unless need to, simple gui program. in case, learning c/c# purpose of creating gui seems overkill me -- not need learn entirely new programming language, need learn how use whatever gui library popular within c/c#! you'd right started -- having learn how use library. instead, python has several great gui libraries can use. tkinter bundled default within python standard, there are other gui libraries available, wxpython or pyqt. here's a comparison of different python gui libraries.

Python - Looping through a multidimensional dictionary -

this question has answer here: how loop dict in {} using python 2 answers if explain think doing, hope can explain going wrong. i have following dictionary: ls = [{ 'the wolf gift (13)': { 'cover': 'v:\\books\\anne rice\\the wolf gift (13)\\cover.jpg', 'author': 'anne rice', 'year': '1988' }, 'mummy (14)': { 'cover': 'v:\\books\\anne rice\\mummy (14)\\cover.jpg', 'author': 'anne rice', 'year': '1989' }, }] first of above multidimensional dictionary? want make sure talking right thing. secondly, how loop through retrieve information @ various levels. dictionary dynamically populated not know keys before hand. i have tried for book in ls , book['cover'] etc.. doesn't seem wo

wpf - Change button image when context menu item is selected -

can tell me how change button image when context menu item clicked? i have button image , context menu in it. want change image of button, everytime click contextmenu item. following piece of code able display contextmenu items on right click. don't know how proceed further. can guide me ? tried using command strangely command never got called. <button background="gray" name="statusbtn" verticalalignment="top" horizontalalignment="right" fontweight="bold" foreground="red"> <dockpanel > <image dockpanel.dock="top" stretch="fill" source="{binding toenum, converter={staticresource enumtoimgconverter}}" height="37" width="72" /> <textblock horizontalalignment="center" margin="0,23,1,2">test</textblock> </dockpanel> <button.contextmenu>