Posts

Showing posts from March, 2015

refactoring - How to move function declaration to another file yet retain Git history? -

i refactoring single-file php script declare functions , classes in separate files. how 1 move block of code 1 file file yet preserve git history each individual line? ability use @ least git blame on code. comparing older versions helpful. note not interested in 'workaround' solutions require additional commands or flags (such --follow ) on code view 'old' history, person viewing history have know file needs special treatment. looking solution writes necessary metadata such normal git commands such blame , log , diff , , such 'just work' without presenting them additional flags or arguments. i have read quite few posts looking solutions similar problems , none address issue of git blame on individual lines. 1 solution think work copy file , entire history , work off of that. however, question remains without satisfactory answer. warning: assumes rewriting history acceptable. not use unless know implications of rewriting history. to spl...

ruby on rails - how to append unique string at the end of resource routes in rails4 -

i tried rails guide , searched lot can find answer. trying generate secret post scaffold in rails 4 using scaffold generator scenario : users can create secret posts , link secret token in future works verification string rails g scaffold secret title:string content:text token:string i want append token value in "secret_posts" routes eg: : secret/1/sadkljaldjlak : secret/1/edit/sasadadallkha i want use token unique code verification . appreciated first, create migration chance token:string token:text, use secureramdom.urlsafe_base64 generate token, use code on model: def secret_token if self.new_record? self.token = securerandom.urlsafe_base64 end end after that, create route this: get 'secret/:edit_hash/edit', to: 'secret#edit', as: :secret_offer patch 'secret/:edit_hash', to: 'secret#update' put 'secret/:edit_hash', to: 'secret#update' and on c...

Facebook Search API, keyword search does not display posts made in a page but only in a profile -

i using facebook search api find posts include keyword. noticed posts returned belong facebook profiles never facebook pages. up, searched keywords of low frequency spotted in pages api did not return them. is there way can search keyword , posts pages ? taking @ the documentation : search &type=post . documentation: all public posts: https://graph.facebook.com/search?q=watermelon&type=post

php - How to pass current URL to mailto body -

i have problem passing url mail body. have use this: <?php function currentpageurl() { $pageurl = $_server['https'] == 'on' ? 'https://' : 'http://'; $pageurl .= $_server['server_port'] != '80' ? $_server["server_name"].":".$_server["server_port"].$_server ["request_uri"] : $_server['server_name'] . $_server['request_uri']; return $pageurl; } ?> and mailto:?body=<?php echo currentpageurl(); ?> instead of link result: http://www.something.com/index.php?id=03new&new=50&lang=en i 1 in mail body: http://www.something.com/index.php?id=03new please me how pass link including "&". thx '&' used in mailto separate different parts like: &subject=some_subject&body=message_body so interpreted (invalid) parameter mailto (and omitted). if want have '&' (and rest of url) inside body, needs replaced % val...

c# - KeyNotFoundException unhandled by user -

