Posts

Showing posts from February, 2014

vim - GVIM : Possible to begin editing the file without having to press "i"? -

this question has answer here: is there way change vim's default mode 6 answers i trying move gedit gvim noticed when open file not free edit it. unless press i go in (insert) mode. is there way bypass this? file instantly editable? you can editing .vimrc file. looks set im! command you're looking set input mode default, you'll need explicitly map escape change command mode. a better question why want this, though. unless you're opening brand new file, once know vim, you'll spend little time in insert mode, should using more advanced command-mode commands (append, correct, etc) edit , update code @ appropriate places. if you're going use vim same way use gedit, don't bother - gedit better vim @ being gedit. edit: after reading comments on question, sounds really, shouldn't using vim. it's not want stumble defaul...

Get checkbox is checked or not using Javascript -

i've got problem can't solve. partly because can't explain right terms. i'm new sorry clumsy question. below can see overview of goal. i'm running code in magento <input type="checkbox" style="margin-left:24px" class="mydelete" name="checkall" onclick='checkedall(testcheck);' /> added id attribute element. <input type="checkbox" style="margin-left:24px" class="mydelete" name="checkall" id="checkall"onclick='checkedall();' /> javascript function checkedall(){ if (document.getelementbyid('checkall').checked) { alert("checked"); } else { alert("you didn't check it! let me check you.") } } demo

substring - Crystal Report : formula for Splitting string on / and concatenating it with other string -

i have string coming in format worvs/000017/0005 . i want split string on / . want 000017 string , further had column has concatenated. i need formula same. create formula , add below code. split (dbfield,"/")[2]

c# - Exception occuring while extracting the value of the node in xdocument -