i trying retrieve query string value inside mainpage.xaml.cs , need access value accessing html id on different page(aspx). point if try access code querystring value not exist keynotfoundexception. i have tried overcome problem doing following htmldocument htmldoc = htmlpage.document; if (htmldoc.querystring["productcode"] != null) { productcode = htmldoc.querystring["productcode"].tostring(); } else { productcode = htmldoc.getelementbyid("vidweeklyfeature").getproperty("value").tostring(); } but still same exception. how can retrieve value based on condition value can accessed querystring or not? (sorry being bit inarticulate) you can use trygetvalue method rather use indexer. it this: htmldocument htmldoc = htmlpage.document; string productcode; if (!htmldoc.querystring.trygetvalue("productcode", out productcode)) { productcode = htmldoc.getelementbyid("vidweeklyfeature").getproperty(...

java - How to remap stripped text position to pdf document position -

i use pdfbox's pdftextstripper extract plain texts 2 pdf files compared using nlp algorithm. algorithm returns postions of common passages of plain texts. what want highlight common passages in pdf. problem have position in plain text not corresponding position in pdf. using pdftextstripper mapping lost. are there solutions/common approaches preserve mapping plain text position pdf document position while stripping text pdfs? accept use different pdf library if supports have use java.

jquery - Why dropdown menu doesn't work in IE9? -

i have dropdown menu works fine in browsers except ie9 . menu http://jsfiddle.net/7xuxv/2/ have no idea why doesnt'work! if have internet explorer 10 , want test in ie9 have hitting f12 on ie10 should start developer tools allows emulate ie9 using browser mode [read more] . any appreciated. thank much. you problem is: z-index: 1 !important; remove in css , works.. yet find why

Create a task in SQL or Windows Server to clean a directory nightly -

i have temp directory on website users export data in .csv files. the newer intranet apps delete file after it's sent client legacy apps leave files in directory. i'd create task clean directory nightly. there can .csv files , directories files in them. basically want run: del *.* /s rd /s ...every night @ midnight. would love sql maintenance task runs on actual sql server , doesn't work mapped drives (unless i'm missing something). how 1 go performing task? can done through sql server somehow? you have option of creating "jobs" run stored procedures or bits of code. these jobs can scheduled run daily, weekly, etc. check out thread: how can create sql agent job in sql server 2008 standard?

How to turn on visualchars on startup in tinyMCE 4 -

i want have visualchars button , functionality turned on editor initiated. tiny mce version 4 only , non jquery version. why? don't know nbsp bad? no, not trying offend god of html correctness. non breaking spaces compulsory in french text in several common instances (before question marks, exclamation marks, colons, semi colons name few occasions). i want see non-breaking spaces are... ... , missing because review content created else (e.g. copy/pasted pdf or word), , speaking check text proper french typography. here how call editor: var ed = new tinymce.editor('tinymce1', { plugins: [ 'advlist link image charmap pagebreak', 'searchreplace wordcount visualblocks visualchars code fullscreen media nonbreaking', 'table template paste' ], language: 'fr_fr', element_format: 'html', keep_styles: false, paste_as_text: true, content_css...

3d - OpenGL ES 2.0 - How to realistically deform a sphere? -

i want design 3d physic engine android application. using opengl es 2.0. this want : let's have sphere @ center of device's screen. suppose sphere filled water (like water balloon). because of gravity, expect sphere deformed @ bottom. furthermore, using accelerometer of phone, can shift gravity, changing deformation of sphere. i have made lot of research, still have no idea how that. don't think it's hard do, way can think of how manually draw, frame frame, different shapes. is there way of generating deformation, instead of drawing 'by hand' ? maybe using shaders ? i'm lost right ! thank help. if want in 3d, in realistic way - has nothing opengl es, , require advanced physics engine. shaders used render results. unless need simple deformation of 2d picture of 3d sphere, frankly, judging way ask question - hard you.

php - How do I test a command-line program with PHPUnit? -

how test command-line program phpunit? see plenty of using phpunit command line, none testing command-line program phpunit. this comes because writing command-line programs in php , joomla, don't see way test output, when errors occur (because cannot test error output using phpunit's expectoutputstring() ). (edit: note bulk of code in classes tested phpunit -- i'm looking way test command-line (wrapper) program's logic.) one way use backtick operator (`) capture output of program, examine output. works under unix/linux-style oses, can capture error outputs stderr. (it more painful under windows, can done (especially using cygwin).) for example: public function testhelp() { $output = `./add-event --help 2>&1`; $this->assertregexp( '/^usage:/m', $output, 'no message?' ); $this->assertregexp( '/where:/m', $output, 'no message?' ); $this-...

jsf 2 - index page rendered as xml instead of html -

this question has answer here: why jsf + spring web application output jsf source code instead of interpreted html page? 1 answer i have web app have tested locally , works fine, on deployment production server (manually without netbeanside) on glassfish 3.1.2 , deploys on running url see xhtml content instead of applications login page. missing. if have tried re-deploying war file no luck. ui:composition xmlns:ui='http://xmlns.jcp.org/jsf/facelets' template='/web-inf/templates/temp.xhtml' ui:define name='dynamiccontent' ui:composition instead of actual html markup i found out problem netbeans ide using glassfish4, , production 3.1.2, after installation , configuration of v4 on production ok.

vocabulary - Some Jena vocabs use 'ResourceFactory.createProperty()' while others use 'ModelFactory.createDefaultModel().createProperty()' -

i'm new jena, when @ vocabularies defined jena source (i.e. in directory: jena-2.10.0-source\jena-core\src\main\java\com\hp\hpl\jena\vocabulary ) see of vocabularies create properties , resources using 'resourcefactory.createproperty()' (e.g. owl2.java, rdf.java, rdfs.java), whereas others in same directory use 'modelfactory.createdefaultmodel().createproperty()' (e.g. dc_11.java, vcard.java, dcterms.java). i understand resourcefactory used create resources , properties without reference 'model' , want understand why of these vocabs choose create , use 'model' instance while others choose not to. is personal style, or 1 approach recommended on other (maybe 1 style 'old approach', understand jena has been around long time)? i'd use both rdfs , dc_11 vocabs code, , define own app-specific resources , properties, i'm trying understand approach should adopt own stuff. that both styles used historical accident. think ...

java - Spinner shows the selected item in Android -

in program have spinner show 3 string s taken arraylist<string> . use code: pinnerarray = new arraylist<string>(); spinnerarray.add("it"); spinnerarray.add("en"); spinnerarray.add("pr"); arrayadapter lenguageadapter=new arrayadapter(convertview.getcontext(), r.layout.lenguage_item_layout, spinnerarray); holder.spinnerlenguage.setadapter(lenguageadapter); my spinner shows it and, when click on it, opens list of items. in list there 3 items ( it , en , pr ) want show selected item (in case it ) 1 time , not 2 times. how can correct code?

Shell command not working via exec() in php -

i'm executing php function via php exec() function seems pass through 1 variable @ time. $url = "http://domain.co/test.php?phone=123&msg=testing" exec('wget '.$url); within test.php file have $msg = "msg =".$_get["msg"]." number=".$_get["phone"]; mail('me@gmail.com', 'working?', $msg); i email returns phone variable only. but if change url follows $url = "http://domain.co/test.php?msg=testing&phone=123" i msg not phone ? ideas on causing strange behavior? the & sign special character in unix shell. need escape it: exec("wget '$url'"); also, if url based on user input in way, careful escape escapeshellarg . otherwise users able run arbitrary unix commands on server.

assembly - How to determine location of _main in x86-64 executable? -

i interested in constructing cfg x86-64 executable using static methods. having trouble including "main" function because there no precomputed jumps main function; appears jump may not computed until program run. such, cfg missing 1 of important functions - main one! how can statically determine location of _main? for further information read microsoft pe specification . getting entry point address base of actual pe executables (term image preffered in documentation) lies in old dos .exe mz executables. first 2 bytes of every executable ascii 'm' , 'z'. nowadays, dos header skipped. used contain values such starting cs , ip , ss or sp . get value @ offset 0x3c in file. start of pe header. pe header stores fields target machine, number of sections , on. these things not important you. you can skip whole pe header. (add 0x14 pointer - sizeof(pe_header_s)==20 ) after adding 20 bytes pointer, you're pointing start of pe optiona...

javascript - Node.js concat array after async.concat() -

i have array, need recompile use of edits. of async.concat() , not working. tell me, mistake? async.concat(dialogs, function(dialog, callback) { if (dialog['viewer']['user_profile_image'] != null) { fs.exists(im.pathtouserimage + dialog['viewer']['user_profile_image'].replace('%s', ''), function(exits) { if (exits) { dialog['viewer']['user_profile_image'] = dialog['viewer']['user_profile_image'].replace('%s', ''); } callback(dialog); }); } }, function() { console.log(arguments); }); in opinion, logical. callback invoked after first iteration. how can send data after completion of processing entire array? thank you! instead of callback(dialog); , want callback(null,dialog); because first parameter callback function error object. reason console.log(arguments) getting called after first iter...

fortran90 - Read integer statement -

i quite new fortran , have question. need read 2 integers following line: k=234, l=241, i=0 i not interested in last value. need integers 234 , 241. tried read(20,'(3x,i3,3x,i3)')a,b it compiles, when run program error message: at line 27 of file test.f90 (unit = 20, file = 'int_p2.dat') fortran runtime error: bad value during integer read don't know doing wrong. can give me advice? you have strings in line, read statement ought account it. should replace with read(20, '(3(a2,i3,2x))') dumchar, k, dumchar, l, dumint, dumchar where dumchar character of length 2 , dumint integer.

sql - Error while inserting into database c# -

there no error clarification i trying insert table called "test" has 1 column, primary key called "id". new using databases in visual studio , think there wrong insert syntax since other functions work fine. general layout this? using (sqlcommand command = new sqlcommand("insert test (id) values(1)", conn)) overall code looks this: class program { static void main(string[] args) { string connection = "data source=.\\sqlexpress;" + "user instance=true;" + "integrated security=true;" + "attachdbfilename=|datadirectory|haythamservice.mdf;"; try { using (sqlconnection conn = new sqlconnection(connection)) { conn.open(); using (sqlcommand command = new sqlcommand("insert test (id) values(1)", conn)) { command.executenonquery(); ...

mysql - Which server to choose -

i run centos 6 server on media temple great needs have had issues installing ffmpeg , various packages. of yum installs old. below list of other packages available. ubuntu 12.04 - lts precise ubuntu 12.10 - quantal ubuntu 10.04 - lts lucid ubuntu 13.04 - raring fedora 18 debian 7.0 - wheezy debian 6.0 - squeeze centos 6 what advantages of above? how different really? looking build website lot of video , audio manipulation server side. is there 1 deals better other? not me wrong. centos server has been great. trying decide whether stick centos new hosting, or whether there advantage me use 1 above list. install ubuntu 12.10 on local , see how handles packages need. find better when comes package management, dependency resolving, package compatibility ect.

url - Implement a "Cancel" link in Struts 2 that returns to the previous page, one of multiple callers? -

i need implement link on page "cancel" takes user page on. think can use dynamic result have caller pass in action need return to. described in: struts2 - how dynamic url redirects? but each of callers have different parameters page specify state in. how reset state action variables before redirect previous action? you need save state "caller" in session , , pass reference via parameter of action. using parameter value retrieve state , reinitialize action. it's done if save request url of "caller" in session , redirect on "cancel" redirect result supplying url dynamic parameter.

iphone - How to get SQLITE database file to sync in DropBox? -

i working on ipad app.here want upload whole database file dropbox.i searched on google didnot found appropriate solution.i used following code create database. -(bool) createdatabasefile { nsstring *docsdir; nsarray *dirpaths; nsfilemanager *filemgr = [nsfilemanager defaultmanager]; bool successmsg = yes; // documents directory dirpaths = nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes); docsdir = [dirpaths objectatindex:0]; // build path database file self.detaildatabasepath = [[nsstring alloc] initwithstring:[docsdir stringbyappendingpathcomponent:@`"database.sql"`]]; // check existence of database file if ([filemgr fileexistsatpath:self.detaildatabasepath]) { //file exists @ path } else { //since file not available @ path create database file successmsg = [filemgr createfileatpath:self.detaildatabasepath contents:[nsdata data] attributes:nil]; } return successmsg; } so how can "database.sql" file.pleas...

c# - Reload treeview and open in one place - Dynatree -

i'm trying recharge treeview using dynatree , expand in same place left off, can not. i'm carrying whole, making query in mvc using oracle , returning shortlist dynatree keys defined. my code: $("#tree").dynatree({ selectmode: 3, clickfoldermode: 3, initajax: { type: "post", url: "/controller/gettree" } }); to recharge record insert via ajax mvc, way upgrade give reload treeview, so: $("#tree").dynatree("gettree").reload(); then try expand or getnodebykey use, still not work $("#tree").dynatree("getroot").visit(function (node) { node.expand(true); }); thanks there cookie persistence functionality or can tree.selectkey(val).expand(); val key of need expand. you can use generateids:true; option when creating tree can access directly nodes if know id , can use jquery selector.

java - Verifying private constructor is not invoked/called using JMockit -

i have following class. public task { public static task getinstance(string taskname) { return new task(taskname); } private task(string taskname) { this.taskname = taskname; } } i testing task.getinstance() using jmockit. while test, need verify call private task() made. have used verifications block earlier verify method execution on test fixture object, here don't have that. this can done, although shouldn't on written test: @test public void badtestwhichverifiesprivateconstructoriscalled() { new expectations(task.class) {{ // partially mocks `task` // records expectation on private constructor: newinstance(task.class, "name"); }}; task task = task.getinstance("name"); assertnotnull(task); } @test public void goodtestwhichverifiesthenameofanewtask() { string taskname = "name"; task task = task.getinstance(taskname); assertnotnull(task); ...

osx - dyld: Library not loaded ... Reason: Image not loaded -

Image
when trying run executable i've been sent in mac os x, following error dyld: library not loaded: libboost_atomic.dylib referenced from: /users/"directory executable in" reason: image not found trace/bpt trap:5 i have installed boost libraries , located in /opt/local/lib . think problem has executable looking in directory in when paste 'libboost_atomic.dylib' in there, doesn't mind anymore. unfortunately complains can't find next boost library. is there easy way fix this? find boost libraries: $ otool -l exefile exefile: @executable_path/libboost_something.dylib (compatibility version 0.7.0, current version 0.7.0) /usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 65.1.0) /usr/lib/libsystem.b.dylib (compatibility version 1.0.0, current version 169.3.0) and each libboost_xxx.dylib , do: $ install_name_tool -change @executable_path/libboost_something.dylib /opt/local/lib/libboost_somethin...

insert - PHP "Notice: Array to string conversion" error when inserting to SQL -

i'm trying insert values table, keep getting following notice : notice: array string conversion in c:\program files\wamp\www\process_invitation.php on line 10 line 10 insertion line in following code : if ((isset($_post['inviter'], $_post['opponent'])) && ($_post['inviter'] != '' && $_post['opponent'] != '' )) { $inviter = $_post['inviter']; $opponent = $_post['opponent']; $now = time(); if ($mysqli->query("insert invitations (inviter_user_id, invited_user_id, time) values ('$inviter','$opponent','$now')")) { return; } } have tried var_dumping $inviter , $opponent see datatype are? try casting them (string) too. also, it's idea use parameterised queries mysqli. stands, you're leaving wide open sql injections.

text files - Recover data to a drop down list from an external data -

is possible recover data external source, in order enrich contents of drop-down list? if possible, form or should jira project administrator add manually new data in drop-down list? should use plugin that? for example : i have select list operating system, contains windows, linux, mac somewhere on network, have textfile contain several lines 1 operating system line. is possible recover 'unix' text textfile written in line 4 ?

python - Get the address for f.seek()? -

i'd address hex byte in file, example change ff bytes af. so, first have find matching byte sequence. how do that? actually, tried import re target = 0x76c0 f = open("bin.dat", 'rb+') data = f.read() match = re.search(target, data) if match: print "found." data.replace(target,0xffff) else: print "no match" f.close() to find , replace it, somehow python complains f.close(). started approach using f.seek() , f.write, need address of first byte match. any ideas? thanks, john

sql - Bringing the other column , along all with all the other columns of the table (Oracle) -

i trying bringing other column , along all other columns of table (oracle) as shown below select order_id,person_id,col4,col5,* orders it giving below error : ora-00936: missing expression 00936. 00000 - "missing expression" *cause: *action: error @ line: 1 column: 66 any inputs helpful !! use alias: select col1, col2, c.* my_table c

codeigniter - Nginx: Serve Files from different Root Locations -

hej, i have following situation: have 2 systems running (magento , codeigniter) should operate under same url. magento responsible few urls: http://dev/checkout , http://dev/kasse example should served magento lies in /vagrant/magento all other request should served codeigniter lies in /vagrant/codeigniter i got working, uses if's , have add folder in 2 files, not nice. , php thinks root lies in wrong folder ( /vagrant/ , without magento folder) what doing wrong , how right? thanks! # ./sites-available/default server { listen 80; listen [::]:80 default_server ipv6only=on; server_name rh.dev; root /vagrant/codeigniter/; location ~ /(kasse|tools|checkout|warenkorb|skin|media) { alias /vagrant/magento/; index index.php; try_files $uri $uri/ @handler; } location / { index index.php; if ($request_uri ~* "\.(ico|css|js|gif|...

c# - Show all categories and subcategories on a nopcommerce 3.0 website? -

i wondering if knows how modify code make left hand navigation menu show subcategories in addition categories on homepage, category, search & product pages? i need push in right direction. code complicated can tell it's organized well. the nopcommerce performs lazy load sub-categories of category. to make loading during menu loading necessary sub-categories of categories. after obtaining these sub-categories, need store these data in cache increase performance of website.

c# - convert IList<Derived> to IReadOnlyCollection<Base> -

i have private field ilist<derivedclass> _elements , want create property returning ireadonlycollection<baseclass> . public ireadonlycollection<baseclass> baseclasses { { return _elements; } // compile time error } how without running compile errors? (afaik should work, t in ireadonlycollection<t> covariant) use list<t>.asreadonly() method: public ireadonlycollection<baseclass> baseclasses { { return _elements.cast<baseclass>().tolist().asreadonly(); } // compile time error } or since ireadonlycollection<t> covariant can skip cast<baseclass> : public ireadonlycollection<baseclass> baseclasses { { return _elements.tolist().asreadonly(); } // compile time error } you skip tolist() if field list<t> , not ilist<t> .

math - Working out a percentage of a value -

i'm trying workout equity stake in investment. want plug these numbers demo application i'm building in java script. it's math part i'm having problem working out. i have been giving numbers deal not sure how came equity number. so here apps numbers used. total value of company $800,000 investors 60% partner 40% yearly gross profit = $1,560,000 yearly net profit = $624,000 so worked out if investor put in $133,333 equity amount of 0.1 , yearly return of 62,400 ok 0.1 x 624,000 = 62,400 how did 0.1 value putting in $133,333 for example lets had filed user inputs amount of 80,000 equity value given above numbers. if can figure part out can add them variables in js , display accordingly. updated: there 1 partner 40% other number of investors amount make 60% of rest of equity. thanks from numbers have provided $800,000 must value of investors 60% stake not of whole company. the current investors looking sell 1 sixth of total stake...

c# - Sql command for finding IDENT_CURRENT -

i have got find last number inserted identity column "id_k" table klient. how should improve code? thanks in advance. sqlcommand comm = new sqlcommand("ident_current klient", spojeni); // sqlcommand comm = new sqlcommand("select max (id_k) klient", spojeni); spojeni.open(); int max = (int)comm.executescalar(); spojeni.close(); foreach (datagridviewrow row in dtg_ksluzby.rows) { if (convert.toboolean(row.cells[3].value) == true) { sqlcommand prikaz2 = new sqlcommand("insert klisluz(text,pocet,akce,subkey) values(@val1,@val2,@val3,@val4) ", spojeni); prikaz2.parameters.addwithvalue("@val1", row.cells["text"].value); prikaz2.parameters.addwithvalue("@val2", row.cells["pocet"].value); prikaz2.parameters.addwithvalue(...

ruby - How to test only one of the multiple method calls in RSpec? -

in method have multiple calls method different arguments. want test 1 particular call see if arguments call match condition. there better way stubbing every other call? for example, have def some_method foo(1) foo('a') foo(bar) if ... # complex logic foo(:x) ... end i want test if foo called argument bar . subject.should_receive(:foo).with(correct_value_of_bar) but other calls of foo inside same some_method ? okay, based on latest comment want observe you're logging output. here's example observe behavior replacing stdout stringio instance: # foo.rb require 'rubygems' require 'rspec' require 'rspec/autorun' require 'stringio' class foo def puts 1 puts 'a' puts 'bar' if true # complex logic puts :x end end describe foo describe '#something' context "and complex happens" let(:io){ stringio.new } "logs stdout" $s...

ruby on rails - In HAML, syntax error, unexpected ')' not placed by me -

i rendering drop down list of options in haml following code: - @campaigns.each |campaign| %tr{class: 'tr_' + cycle('odd', 'even'), id: "#{campaign.to_param}"} %td= link_to campaign.name, campaign %td= campaign.synopsis %td= campaign.focus_area %td= number_to_currency(campaign.goal_in_dollars) %td= campaign.approval_requested_at //line 34 %td= link_to 'approve', approve_admin_campaign_path(campaign)//line 35 %td= form_tag({controller: "admin/campaign", action: "deny"}, method: "post") //line 36 = text_field_tag :reason, params[:reason] //line 37 = submit_tag("deny") //line 38 however, i'm getting error: /users/user/rails_projects/wdi/app/views/admin/campaigns/index.haml:34: syntax error, unexpected ')' ));}</td>\n #{_hamlout.fo... ^ /users/user/rails_projects/wdi/app/views/admin/campaigns/index.haml:36: unknown r...

multithreading - How can I simulate the simultaneous execution of multiple tasks in .Net? -

i run several tasks simultaneously. clear, desire simultaneous, not merely parallel -- @ point in time, want every task have consumed equal number of cpu cycles, within tolerance. how best done in .net? there 2 ways measure this, wall clock time , cpu time . people tell use stopwatch measure performance, may or may not number want. if care how long took execute in real time, use stopwatch, if want know how long thread running, can done native api call getthreadtimes . here article on codeproject uses it. note won't able use tpl this, need use real threads tpl recycles threads times not real execution times task. a second option use querythreadcycletime . not give time, give number of cycles current thread has been executing, can 1 @ start , 1 @ end , subtract 2 numbers. note again task reuses threads number may or may-not reliable unless use full threads. be aware can't directly convert cycles->seconds due fact many processors (especially mobile proc...

antlr4 - Getting token start character position relative to the beginning of file -

is there reliable way antlr4 api token start character position relative beginning of file, not line? after doing research way found use custom implementation of intstream, not treat '\n' line terminators, perhaps i'm missing easier way? i'm using visitor api if matters. the application i'm working on parses source files , provides insertion coordinates application uses provided coordinates insert additional code. more convenient if application got symbol position in file, rather line:positioninline pair. you can use of following, depending on whether have token or terminalnode . token.getstartindex() terminalnode.getsourceinterval() .a edit: return token index, not character position. terminalnode.getsymbol() .getstartindex()

Can Drupal 7 be easily configured to inline an article on the homepage? -

i posted, on drupal 7 site, article intended displayed inline (not title linked page article). is there straightforward way display text of node on homepage, or undertaking? imagine theme can edited block of html displayed, hope isn't best way. what best approach that? with node there many different ways achieve this, popular way use views module display full content of node in block on home page. then can place block in 1 of home page regions in block administration screen. still leaves full content on home page , actual article node. without node you create simple block if don't want content node , display on home page. without node or block you "hard code" directly page--front.tpl.php file if it's won't updating on regular basis.

image - How can I produce more than one file format per plot code in R? -

i use github markdown document data analysis r. when make plot use: jpeg("file_name.jpg") plot(...) dev.off() to save plot jpeg can embedded , displayed in markdown document this: !(file_name.jpg) however, need make pdf of plot final publication. write entire plot code on again pdf("file_name.pdf") results in lot of duplicate code. i have tried putting jpeg , pdf calls in sequence bottom 1 gets produced. is there way make jpeg , pdf file same code during 1 run of code? or can use dev.copy : plot(cars) dev.copy(jpeg, "cars.jpeg") dev.off() dev.copy(pdf, "cars.pdf") dev.off()

php - HTML Forms to query multiple pages -

i trying build meta search engine. i have following code. <form method="post" action="google_basic.php"> <label for="service_op">service operation</label><br/> <input name="service_op" type="radio" value="web" checked /> web <input name="service_op" type="radio" value="image" /> image <br/> <label for="query">query</label><br/> <input name="query" type="text" size="60" maxlength="60" value="" /><br /><br /> <input name="bt_search" type="submit" value="search" /> </form> <h2>results</h1> {results} i need form have more 1 action= ""(i realise form can have 1 action, need equivalent of 3 actions ="" ). form needs access 3 search engines , display results. best way this?...

asp.net web api - Exception in ExceptionFilterAttribute is always of type HttpResponseException -

following this post on exception handling in asp.net web api, created exceptionfilterattribute looks this: public class notimplexceptionfilterattribute : exceptionfilterattribute { public override void onexception(httpactionexecutedcontext context) { if (context.exception notimplementedexception) { context.response = new httpresponsemessage(httpstatuscode.notimplemented); } } } ... , asp.net web api controller looks this: public class productscontroller : apicontroller { [notimplexceptionfilter] public string get() { throw new notimplementedexception("this method not implemented"); } } the problem context.exception always of type system.web.http.httpresponseexception no matter exception throw in actionmethod . such, code inside if statement never gets executed. message property on exception is: processing of http request resulted in exception. please see http response returned ...

java - How do I call multiple data types from GetDirectBufferAddress in JNI? -

i bytebuffer via native methods. the bytebuffer starts 3 int s, contains doubles. third int tells me number of doubles follow. i able read first 3 int s. why code crashing when try read doubles? relevant code first 3 integers: jniexport void jnicall test(jnienv *env, jobject bytebuffer) { int * data = (int *)env->getdirectbufferaddress(bytebuffer); } relevant code remaining doubles: double * rest = (double *)env->getdirectbufferaddress(bytebuffer + 12); in posted code, calling this: double * rest = (double *)env->getdirectbufferaddress(bytebuffer + 12); this adds 12 bytebuffer jobject , not number. getdirectbufferaddress() returns address; since first 3 int 4 bytes each, believe correctly adding 12, you not adding in right place . what meant this: double * rest = (double *)((char *)env->getdirectbufferaddress(bytebuffer) + 12); for overall code, initial 3 int s , remaining double s, try similar this: void * address = env-...

php - Check if INSERT succeeds -

here trying insert values in table course_student.the query running after inserting values in database not getting alert. <?php if(isset($_post['submit'])) { $connect =new mysqli("localhost","root","","new"); if(!$connect) { die("database connection error".mysql_error()); } //select database if(mysqli_connect_errno()) { die("database selection error".mysqli_connect_error()); } $course=$_post['select1']; $userid=$_session['user_id']; $sql="insert course_student (courseid,studentid)values ($_post[select1],'$userid')"; $result=$connect->query($sql); if ($result) { ?> <html> <body> <script> alert("fail"); </script> </body> </html> <?php } else { ?> <script> alert("fail"); </script> <?php } } ?> 1st - can echo "<script>alert('something')</script>...

sql - extracting text from a column using regexp_substr -

i have table varchar column data this: "<tasa> <parametros> <parametro> <nombre>ea</nombre> <valor>35</valor> </parametro> </parametros> <valortasa>3.15</valortasa> </tasa>" i need able extract value between valortasa tags, don't know how use function , can't access oracle documentation. i'm trying select regexp_substr(field, '<valortasa>[0-9]{0-3}</valortasa') dual; with no results. appreciated more simple way using extractvalue function extract value of node. -- sample of data sql> t1(col) as( 2 select '<tasa> 3 <parametros> 4 <parametro> 5 <nombre>ea</nombre> 6 <valor>35</valor> 7 </parametro> 8 </parametros> 9 <valortasa>3.15</valort...

soap - PHP SOAPClient Request Issue -

i trying call web service http:// 115. 186. 182.11/csws/service.asmx?op=sendsms following php code gives me exception error mate in script: server unable process request. ---> object reference not set instance of object. will highly appreciate on this. try { $client = new soapclient("http://115.186.182.11/csws/service.asmx?wsdl"); $method = 'sendsms'; $params = array( new soapparam('xxxxx', 'src_nbr'), new soapparam('xxxxxx', 'password'), new soapparam('xxxxx', 'dst_nbr'), new soapparam('xxxxx', 'mask'), new soapparam('message test message', 'message') ); $result = $client->__call($method,$params); } catch(soapfault $e){ echo "error mate in script: " . $e->getmessage(); } echo "<pre>"; var_dump($result); echo "</pre>"; $xmlobj = simplexml_load_string($result); print_r($xmlobj); following specification... po...

html - Footer's background gets cut off when viewing the site on mobiles -

Image
i'm working on new site, , weird happens when open site on mobile phone (same thing happens on iphone , android) the website not responsive, , when visits webpage mobile device footer's background wide original viewport - means of footer has no background (which makes text unreadable) the url is: http://www.wholesomegifts.com.au/ (visit on mobile, go down footer , swipe right see problem) any thoughts? workaround - i set divs min-width:960px - ugly hack did trick. i still don't understand why background didn't stretch in first place, if can shed light on subject great

r - Subset data frame for specific dates -

i have data frame one yr06 = as.date("2006-07-01")+0:100 yr07 = as.date("2007-07-11")+0:108 date = c(yr06,yr07) data = c(0:100,0:108) df = data.frame(date,data) i want subset these dates d6 = as.date("2006-08-20")+0:38 d7 = as.date("2007-08-20")+0:44 sub.df = subset(df, as.date(date) >= '2006-08-20' & as.date(date) <= '2006-09-27' | as.date(date) >= '2007-08-20' & as.date(date) <= '2007-10-03') is clumsy solution.

c# - How can I select a user control by grid row and column number? -

is possible select user control based on grid name, grid row , grid column? toggle checkbox based on row number , column number within grid. this have : for( = 1; i<7; i++) { (j = 1; j < 33; j++) { checkbox = new checkbox(); a.name = "sat_id_" + i.tostring() + "_" + j.tostring(); this.sat_id_grid.children.add(a); a.style = (style)application.current.findresource("readonlycheckbox"); grid.setrow(a, ); grid.setcolumn(a, j ); } } once created, how can reference checkboxes if know name? use findcontrol(), , don't need cell. something : datagridview1.rows[0].findcontrol("name_of_your_user_control")

jquery - Select a value after an input select is populated dynamically with change event -

i have 2 inputs select, second 1 populates when 1 value selected @ first input select, works. i'm selecting value dinamically , second select populating, problem comes when want select option second input select. can't it. the ajax executing in other file can't modify ajax, want select option dinamically when value appear @ dom. <script> jquery($).ready(function(){ //here i'm selecting option land , region populating jquery("#land option[value={value1}]").attr("selected","selected").change(); //when try select region dinamically doesn't work jquery("#region option[value={value2}]").attr("selected","selected").change(); }); </script> i want select value second input. i seems value isn't there, maybe using event handler, solve it. how can solve porblem? this sample ajax function based off of first select, select make of car, make...

php - A better way to write MySQLI calls -

im new stackoverflow. understand question at moment write mysqli calls - depends i'm trying achieve. function getarticles($dbh) { $query = "select article_id,article_name,article_text articles"; $result = mysqli_query($dbh,$query); if(!mysqli_errno($dbh)) { if(mysqli_num_rows($query) > 0) { $articles = array(); while($rows = mysqli_fetch_object($query) { $articles[] = $rows; } } mysqli_free_result($dbh) } else { echo mysqli_error($dbh); } return ($articles); } then fetch them , display using foreach() in calling page. can make mysql calls better in way?, or how write mysql calls. i choose oo way too, apart that, wrap calling query in separate class or function. can write function takes sql query , array of parameters input, , returns array results or error code or error object (or array). way, functions getarticles, of have dozens, contain sing...

java - How do I append a "descendant" clause next to an xpath variable? -

this code looks like public void sometest() { string x = "/html/body/div/div[" string y = "]/a" (int = 1; < 5; i++){ string links = x + + y; driver.findelement(by.xpath(links)).click(); // iteratively go next link , click on } } what i'm trying achieve, however, once clicks on link, should descendant links , click on well. there way of doing that? if try following, work? driver.findelement(by.xpath(links/descendant::a).click(); it's fragile way of coding, altering xpath go through loop. instead, recommend using findelements method , looping through elements returns, this: public void sometest() { xpath xpath_findlinks = "/html/body/div/div/a"; xpath relative_xpath = "./..//a"; (webelement eachlink : driver.findelements(by.xpath(xpath_findlinks))) { eachlink.click(); (webelement descendantlink : eachlink.findelements(by.xpath(relative_xpath)))...

SharePoint 2010 Check Permission shows "None" for Users added through AD Security Groups -

i using sharepoint 2010 , ad well. i have added users in ad , add them group called "testingusers" in ad, group has group scope global , group type security , in sharepoint group holds "read" permission, but when add user through ad , check permission in sharepoint shows "none" instead of showing "read" , same user can log site credentials well pls me .... http://blogs.technet.com/b/yashgoel-msft/archive/2012/04/13/check-permissions-showing-quot-none-quot-for-users-added-through-ad-groups-in-sharepoint-2010.aspx when try checkpermissions user added on site through ad group “none” though group has permissions on site , user doesn’t have issue in logging site. it’s check permission doesn’t work group , user. resolution: take uls while doing check permissions , if see following entry 04/02/2012 17:27:49.89 w3wp.exe (0x169c) 0x0974 sharepoint foundation general 7fdb unexpected ...

SSIS Business Intelligence LookUp task Visual studio Get Data -

please need help, have stagging table on- air(*bts*,ville,region,zone) , table dim_bts(*bts*,bsc,statut,date_bts,classe,idville) dimaxegeographi(idville,ville,zmr,region) and need yor how idville dimaxegeographi , put on dim_bts using attribute bts stagging table on ssis on business intelligence don't know how id-ville . assumption: in table dimaxegeographi, ville , region make record unique. try this: merge dim_bts target using ( select a.bts, d.idville air inner join dimaxegeographi d on a.ville = d.ville , a.region = d. region ) source on source.bts = target.bts when matched update set target.idville = source.idville ; note: helpful if can post sample data , expected result.

php - Selecting from a Many to Many table -

this question has answer here: sql: products category must in set of categories 1 answer i want post_id , thumbnail of post(s) have multiple tags. tables follow: table: post ------------------- post_id | thumbnail 1 | 1.jpg 2 | 2.jpg 3 | 3.jpg 4 | 4.jpg 5 | 5.jpg table: tags ----------- tag_id | tag 1 | red 2 | yellow 3 | orange 4 | blue 5 | pink table: post_tags ---------------- post_id | tag_id 1 | 1 1 | 2 1 | 4 1 | 5 2 | 2 2 | 3 3 | 4 3 | 1 3 | 2 4 | 5 4 | 4 5 | 1 5 | 3 5 | 5 i use this, not working: first tags of posts in array, , compare them find if post has 3 tags mentioned. select post_id post_tags tag_id in ($thistags[0], $thistags[1], $thistags[2], $thistags[3]) do need join or group or something? new sql , ...

php - webservice not returning a array -

i need webservice, returning stdclass object ( [getofertasaereasresult] => ) i need return array values. <?php try { $wsdl_url = 'http://portaldoagente.com.br/wsonlinetravel/funcoes.asmx?wsdl'; $client = new soapclient($wsdl_url); $params = array( 'slojachave' => "y2y4zgrkowu=", ); $return = $client->getofertasaereas($params); print_r($return); } catch (exception $e) { echo "exception occured: " . $e; } ?> assuming data following: $return = '<?xml version="1.0" encoding="utf-8"?> <soap12:envelope xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:xsd="http://www.w3.org /2001/xmlschema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"> <soap12:body> <getofertasaereasresponse xmlns="http://tempuri.org/"> <getofertasaereasre...

.net - Make a c# application that runs continuously -

i writing client side app pushes data users computers website. want application update website every 60ish seconds. right have function wrapped in infinite while loop 45 second sleep. but, windows says application not responding though updating website. here how code structured. your problem while loop blocking ui thread . fix this, need run code on separate thread. the easiest way start off.. might use timer : system.timers.timer timer = new system.timers.timer(45000); // timer execute every 45 seconds timer.elapsed += (sender, e) => { // upload code here }; timer.start(); you should threading @ later stage though. perhaps backgroundworker or task parallel library.

swing - How to create a Right Click Menu for a Text Field in Java? -

i novice java programmer. trying edit java application, application download manager. has text field in have paste url download particular file. problem trying add mouse event can right click , "paste" url text field. add "cut" , "copy" options right click. have tried many things , failed achieve wanted. it of great if me done giving me example of code. i know simplest way "cut", "copy" & "paste" menu right clicking text field. thank you. partial source code of download manager application modifying. public class ftpdownloader extends jframe implements observer { private jtextfield addtextfield = new jtextfield(40); private downloadstablemodel tablemodel = new downloadstablemodel(); private jtable table; private jbutton pausebutton = new jbutton("pause"); private jbutton resumebutton = new jbutton("resume"); private jbutton cancelbutton, clearbutton; private jlabel savefilelabel =...

c++ - What is the equivalent switch to /MT (VC++) for g++ in linux (CentOS)? -

my users complain have install linux thread building blocks on machines not own, , many hosts don't want intel thread building blocks installed of end users, want create static version of dynamic library / plugin / module / extension (whatever corrct term plugable c++ program / dll / so). i found out windows have use /mt (multi threaded) instead of default /md switch (multi threaded dll ) program have no dependencies (but, windows has concurrent container library don't need use tbb there). i cannot figure out equivalent linux is? or there maybe .sln makefile converter can figure out options? i'm developing on windows, of end users use linux make sure don't have burden on them , want them comfortable using open source releases. the /mt flag in microsoft c++ compiler causes linker link against static versions of c , c++ run-time libraries. microsoft ships static , dynamic versions of run-time libraries, option selects set of libs link against. flag n...

Defining a constant in Java -

public enum categories { general, lights, effects, interactive, ui("ui"), optimizations, parsers, animation, materials, about; private string name; categories() { name = tostring().tolowercase(locale.getdefault()); name = name.substring(0, 1).touppercase(locale.getdefault()) + name.substring(1, name.length()); } categories(string name) { this.name = name; } public string getname() { return name; } } inside enumeration first line starting "general, effects" wondering are? ui("ui"). meant constants? why ui("ui") have ( , ) when rest of them don't? thanks in advance... public enum categories { general, lights, effects, interactive, ui("ui"), ... these represent enum constants accessible qualifying them class name as categories.general, categories.lights, categories.ui, ... enums b...

rest - Returning JSON from RESTful Java server code? -

i've inherited web project contractor started. , coworkers unfamiliar technology used, , have number of questions. can tell, appears sort of restful java server code, understanding there lots of different types of java restful services. 1 this? specific questions: 1) can read more (particularly introductory information) specific service? 2) code creates , returns json through kind of "magic"... merely return model class (code below) has getter , setter methods fields, , it's automagically converted json. i'd learn more how done automagically. 3) have code creates json. need return using framework. if already have json, how return that? tried this: string testjson = "{\"menu\": {\"id\": \"file\", \"value\": \"hello there\"}}"; return testjson; instead of returning model object getters/setters, returns literal text string, not json. there way return actual json that's json string, , have ...