i have xml : <runresult> <previewrecords></previewrecords> <recordsprocessed>100</recordsprocessed> <logerror>false</logerror> </runresult> i using following command fetch value of node recordsprocessed , int nofrecords = 0; nofrecords = convert.toint32(xdrunresultdoc.root.element("runresult").element("recordsprocessed").value; but @ line throwing exception " object reference not set instance of object ". please suggest going wrong. xdrunresultdoc.root points <runrdesult> element, don't have call element("runresult") again. and suggest using (int) casting on xelement instead of convert.toint32 : xelement explicit conversion (xelement int32) int nofrecords = (int)xdrunresultdoc.root.element("recordsprocessed");

java - JButton text not changing -

so code has jpanel text fields , jbutton , , when user clicks button goes button listener, takes data text fields , processes it, creating jlabels adds invisible jpanel . make first jpanel invisible, , make second panel visible, revealing "results" generate. this works problem is, while program processes data gets text fields, want jbutton change says, , tried using event.getsource().settext() , , able find changing button text (by printing console), not updating button changed text. i tried forms of revalidate , repaint , validate after this, none of worked. ideas? thanks! //entrypanel first panel, , pickspanel second panel button.addactionlistener(new actionlistener() { public void actionperformed(actionevent event) { ((jbutton)event.getsource()).settext("thinking..."); revalidate(); repaint(); try { criticpick picks = new criticpick(cityfield.gettext(),statefield.gettext()); linkedli...

benchmarking - can I run gridmix3 on hadoop-0.20.203.0?How? -

i use hadoop-0.20.203.0. in reasons,i should use version of hadoop.and can't change version of hadoop.in version of hadoop, there gridmix , gridmix2 benchmarks.but want run applications in benchmark there aren't in gridmix , gridmix2.(such wordcount,grep,terasort).what should do?can use gridmix3 in hadoop-0.20.203.0?or there way add these applications gridmix or gridmix2? new hadoop...please me...

java - Camel: disable polling messages -

i using camel setup routing using file , jms-queue components. problem having cannot disable polling messages sent console. i tryed multiple ways disable these messages setting logging level(runlogginglevel = off) on routes, trace = false on context, set logger on routes , few others nothing works. a message file component looks this: 2013-08-26 09:34:47,651 debug [camel (camelcontextorder) thread #0 - file://order-import/order-in] o.a.c.c.f.fileconsumer took 0.001 seconds poll: order-import\order-in and messsage jms queue: 2013-08-26 09:34:46,281 debug [activemq journal checkpoint worker] o.a.a.s.k.messagedatabase checkpoint started. 2013-08-26 09:34:46,403 debug [activemq journal checkpoint worker] o.a.a.s.k.messagedatabase checkpoint done. you have debug logging level configured. should change info etc camel / activemq not log much. check logging configuration adjust this.

jquery - jsTree opened node attributes... how to get? -

i new jstree , have problems getting attributes of nodes. here code... var $mytree = $('#treediv').html(res).jstree({ ...options }).on("loaded.jstree", function () { $mytree.jstree('open_node', '#' + idtoopen, false, true); }); $mytree.bind("open_node.jstree", this.onnodeopen); function onnodeopen(event, data){...here want of attributes of opened node}; my nodes have structure <li><a href='#' id='some guid' rel='some string' accesskey='some number'>title of node</a></li> now want retrieve id, rel , accesskey attribute values in onnodeopen function, how can that? data.rslt.obj contains jquery extended version of node clicked: so retrieve id: var id = data.rslt.obj.attr("id") i prepared small jsfiddle shows in action: http://jsfiddle.net/ak4ed/144/

Javascript Regex: create new a lookbehind regular expression with variable? -

i want create new regexp variable javascript. got trouble when want create new lookaround regexp : var xvar = "_on"; var regex = new regexp("(?<!" + xvar + ")(.gif|.jpg|.png)$"); #=> syntaxerror: invalid regular expression: /(?<!_on)(.gif|.jpg|.png)$/: invalid group i tried escape special characters follow creating regexp special characters , can create new regexp string, not lookaround regex. /\(\?<!_on\)\(\.gif\|\.jpg\|\.png\)\$/ can me? i don't know goal of regexp quantifier (...) causes error in situation. example, use non-capturing parentheses (?:...) . var regex = new regexp("(?:<!" + xvar + ")(?:.gif|.jpg|.png)$"); refer to: regular expressions - javascript | mdn . @alan moore: you're right.

regex - JavaScript to search a string and brace all capitalzied tokens -

i need javascript search string capitalized tokens, excluding first, , replace of them bracketed token. e.g. "rose harbor in bloom: novel" -> "rose {harbor} in {bloom}: {a} {novel}" "in america: novel" -> "in {america}: novel" "what else. in country" -> "what else. {in} country" you can use matched string in replacements using $&. also, \b specifies word boundary , [a-z] specify capital characters. *? attempts make match few characters possible so want .replace(/\b[a-z].*?\b/g, '{$&}') so example: "a string yes?".replace(/\b[a-z].*?\b/g, '{$&}') returns "a {string} {good} yes?" to exclude first token you'll have little creative; function surroundcaps(str) { //get first word var temp = str.match(/^.+?\b/); //if word found if (temp) { temp = temp[0]; //remove string str = str.substring(te...

regex - Match a string and the 5 characters before and after -

i need match string one or two , 5 characters before , after with following text in input lorem ipsum dummy 1 text of printing , typesetting industry. lorem ipsum has been industry's standard dummy text ever since 1500s, when unknown printer took galley of type , scrambled make type specimen 2 book. has survived not 5 centuries, leap electronic typesetting, remaining unchanged. popularised in 1960s release of letraset sheets containing lorem ipsum passages, , more desktop publishing software aldus pagemaker including versions of lorem ipsum. the output should be ummy 1 text imen 2 book the regex should works scan method in ruby this regex should work: .{5}(?:one|two).{5} if want word boundaries then: .{5}\b(?:one|two)\b.{5} live demo (ruby): http://www.rubular.com/r/acdofxmx31

asp.net mvc 4 - Custom helpers setting element attributes equal to a model property -

using mvc 4.5 custom html helper, how can set custom element's id model's property. i have created 2 classes: public class zclass1 { public zclass2 zclass2 { get; set; } } public class zclass2 { public string name { get; set; } } within view model @model zclass1 i have created simple custom html helper: using system; using system.web.mvc; namespace j6.salesorder.web.models.helpers { public static class spanextensions { public static mvchtmlstring span(this htmlhelper helper, string id, string text) { var tagbuilder = new tagbuilder("span"); tagbuilder.attributes.add("id", id); return new mvchtmlstring(tagbuilder.tostring()); } } } so, within view html helper used: @using mymodelpath.models.helpers @html.span("myid","just text"); it renders correctly: <span id="myid">just text</span> however, instead of hard c...

Prestashop add to cart button doesn't work -

i have disabled price displays visitors on shop. so, have log in/register see prices. to checkout, have register/log in too. guess checkout being disabled. however, want allow them add products cart if not logged in , don't see prices. need log in if want purchase/checkout. if enable price displays visitors on site, works fine. however, when disable it, add cart button no longer works. suggestions on making work visitors too? in prestashop/themes/yourtheme : edit product-list.tpl , products.tpl adjusting smarty {if} statements surrounding 'add cart' button/link link shows when prices disabled. edit shopping-cart.tpl , shopping-cart-product-line.tpl adding smarty {if} statements hide prices when users not logged in. there might few other places edit, should started.

Python regex: find and replace commas between quotation marks -

i have string, line = '12/08/2013,3,"9,25",42:51,"3,08","12,9","13,9",159,170,"3,19",437,' and find , replace commas, between quotation marks, ":". looking results line = '12/08/2013,3,9:25,42:51,3:08,12:9,13:9,159,170,3:19,437,' so far have been able match pattern with, import re re.findall('(\"\d),(.+?\")', line) however, guess should using re.compile(...something..., line) re.sub(':', line) does know how this? thanks, labjunky >>> import re >>> line = '12/08/2013,3,"9,25",42:51,"3,08","12,9","13,9",159,170,"3,19",437,' >>> re.sub(r'"(\d+),(\d+)"', r'\1:\2', line) '12/08/2013,3,9:25,42:51,3:08,12:9,13:9,159,170,3:19,437,' \1 , \2 refer matched groups. non-regex solution: >>> ''.join(x if % 2 == 0 else x.replace(...

java - How to do right click table row on netbeans? -

Image
into when right click row.after clicked view profile popup , new jframe , display profile. using gui builder. sorry being noob. i'm still beginner.it's hard find on google how right click thing. update2 i created menu how student id cell only... code jmenuitem item = new jmenuitem("view profile"); jmenuitem item2 = new jmenuitem("delete"); item.addactionlistener(new actionlistener() { @override public void actionperformed(actionevent e) { joptionpane.showmessagedialog(studentlist.this, "testing"); } }); jpopupmenu1.add(item); jpopupmenu1.add(item2); and on mousereleased private void tablemousereleased(java.awt.event.mouseevent evt) { int r = table.rowatpoint(evt.getpoint()); if (r >= 0 && r < table.getrowcount()) { table.setrowselectioninterval(r, r); } else { table.clearselection(); } int...

c# - wpf dynamic object explorer -

i new wpf , have searched while following , came noting (not notion how start writing it): i need build gui environment (wpf on c#) support instantiation of classes- meaning want ability design new classes (not in gui), , have gui automatically (dynamically) expose constructors (will let me build instance of class) , expose of properties manipulation - object explorer/ resource manager if will.. the classes decoupled gui- need gui able create instances of them on demand- maybe real life example serve me better: programmer writes new class: public class person { #region members string _name; #endregion #region properties /// <summary> /// artist name. /// </summary> public string name { { return _name; } set { _name = value; } } #endregion } i want gui support creating instances of person , viewing properties (name) without modifying gui code. meant properties instead ...

accessibility - Getting DocBook alt. text to work with apache fop -

i'm in process of writing larger docbook document, , while looks decent enough, i've been asked improve accessibility of it. after reading documentation figured, "that looks simple enough, i'll add <alt> element in there , that'll fix everything!" ...needless wasn't case. the way i've been including keys images 'till now; <inlinemediaobject> <imageobject> <imagedata format="png" fileref="figs/key-down.png"/> </imageobject> <alt>down</alt> </inlinemediaobject> i opted graphic element on using <keycap> in case makes keys in document closer real thing. cover bases i'm testing following, didn't work either: <keycap><alt>down</alt>&#x25bc;</keycap> the screen reading software still can't read alt-text. do need other type of configuration work in screen reading software, aside running fop -a flag? ...

javascript - Jquery must be stopped from closing when inside div is clicked -

http://jsfiddle.net/pfwzg/3/ i have password enter box pops up, , when click anywhere on page, fades out. fades out when try enter password too. kindly appreciated. $(document).ready(function () { $('.chatmic').click(function () { $(".chatmic").toggleclass("chatmicoff"); }); $('.chatloudspeaker').click(function () { $(".chatloudspeaker").toggleclass("chatloudspeakeroff"); }); $('.adminbox').click(function () { $(".passwordcontainer").toggle(); $(".textbox3").focus(); }); $('.adminbox').click(function () { return false; }); $('.adminbox').click(function () { $('.passwordcontainer').fadein('fast', function () { $(".textbox3").focus(); $(document).one('click', function (e) { $('.passwordcontainer').fadeout('fast'); ...

sql - Crystal Report Truncate XML String? -

i using crystal report connecting sql server database. , have database field has xml data on it. if browse data field in crystal report, can see lenght of field 255 characters. stored procedure has column of field looks : alter procedure [dbo].[getdata] ( @id int ) begin select p.id, ,p.name ,dbo.getattributesasxml (scalre-valued-function) field want change it's lenght batch p end here scalre-valued-function : alter function [dbo].[getattributesasxml] ( @productid int ) returns xml begin declare @result xml; select @result = (select * (select at.id id ...

Drupal 6 - execute code after taxonomy term delete -

as title says, how can execute code after taxonomy term deleted. drupal 7 has hook_taxonomy_term_delete, function not available 6. know work around? the corresponding hook in d6 called hook_taxonomy . it called thusly: hook_taxonomy($op, $type, $array = null) where: $op 1 of 'delete' , 'insert' , 'update' $type 1 of 'vocabulary' , 'term' , and $array thing $op being done to. so in case example implementation of hook go this: function example_taxonomy($op, $type, $array = null) { if ('term' == $type && 'delete' == $op) { // execute code here } }

opengl - GLSL - How to avoid polygons overlapping? -

i'm making per pixel lighting shader in glsl. pictured grid of cubes where, depending on order they're drawn, sides should obscured rendered on top of others. not problem when switch fixed function opengl lighting setup. causing it, how fix it? what looks like vertex shader: varying vec4 ecpos; varying vec3 normal; void main() { gl_texcoord[0] = gl_texturematrix[0] * gl_multitexcoord0; /* first transform normal eye space , normalize result */ normal = normalize(gl_normalmatrix * gl_normal); /* compute vertex position in camera space. */ ecpos = gl_modelviewmatrix * gl_vertex; gl_position = ftransform(); } fragment shader: varying vec4 ecpos; varying vec3 normal; uniform sampler2d tex; uniform vec2 resolution; void main() { vec3 n,halfv,lightdir; float ndotl,ndothv; vec4 color = gl_lightmodel.ambient; vec4 texc = texture2d(tex,gl_texcoord[0].st) * gl_lightsource[0].diffuse; float att, dist; /* fragment shader can't write verying variable, hence ...

ios - How not to ask for publish permission everytime? -

i did in facebook [self vsuspendandhaltthisthreadtillunsuspendedwhiledoing:^{ [[nsoperationqueue mainqueue] addoperationwithblock:^{ [self.acastore requestaccesstoaccountswithtype:self.acaccounts options:[self dicpostoptions] completion:^(bool granted, nserror *error) { self.bpermissiontoaccessstoregranted=granted; [self vcontinue]; }]; }]; }]; basically asking publish permission. want check whether such publish permission has been granted or not before asking again. how so? to check permissions available: if(![postrequest.session.permissions containsobject:@"publish_actions"])

gzip - Linux zip a directory excluding some internal directories -

i'm trying zip public_html folder exclusion of 2 folders, this: tar -czf myzip.tar.gz --exclude=home/mydomain/public_html/folder0 --exclude=home/zeejfl6/folder1 /home/mydomain/public_html/ but error: tar: removing leading `/' member names i tried few combinations... doing wrong? it's not error , it's warning . archives containing absolute paths files security risk. imagine archive containing /etc/passwd . if insist upon having absolute paths in archive, use -p option: -p, --absolute-names don't strip leading `/'s file names

apache - Issue with RewriteCond -

ive got issue apache's rewrite module. im trying do: ive got confluence(tomcat) running on server apache reverse proxy in front. also, im using authentification in apache (form auth). if ure trying access [server]/confluence, redirected file login.php containing authentification routine. if login succeeds, proxy lets u access tomcat. every other request blocked. works every request except [server]/login.php file exists indeed in htdocs. every other request handled with fallbackresource wrong_url.shtml now want block direct access login.php stuck in dead end. i tried using rewritecond ${request_uri} phpinfo() gave me this: <server>/confluence (you automatically redirected login.php apache): php says request_uri = /confluence <server>/login.php: php says request_uri = /login.php makes sense, though. did is: <virtualhost *:80> servername 192.168.2.237 rewriteengine on rewritecond %{request_uri} ^/login.php$ rewriterule ^/login.ph...

javascript - JQuery: how to make a superposition of many moving animations which start asynchronously? -

Image
i want make 1 animation superimposed on another. the second (the third, fourth) animation can start asynchronously . need specify difference between new , old positions (not absolute 'left'). e.g. // 1 moment $( '#my_div' ).animate( { 'leftshift': "+20px", 2000, 'easeoutquad' } ); // moment, may second later $( '#my_div' ).animate( { 'leftshift': "+50px" }, 2000, 'easeoutquad' ); is possible add results of several animations? the graph clarify want (x-axis: time, y-axis: speed of distance change). i'd see speeds of animations added, not one-by-one animations. what did roko c. buljan offer? but don't want deferred animations, want real-time animation. note. current syntax ("+20px", "+50px") not supported now. it's example. i solved problem case. i need smooth animation. so, when user initiates new push, should new impulse. so, object mustn...

javascript - Texture update in three.js -

in three.js project try change color texture clicking on image. here goes code: ... var col; document.getelementbyid('image3').onclick = function() { col=("textures/synleder/synleder_col.png"); }; var textures = { color: three.imageutils.loadtexture(col), normal: three.imageutils.loadtexture('textures/synleder/synleder_nrm.jpg'), specular: three.imageutils.loadtexture('textures/synleder/synleder_spec.jpg'), }; textures.color.wraps = textures.color.wrapt = three.repeatwrapping; textures.color.repeat.set( 2, 2); textures.normal.wraps = textures.normal.wrapt = three.repeatwrapping; textures.normal.repeat.set( 2, 2); textures.specular.wraps = textures.specular.wrapt = three.repeatwrapping; textures.specular.repeat.set( 2, 2); var shader = three.shaderlib[ "normalmap" ]; var uniforms = three.uniformsutils.clone( shader.uniforms ); uniforms[ "tnormal...

javascript - prevent IE from wrap in P element in contenteditables -

suppose have contenteditable div in page, when user starts type div , ie wraps user input p element, ff not question how prevent ie behavior? thanks here's basic snippet task, can develope further. function keydown (e) { var range = document.selection.createrange(); if (e.keycode !== 13) return; range.pastehtml('<br>'); e.cancelbubble = true; e.returnvalue = false; return false; } if (pad.attachevent) { pad.attachevent('onkeydown', keydown); } the code using ie's legacy selection/range , eventhandling models, works in ies. can play code @ jsfiddle .

Android Launcher Live Wallpaper -

so i'm making android launcher app. done, without live wallpaper support. can't find on subject. can set wallpaper, choosing gallery, can't find way live wallpapers. i'm using imageview display static wallpaper. ideas how choose , set live wallpaper? on should set too? don't think work on imageview. thanks.

c# - Remove duplicate from the following list using Linq -

i have class items properties (id, name, drugcode1, drugcode2). the list of items populated duplicated items. for eg.: ------------------------------------------ id name drugcode1 drugcode2 ------------------------------------------ 1 item1 2 3 2 item2 3 2 3 item3 4 3 1 item1 3 2 3 item3 3 4 if durgcode1 , drugcode2 reversed consider items duplicates eg: 1 item1 2 3 1 item1 3 2 the above 2 itmes considered duplicate since drugcode1 , drugcode2 reversed. need fetch 1 item. how remove duplicates in list using linq? since have not tagged linq-provider presume linq-to-objects . use anonymous type in same order groupby : ienumerable<item> distinctitems = items .groupby(i => new { min=math.min(i.drugcode1, i.drugcode2),max=math.max(i.drugcode1, i.drugcode2) }) .select(g => g.first()...

c# - Can't load .dll file (HRESULT 0x80070002) -

Image
eclipse .dll file plug-in of mine needs execute. full path of file: c:\eclipse\eclipse-sib\eclipse\configuration\org.eclipse.osgi\bundles\324\1\.cp\jni4net.n.w32.v20-0.8.6.0 trying open this: public class main { public static void main(string[] args) { file f = new file("c:\\eclipse\\eclipse-sib\\eclipse\\configuration\\org.eclipse.osgi\\bundles\\324\\1\\.cp\\jni4net.n-0.8.6.0.dll"); system.out.println(f.getname() + " " + f.getabsolutepath()); } } does work! output: jni4net.n-0.8.6.0.dll c:\eclipse\eclipse-sib\eclipse\configuration\org.eclipse.osgi\bundles\324\1\.cp\jni4net.n-0.8.6.0.dll but run plug-in file gets accessed receive following: using fuslogvw.exe says same: *** assembly binder log entry (26.08.2013 @ 13:53:35) *** operation failed. bind result: hr = 0x80070002. system cannot find file specified. assembly manager loaded from: c:\windows\microsoft.net\framework\v2.0.50727\mscorwks.dll running under executable c:...

security - Limiting number of statements in a SQL query in JDBC -

is possible @ jdbc? to emphasise more, consider following query common in sql injection: statement.execute("select * x; drop table y;"); is there workaround execute first statement here? possible in of nosql databases.

multiple functioning using java and spring framework -

i using spring , i need send mail 10000 users.now waiting in page till mails sent.but dont want wait.i need give task class execute automatically after handover,then need continue task. how can this? thanks in advance... the @async annotation the @async annotation can provided on method invocation of method occur asynchronously. in other words, caller return upon invocation , actual execution of method occur in task has been submitted spring taskexecutor. source

lucene - Fulltext search in Mongodb using Hibernate Ogm -

Image
i want implement fulltextsearch in mongodb using hibernate ogm. wrote code, code returns me empty result. have checked 2 files, produced lucene luke, seems both of them empty. don't know cause of problem. i have enabled fulltext search in collection command: db.admincommand( { setparameter : "*", textsearchenabled : true } ); and have put index on userid field in users collection. db.users.ensureindex({userid:1 }) also have entity class: @entity @indexed @table(name="users") @genericgenerator(name="mongodb_uuidgg",strategy = "uuid2") public class user implements serializable{ private static final long serialversionuid=1l; @documentid private string id; @column(name="city") @field(index = index.no,analyze = analyze.yes,store = store.yes) private string city; @column(name="userid") @numericfield @field(index = index.yes,analyze = analyze.no,store = store.yes) privat...

CakePHP routes with sub-folders -

i have problem cakephp route router::connect( '/catalog/:slug/:slug2/*', array( 'controller'=>'pages', 'action'=>'view' )) when have url /catalog/something/page:2 - catches link. shouldn't, because there no slash after params page:2 , how fix it? thanks!! i hope may helpful. router::connect( '/catalog/:slug/:slug2/*', array( 'controller'=>'pages', 'action'=>'view' ), array('pass' => array('slug', 'slug2'))); and in view file can write generate link above. echo $this->html->link('link', array( 'controller' => 'pages', 'action' => 'view', 'slug' => 'slug', 'slug2' => 'slug2' ));

python - Django don't see dj_database_url -

i want deploy django app on heroku. when try sync db localy error message: importerror: not import settings 'aplikacjakz.settings' (is on sys.path?): no module named dj_database_url i installed dj database url. requirements file: django==1.5.1 argparse==1.2.1 distribute==0.6.34 dj-database-url==0.2.2 dj-static==0.0.5 django-toolbelt==0.0.1 gunicorn==17.5 psycopg2==2.5.1 static==0.4 wsgiref==0.1.2 this settings: databases = {'default': dj_database_url.config(default='postgres://localhost')} databases = { 'default': { 'engine': 'django.db.backends.sqlite3', 'name': '/var/db/appkz', 'user': '', 'password': '', 'host': '', 'port': '', } } heroku has been kind enough explain process in details here h...

php - preg_replace all occurrences in string withing defined delimeters -

i trying replace occurrences of " a " " b " inside string. problem need replace letters inside brackets: asd asd asd [asd asd asd] asd asd asd for have code: $what = '/(?<=\[)a(?=.*?\])/s'; $with = 'b'; $where = 'asd asd asd [asd asd asd] asd asd asd'; but replaces first "a", , getting result: asd asd asd [bsd asd asd] asd asd asd i realy need done 1 preg_replace call. you cannot single preg_replace call because lookbehind need "there opening square bracket somewhere before match" , impossible since lookbehind patterns must have fixed length. why absolutely need in 1 call anyway? doable pretty preg_replace_callback , match groups of content inside square brackets , use preg_replace on match each time (or simple str_replace if going replace "a" "b"). example: $what = '/\[([^]]*)\]/'; $where = 'asd asd asd [asd asd asd] asd asd asd'; echo p...

Create ubercart Pre Order drupal 7 -

i looking solution create pre-order function using ubercart 3 , drupal 7 basically creating website whereby registered retail customers can place orders online using website want add products site have not arrived yet , have add order button display pre-order , show eta of when product arriving. anyone have idea how can achieve ? the estimated time of arrival can simple product date field set. also, since want product available preorder can alter button label using hook_form_alter . , if statement button (so alter products have preorder) eta field above or helper field of boolean type enable "preorder" state.

if statement - R - calculating values assigned to the same number -

i have question regarding data: data = 1 time 3 2 20 0 3 20 0 4 20 0 5 350 1 6 350 1 7 350 1 8 10 0 9 20 1 10 37 0 11 37 0 12 50 1 13 50 1 14 40 0 15 40 0 16 40 0 i want summarize time spent looking @ 1 (as indexed in column 3). time assigned total looking time when 1 looked @ - need summarize first time when 1 newly indicated - 350 + 20 + 50. an if -loop like: if (data$3 == 1) { sum <- data[:,2] } does not work, values summarized. need addresses first 1 after 0. use ddply plyr package (mydata data , col3 column 3 in data name col3. mydata > mydata col1 time col3 1 1 20 0 2 2 20 0 3 3 20 0 4 4 350 1 5 5 350 1 6 6 350 1 7 7 10 0 8 8 20 1 9 9 37 0 10 10 37 0 11 11 50 1 12 12 50 1 13 13 40 0 14 14 40 0 15 15 40 0 library(plyr) ddply(mydata,.(col3), summarize, mysum=sum(unique(time))) col3 ...

How to download Google Apps Script? -

i'm writing little ruby script sync google apps script files. i'm following instructions google developers , examples on github (google/google-api-ruby-client-samples). after getting list of project files i'm trying content of each file. proposed in guide fetch the export-links url: result = google_client.execute(:uri => file_data['exportlinks']['application/vnd.google-apps.script+json']) the problem http status 302 , html content telling me document has moved. opening url in browser downloads file correctly. guess due authentication functionality. there way make client library handle properly? fetching normal document in format works fine way... the complete code can found on github: https://github.com/devex/gaspm you can get https://script.google.com/feeds/download/export?format=json&id=[fileid] same access token use authorize other drive api requests.

android - Accessing fragment method from async task -

first off, practice, accessing fragment's method asynchronous task? i have async task generates list of latlng use in fragment draw polyline. however, if try use getter method list. public list<latlng> getlist() { return this.list; } i nullpointerexceptions have perform inside fragment, while(list == null) { // fixme delay because of list = getroute.getlist(); } which defeats purpose of having background task. is there way can call method within async task's post execute method? @override protected void onpostexecute(otpresponseui otpresponse) { fragment.fragmentsmethod(getlist()); mdialog.dismiss(); } this way can correctly show process dialog , not leave user hanging while loads list. update tried invoking callback this callback function in fragment not executed. update2 ok passed fragment instance async task able call fragment method. per advice: create list object in custom asynctask clas...

python - How to parse INI style file -

i have file in format similar ini [name1] valu1 [name2] value2 [section] [name3] valu3 how parse such files in python use configparser , documentation description: this module defines class configparser. configparser class implements basic configuration file parser language provides structure similar find on microsoft windows ini files. can use write python programs can customized end users easily.

java - Spring configuration: How to export util:list based bean in osgi:service? -

i have bean defined <util:list id="mylist"></util:list> now need export <osgi:service> . this <osgi:service ref="beantobeexported" interface="com.xyz.messageservice"/> but don't know set interface. me? and cardinality set in <osgi:reference> ? you can use bean-name attribute. bean-name convenient shortcut specifying filter expression matches on bean-name property automatically advertised beans published using service element. <osgi:service ref="mylist" interface="java.util.list"/> <osgi:reference id="myid" bean-name="mylist" interface="java.util.list" /> you use service properties , filter expressions instead bean-name more straightforward. you can read more here .

angularjs - How to modify a scope's value within a directive -

within directive, i'd modify expression's value when button clicked. below code modifying value locally within directive. i'd change value outside of directive well. how can accomplish that? scope: false, link: function (scope, el, attrs) { //toggle state when clicked el.bind('click', function () { scope[attrs.ngmodel] = !scope[attrs.ngmodel]; }); plunker: http://plnkr.co/edit/xqybnz5bhlp844kxjxks?p=preview the problems binding expression in ng-model. since has '.' in it, need use $parse , set value correctly. see documentation here something like var getter=$parse(attrs.ngmodel); var setter=getter.assign; setter(scope,!getter(scope)); see updated plunkr here http://plnkr.co/edit/vae43y5cagcf8jq5alay?p=preview basically setting scope[attrs.ngmodel] = !scope[attrs.ngmodel] creates new property user.active . set should scope['user']['active'...

Is there any way we can remove watch in angularjs -

angularjs watches dom elements,many elements means watches created. there way can remove unneeded watch? i hope helps : remove watches in angularjs

c# - REST API Put large data -

i have rest api implemented in microsoft web api. in client use httprequestmessage , httpresponsemessage. when sending small class, serialize json , send it. soon, class becomes bigger, , need json class, zip (in memory) , send server. can no longer use same technique, need send zip in chunks. what proper way achieve ? have read post posting file , associated data restful webservice preferably json need articles, dont know start. on client side should work pretty out of box... var httpclient = new httpclient(); httpclient.defaultrequestheaders.transferencodingchunked = true; var content = new compressedcontent(new streamcontent(new filestream("c:\\big-json-file.json",filemode.open)),"utf8"); var response = httpclient.postasync("http://example.org/", content).result; you can find implementation of compressedcontent in webapicontrib . if using earlier .net 4.5 request buffered client side befor...

ios - how prevent cell width from expanding when done editing in UITableView -

Image
if notice in ipad contacts app when tap on "+" edit icon add new address, cell not expand left when icon disappears (see 1st screen capture below). trying similar having no luck (see 2nd screen capture below). tried using solution suggested here didn't work. for record not trying replicate actual contacts app or integrate contacts. we're working on unrelated , designer wants follow pattern doing poc work see can do. edit - question, verify thinking, in contacts app here what's happening when "+" icon tapped, cell set not editing more, these text fields added cell, label changed, , reloaddata called, right? edit - suggestion tim, i'm there! had worked out 1/2 of running issue "+" icon not animating out, abruptly disappearing. added reloadrows... call commiteditingstyle entire cell disappears. here code: - (uitableviewcelleditingstyle)tableview:(uitableview *)tableview editingstyleforrowatindexpath:(nsindexpath *)indexpath { ...

vba - change cell properties from an excel file open with a wsf script -

i have wsf script, vritten in visual basic, run db2 query , save results in file .csv . function creacsvdasql (sql,filecompletepath) dim input , conn,rs,csvtext,fso,fs,line set conn = createobject ("adodb.connection") conn.open _ "provider=sqloledb.1;initial catalog=xxxx;data source=xxxxx;mars connection=true;user id=xxxx;password=xxxx" set rs = conn.execute (sql) line = "" dim tmp each tmp in rs.fields line=line & tmp.name & ";" next if (not rs.eof) csvtext = line & vbcrlf & rs.getstring (2,, ";", vbcrlf) rs.close: set rs = nothing conn.close: set conn = nothing dim l_sn l_sn = replace (now, "-", "") l_sn = replace (l_sn, ":", "") l_sn = replace (l_sn, "", "") set fso = createobject ("scripting.filesystemobject") set fs = fso.createtextfile (filecomp...

multithreading - Invoking code inside a thread that has already been started in java -

how can run code inside custom thread has started? i need run code inside started thread edt-swingutilities.invokelater() or android.view.runonuithread() does. thanks! if expect able on thread not otherwise dedicated accepting tasks execution, answer simple: ask impossible. way accomplish explicit cooperation thread on want this. if above paragraph did not discourage you, best option use executorservice , submit tasks it. service can configured single-threaded, if goal.

php - How to create array with values that exists in longer array and does not exists in shorter array? -

have 2 php arrays. one array created input values (array named $date_and_currency_array_for_comparision ). array ( [0] => array ( [currencyabbreviation] => usd [dateofcurrencyrate] => 2013-07-22 ) [1] => array ( [currencyabbreviation] => cad [dateofcurrencyrate] => 2013-07-11 ) [3] => array ( [currencyabbreviation] => czk [dateofcurrencyrate] => 2013-07-31 ) ) another array created values in mysql (named data_select_currency_rate ) array ( [0] => array ( [currencyabbreviation] => cad [dateofcurrencyrate] => 2013-07-11 ) [1] => array ( [currencyabbreviation] => czk [dateofcurrencyrate] => 2013-07-31 ) ) need create array values first array if these values not exist in second array. at first tried $curren...

ruby on rails - How to validate price in input? -

i have input (it's text input) users can set price. problem is, users can set price this: 9 9.99 9,99 $9.99 what's best way validate input? running app on heroku (= postgresql database), data type column decimal . try below. matches examples. validates :price, :presence => true, :format => { :with => /^(\$)?(\d+)(\.|,)?\d{0,2}?$/ }

ios - Different App Icons based on Bundle ID in Build Phases->Run Script -

i had idea have both app store version of application , development version of application on phone. have accomplished changing bundle id. curious if there way write script determine bundle id is, , change app icon based on id is. ideas on how go this? far have script: bundle_id=$(/usr/libexec/plistbuddy -c "print :cfbundleidentifier" "${build_root}/${infoplist_path}") normal_id="com.appname" if [bundle_id != normal_id]; // set testing app icon else // use normal app icon fi you're looking this: http://nilsou.com/blog/2013/07/29/how-to-have-two-versions-of-the-same-app-on-your-device/

Android How to know which Contacts have my application installed? -

i'm creating application need know in contacts has application installed on phone. have contact list in listview displayed in application, contacts shown need restricted have application installed. there way tell? thanks! you're gonna have store information somewhere in cloud. you need activity or service store user information somewhere (eg dababase) , you'll have info users there in order filter list view's adapter.

Logging/Tracing-Lib for .Net -

i need swap log4net other logging library has build-in functionality @ least these requirements: filelogging (text) archiving size , date (no archive should ever deleted) archiving zip/compressed file possibility configure archiving in way, have 1 zip file per day i did try of major libraries nlog , smartinspect none offer functions move archived/rolled files zip file. for log4net did implement functionality myself new project customer not want use log4net... would possible extend nlog nlog.extended this? or know other lib allready has "features" (free or commercial)? thanks in advance rene rene - serilog 's free , has simple model plugging in sinks. i'd recommend copying source of rollingfilesink class github repository, , adding few lines of code zip "outgoing" file on roll. plugging custom sink in easy: var log = new loggerconfiguration() .writeto.sink(new zippedrollingfilesink("c:\\logs\\myapp-{date}.txt")...

javascript - Drop down list of products has a different ID each time page is loaded -

i using selenium ide repetitive form filling tasks web app. part of process involves selecting group of products , choosing of base products group. example: want see painting , wallpaper products under diy , hardware section. in selenium correctly identifies , selects diy , hardware section. generates new set of drop down lists appear then, should able choose 'paint' , 'wallpaper'. selenium gives error here: [error] element id=selectgroup_rt_paint_ca9368dd-ddc0-4ade-a17f-f0e5a56e5e23_1 not found the problem letter , number sequence after rt_paint appears unique value each time drop down lists generated, though contain same values. there way around this? this html of selenium task: <tr> <td>select</td> <td>id=selectgroup_rt_paint_ca9368dd-ddc0-4ade-a17f-f0e5a56e5e23_1</td> <td>label=dulux</td> </tr> i'm new selenium don't know try, hence no code example. there w way change id like... rath...

c++ - I am stuck with creating an output member function -

i stuck on output member function of class. have no idea how create , couting not seem work. other advice great. in advance here's code: #include <iostream> #include <string> #include <vector> using namespace std; class stringset { public: stringset(vector<string> str); void add(string s); void remove(int i); void clear(); int length(); void output(ostream& outs); private: vector<string> strarr; }; stringset::stringset(vector<string> str) { for(int k =0;k<str.size();k++) { strarr.push_back(str[k]); } } void stringset::add(string s) { strarr.push_back(s); } void stringset::remove(int i) { strarr.erase (strarr.begin()+(i-1)); } void stringset::clear() { strarr.erase(strarr.begin(),strarr.end()); } int stringset::length() { return strarr.size(); } void stringset::output() { } int main() { vector<string> vstr; string s; for(int i=0;i<10;i+...

java - Adding JScrollPane in JTextArea using GridBagLayout -

i'm having issue adding jscrollpane in jtextarea using gridbaglayout. program runs fine when scrollbar isn't needed layout gets messed , content gets cut off when is. relevent code follows import java.io.*; import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.util.*; public class testgui extends jframe { public static string name; static jtextfield textfield = new jtextfield(30); static jtextarea textarea = new jtextarea(30,30); public static void main( string[] args) { jframe frame = new jframe(); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.settitle("checkem"); frame.setlocation(500,400); frame.setsize(800,800); jpanel panel = new jpanel(new gridbaglayout()); gridbagconstraints c = new gridbagconstraints(); jscrollpane scrolltxt = new jscrollpane(textarea,jscrollpane.vertical_scrollbar_as_needed,jscrollpane.horizontal_scrollbar_never...

settings - Enable Android System Touch Sounds -

i'm trying enable/disable touch sounds programmatically service. what did until is: settings.system.putint(getcontentresolver(), settings.system.sound_effects_enabled, sound_effects); sound_effects can 0 (disabled) or 1 (enabled) but doesn't affect general settings - settings in android os remain unchanged ... if manually change them, above code doesn't change them accordingly. how change settings programmatically ? keytone, touch sounds, screen lock sound ? thanks i think u missing permission . add following permissions. public static final string modify_audio_settings constant value:android.permission.modify_audio_settings" public static final string write_settings constant value: "android.permission.write_settings"

jquery - How can I make a sync call with backbone fetch -

i need call fetch synchronous call, know jquery ajax can use {async: false} can pass option fetch function ? so short answer yes, can simple call fetch function param {async:false}.

django-dynamic-fixture foreign key to self -

i have tests.py looks this: from django_dynamic_fixture import g,n person.models import person django.test import testcase class emailsendtests(testcase): def test_send_email(self): person = n(person) my person model looks this: class person(models.model): person_no = models.integerfield(primary_key=true) address = models.foreignkey('address', db_column = 'address_no') guarantor = models.foreignkey('person', db_column = 'gperson_no') when run tests, following: valueerror: cannot assign none: "patient.guarantor" not allow null values. how create django_dynamic_fixture object has foreignkey pointing itself? from understand n function doesn't assign id, since it's not generated in db, maybe reason: https://github.com/paulocheque/django-dynamic-fixture/wiki/documentation#wiki-n other thing, instead guarantor = models.foreignkey('person', db_column = 'gperson_no') yo...

content management system - Orchard CMS Driver's Editor Override Not Firing -

using orchard 1.7. the goal: create collection of we're calling page filters. to create many many part followed tutorial steps described here the problem: editor override in driver class never hit , empty create page nothing save button being returned. model classes: namespace mylib.orchard.hyperlinkitemmanager.models { public class hyperlinkpagefilterrecord { public virtual int id { get; set; } public virtual int pageid { get; set; } } } namespace mylib.orchard.hyperlinkitemmanager.models { public class hyperlinkpagefilterscontentrecord { public virtual int id { get; set; } public virtual hyperlinkpagefilterspartrecord hyperlinkpagefilterspartrecord { get; set; } public virtual hyperlinkpagefilterrecord hyperlinkpagefilterrecord { get; set; } } } namespace mylib.orchard.hyperlinkitemmanager.models { public class hyperlinkpagefilterspart : contentpart<hyperlinkpagefilterspartrecord> { ...