Posts

Showing posts from January, 2014

java - Regex - starts with OPERATION and must be followed by either an integer or double -

so have follow input string operation: 12, 12.32, 54.3332 operation can of min, max, sum. regex should accept strings start of 3 words follow colon , followed either integer or double. i have been googling , fidling around hours before decided turn guys. thanks time! edit: so far have ended regex ^[max:sum:average:min:(\\d+(\\.\\d+)?), ]+$ it matches "max: " correct "max:" , "ma: . matches strings of following format : "max: 12, 12.3323......" you misunderstand meaning of [] . these refer single character alternatives. so [max:sum:average:min:(\\d+(\\.\\d+)?), ] either m or a or x or .... mmmmm should match. you may want more this: ^(max|sum|average|min): (\\d+(\\.\\d+)?(, (?=.)|$))+$ explanation: (max|sum|average|min) either max , sum , average or min . ": " refers actual characters : , space. \\d+(\\.\\d+)? had before. ", " refers actual characters , , space. (?=.) look-ahea...

java - How do you change Vector to ArrayList? -

i developing application in java , since vector obsolete required change using arraylist . this relevant code needs changed arraylist : this "house" class. public vector<vector> getitems() { vector<vector> data = new vector<vector>(); (int = 0; < _itemlist.size(); i++) { vector<string> row = new vector<string>(); row.add(_itemlist.get(i).getdecription()); row.add(string.valueof(_itemlist.get(i).getprice())); data.add(row); } return data; } this gui class: private void updateview() { //gets rows , columns house.class vector<vector> rowdata = _listener.gethouse().getitems(); vector<string> columnnames = new vector<string>(); columnnames.add("product name"); columnnames.add("product price(€)"); //creates shopping cart , sets size + properties table1 = new jtable(rowdata, columnnames); table1.setpreferredscrollablev...

c# - Attaching vs selecting and modifying in L2S -

i have data access layer creates context , retrieves data (with no object tracking) , passes information ui layer:- my unit of work method , release appdatacontext after executing particular method. not keeping track of data context anywhere.. public linqobject getobject(){ using (appdatacontext = new datacontext()){ ---code select , return object } } i modify data using form in ui , submit data db. two approaches are:- 1. detach , reattach different data context using [detach..serialise , attach] *i have lot of plumping code enable functionality* 2. db object using primary key , make changes in selected object , submitchanges. which 1 better approach doing task? i against moving unit of work data access layer wise or web application life cycle (httpcontext), because dont want track changes , complicate entire application structure unwanted plumping code . using linq making retrieval , updates db easy. i have never seen discuss these 2 approaches in lin...

how to get suspended user status from google api using oauth -

i looking way google apis list of not-suspended users in organization, using oath authorization. google profile api has oauth, user list returned not contain issuspended flag. google provisioning api returns issuspended flag, far understand cannot oauth authorized. are there other options have accomplish this? yes, provisioning api works oauth 1.0 , 2.0. see docs , necessary scopes here . if need users in entire google apps instance, use retrieve users in domains api call , filter out users issuspended = true . if need filter list down users under organizational unit (ou), use retrieving organization unit's immediate sibling users api call , filter down list users in ou , not disabled.

TypeScript - Inline function not getting checked for type safety -

i new typescript , trying few things where function demands number parameter , bool return value. function where(items: number[], filter: (item: number) => bool) { (var counter = 0; counter < items.length; counter++) { var item = items[counter]; if (filter(item)) { console.log(item); } } } var data = [1, 2, 3, 4]; case 1 - typescript gives compile error var evenfilter = function (item: number) { //actual line item % 2 == 0; return item; } where(data, evenfilter); case 2 - inline function incorrect return type not generate compile time error where(data, function(item : number){ return item; }); case 3 - short hand syntax not generate compile time error where(data, item => item); is bug typescript or expected behavior? definitely bug. apparently anonymous functions not type checked. functions assigned variables / named functions are. can open bug report here: https://typescript.codeplex.com/w...

windows installer - Wix Patch Generation issues -

i struggling build working patch our product using wix 3.7. we @ development stage our product , want validate process building patches before rtm know original installer has information required. i have tried follow patch creation properties approach detailed on wix toolset website, built 2 installers identical upgradecode , productcode since small update - difference single text file called something_to_patch.txt. when generated patch correctly identifying data in something_to_patch.txt has changed; log file msimsp.exe contains: info comparing files: d:\development\xa3-modular\xanalyser3\installer\patches\tmpinstall\target\warwick control technologies\x-analyser 3\something_to_patch.txt d:\development\xa3-modular\xanalyser3\installer\patches\tmpinstall\origin\warwick control technologies\x-analyser 3\something_to_patch.txt... info comparing bytes... info different content... info file key: something_to_patch.txt modified info: phase iv: entering generate payload. info: p...

java - jvisualvm: Stuck on "Loading Heap Dump" screen -

Image
i created heap dump file hprof using command: java -agentlib:hprof -cp "..\..\jars\trove.jar;.\bin" com.mysite.myapp this created file "java.hprof.txt" 5mb. opened jvisualvm view file, , loaded in. visualvm appears stuck on loading screen. screen below has been 10 minutes now. did miss step? should have used different options on command line hprof? how can read heap dump file? visualvm supports heap dumps in binary hprof format. easier use visualvm create heap dump. if not possible use visualvm, can use jmap -dump:live,format=b,file=heap.bin <pid> . advantage don't need special startup arguments , there no slow down caused hprof agent library.

Adding strings to Rails JSON output -

i need output custom json in order backwards compatible existing software, written in javascript, need wrap json "parsedate(" @ beginning of it, , ");" @ end of it. i tried doing in controller this def index @data = data.all @products = product.all respond_to |format| format.html format.json {render :json => { :products => {:product => @data.name}}} end end and specify in view: app/views/products.json.erb <%= p "parsedata(" %> <%= render :json %> <%= p "};" %> but outputs pure json skipping both "parsedata(" , ");", why? how make json printed in middle of view , append strings top , bottom? json renderer supports callback option. format.json { render :json => { :products => {:product => @data.name }}, :callback => 'parsedate' } you can read implementation in renderer.rb source code.

Page not found Error in WebView android -

i trying open url in webview of application, getting "page not found" error. same url not opening in device(android tablet) browser also. if try open url in desktop browser, opening. please let me know how solve issue. below code. public class linkcompanypagewebview extends activity{ private string url; protected void oncreate(bundle savedinstancestate) { // todo auto-generated method stub super.oncreate(savedinstancestate); setcontentview(r.layout.my_webview); webview wvbrowser; wvbrowser=(webview)findviewbyid(r.id.wvbrowser); wvbrowser.getsettings().setjavascriptenabled(true); wvbrowser.getsettings().setpluginstate(websettings.pluginstate.on); url = getintent().getstringextra("url"); wvbrowser.loadurl(url); wvbrowser.setwebviewclient(new webviewclient() { @override public void onreceivederror(webview view, int errorcode, string description, string failingurl) { log.i("web...

Insert BLOB using java for both DB2 and Oracle -

i validating application developed on oracle db2. since don't want maintain 2 separate sources, need query insert blob field, works in both oracle , db2. don't have identifier distinguish under db application running. i used utl_raw.cast_to_raw in oracle , cast() blob in db2 mutually incompatible. you won't able find common sql uses kind of casting. can "plain" sql using jdbc's setbinarystream() preparedstatement pstmt = connection.preparestatement( "insert blob_table (id, blob_data) values (?, ?)"; file blobfile = new file("your_document.pdf"); inputstream in = new fileinputstream(blobfile); pstmt.setint(1, 42); pstmt.setbinarystream(2, in, (int)blobfile.length()); pstmt.executeupdate(); connection.commit(); you can use setbinarystream() same way update statement.

python - importError: no module named pysphere -

i able type following python.exe create session vmware esxi from pysphere import viserver server = viserver() server.connect("myserver", "user", "password") when save same code .py file , execute windows command line get importerror: no module named pysphere. when in lib\site-packages there pysphere folder. running .py c:\python\ , python package in c:\python27 i not use seeing command , don't understand when ran command showed version 2.6.3 not 2.7. adjusted path in environment variables 2.6 2.7. found registry key pointing 2.6 updated 2.7 (python.file - shell - open - command).

asp.net c# oledbconnection InvalidOperationException -

error: unrecognised escape sequence. code: string connectionstring = "provider=microsoft.ace.oledb.12.0;data source=|datadirectory|\drivebuy.accdb"; oledbconnection con = new oledbconnection(connectionstring); if (fileupload1.hasfile) { string spath = mappath(fileupload1.filename); fileupload1.postedfile.saveas(spath); con.open(); string mysql; mysql = "insert cars(make,model,price,picture) values (?,?,?,?)"; oledbcommand cmd = new oledbcommand(mysql, con); cmd.parameters.addwithvalue("@p1", tbmake.text); cmd.parameters.addwithvalue("@p2", tbmodel.text); cmd.parameters.addwithvalue("@p3", convert.todecimal(tbprice.text)); cmd.parameters.addwithvalue("@p4", fileupload1.filename); cmd.executenonquery(); con.close(); } else { lblerror.text = "image not uploaded"; } a...

symfony - Symfony2 Forms: How do I create a collection of 'entity' forms -

i have 1 many unidirectional relationship in model. user has 1 of many status . using doctrine these mapped unidirectional many-to-many unique constraint on 1 of join columns. i'd use symfony form select status status table, submit form , have symfony persist relationship. i've tried 2 approaches: using entity form type, produces error (due many-to-many relationship doctrine expects receive instance of arraycollection rather single status object. using collection entity objects. when using approach empty div id status rendered in form. expected select box appear containing status options. here code. wrong? entity code: /** * @orm\manytomany(targetentity="status") */ protected $status; form type code: $builder->add('status', 'collection', array( 'type' => 'entity', 'allow_add' => true, 'options' => array( 'class' => 'sunflycorebundle:statu...

C++:openCV error -

Image
hi trying rgb pixel in image using c++ opencv 2.4.5 but error when compile . it loads image exception arise when trying rgb pixel can 1 me please ? the following code loads image , find rgb pixel @ index 25,4 code : #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv/cv.h> #include <opencv/highgui.h> #include <iostream> using namespace std; using namespace cv; int main() { int x; mat input = imread("c:/red.jpg"); if (input.empty()) { std::cout << "!!! failed imread(): image not found" << std::endl; cin>>x; return 0; // don't let execution continue, else imshow() crash. } imshow("input", input); vec3f pixel = input.at<vec3f>(25, 40); ...

ruby on rails - Using Highcharts to make correct graphs on RoR apps -

i using highcharts library create charts on ror application (plugin in redmine). used this video example. my problem every chart want draw formed "line chart". for example: $(function () { $('#container').highcharts({ chart: { type: 'column' }, title: { text: 'monthly average rainfall' }, subtitle: { text: 'source: worldclimate.com' }, xaxis: { categories: [ 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec' ] }, yaxis: { min: 0, title: { text: ...

google drive sdk - Is it possible to query file's properties? -

are custom file properties queryable on files.list requests? filter out files properties queries such property = 'tested' . searching properties not possible @ moment, it's feature on our roadmap. we'd provide in queries key, value , visibility.

optimization - optimal way of passing multiple callback functions as arguments? -

i have function used in cli or web application, being said, there little difference in process; example: if i'm using function cli it'll use text progress bar, doesn't make sense if i'm using function web application. the function loop; i'm looking way make function flexible making possible pass code argument it'll executed @ end of each loop cycle. if i'm using function in cli; i'll pass progress incremental function advance progress bar, , on. my current solution pass progress bar object instance, think isn't proper solution; because doesn't seem flexible long run. a demonstration example of i'm doing: function myfunction($progressbar = null) { for($i = 0; $i......) { //do stuff .... //finally... if(!empty($progressbar)) $progressbar->advance(); } } so, if want add function @ end of loop, i'll have pass argument , call manually later; said, doesn't seem ri...

c++ - How can I use something like std::vector<std::mutex>? -

i have large, potentially varying, number of objects concurrently written into. want protect access mutexes. end, thought use std::vector<std::mutex> , doesn't work, since std::mutex has no copy or move constructor, while std::vector::resize() requires that. what recommended solution conundrum? edit : c++ random-access containers require copy or move constructors re-sizing? std::deque help? edit again first, thoughts. i'm not interested in solutions avoid mutices and/or move them objects (i refrain giving details/reasons). given problem want adjustable number of mutices (where adjustment guaranteed occur when no mutex locked), there appear several solutions. 1 use fixed number of mutices , use hash-function map objects mutices (as in captain oblivous's answer). result in collisions, number of collisions should small if number of mutices larger number of threads, still smaller number of objects. 2 define wrapper class (as in comicsansms's answer...

Quickly update a large amount of rows in a table, without blocking inserts on referencing tables, in SQL Server 2008 -

context: have system acts web ui legacy accounting system. legacy system sends me large text file, several times day, can update contract table in database (the file can have new contracts, or updated values existing contracts). table has around 2m rows , 150 columns. can't have downtime during these updates, since happen during day , there's 40 logged users in given time. my system's users can't update contract table, can insert records in tables reference contract table (foreign keys contract table's id column). to update contract table first load text file staging table, using bulk insert, , use merge statement create or update rows, in batches of 100k records. , here's problem - during merge statement, because i'm using read commited snapshot isolation, users can keep viewing data, can't insert - transactions timeout because contract table locked. question: know of way update large amount of rows, while enforcing data integrity , without ...

database - Codeigniter PHP: How do I use explode in codeigniter to find between 2 integers -

i have select box choice of "very low", "low", "medium", "high" , "very high" choose between 0-19,20-39 etc 100. model: if ($this->input->post('interest_rating') != "") { $range = explode($this->input->post(' ','interest_rating')); $this->db->where('webinar_event.interest_rating >= ', $range[0]); $this->db->where('webinar_event.interest_rating <= ', $range[1]); } i 2 separate errors 1) a php error encountered severity: warning message: wrong parameter count explode() filename: models/hp_model.php line number: 128 database error occurred error number: 1064 2) you have error in sql syntax; check manual corresponds mysql server version right syntax use near 'and webinar_event . interest_rating <=' @ line 5 select * (`health_professional`) join `webinar_event` on `webinar_event`.`hpid` = `health_professional`...

c++ - Invalid arguments in classes -

char* n=m.getname(); i following error invalid arguments ' candidates are: char * getname() ' above instruction.what missing? char* medicine::getname() { return this->name; } name of declared char name[50]; and m const medicine& m if m const , const methods can called on it. maybe can change method to const char* medicine::getname() const; and use this: const char* n=m.getname(); although might consider using std::string data member instead of array of char .

java - When does Hibernate create a new entry from a FK to a non-PK column? -

suppose have: -- table_1 ------------------- |id | property_x | data | ------------------------------ -- table_2 ------------------------ |id | property_x | moar_data | ----------------------------------- and table_1 has fk property_x table_2.property_x (why not table_2.id ? idk, project :( ) the hbms this: <!-- table 1 --> <hibernate-mapping package="com.example"> <class name="table1" table="table_1"> <id column="id" type="integer" name="id"> <generator class="native"/> </id> <many-to-one class="table2" fetch="join" name="table2" not-null="false"> <column name="property_x" /> </many-to-one> </class> </hibernate-mapping> and <!-- table 2 --> <hibernate-mapping package="com.example"> ...

Any reason not to just import CGI in Python? -

any reason try , replace else? i'm beginner python, have encountered problems c , importing cgi. list of instance import cgi not best option great further understanding of language use. you should choose wsgi instead of cgi. cgi applications slow need re- invocation of interpreter every request, wsgi on other hand pools them , more efficient. wsgi more mainstream. little research on web , better , more detailed answers. in past have used cgi python usage has been image/chart generation,where core lib implemented in c/c++.

concurrency - I2C concurrent access on Linux, mutex -

i'm writing multithread c program in embedded linux accesses userspace number of i2c devices (slaves). also, access same i2c device multiple threads. i'm using smbus functions (i2c_smbus_write_byte_data, i2c_smbus_read_byte_data, i2c_smbus_read_i2c_block_data,...). is there protection concurrent access built in or need add mutexes myself? for instance: have read function read data 1 sensor on i2c. same function can called thread well, resulting in possible concurrent access. have use static mutex in function or in i2c access functions? i 2 c shared bus multiple devices, accessed multiple processes threads. linux i 2 c driver code uses mutex manage access each i 2 c bus. for smbus functions, see linux kernel function i2c_smbus_xfer() in i2c-core.c . gets lock i 2 c adapter before beginning transfer (look @ source code, , see call i2c_lock_adapter() ). smbus transactions based on function. for i 2 c functions, see linux kernel function i2c_transfer() in i2c...

php - Check if username exists, if so, increment by one -

when username inserted database, such as: john_smith i need check if there john_smith present. if so, increment 1 become john_smith_1 so if following usernames exist: john_smith john_smith_1 john_smith_2 john_smith_3 ....up john_smith_10 i need next john_smith inserted incremented john_smith_11. so far, have searched , come this: $preferredname= "john_smith" //check duplicate user names $duplicate= check_for_duplicate_username($preferredname); //if duplicate, increment preferredname if ($duplicate) { $parts = explode("_",$preferredname); if (isset($parts[1])) $preferredname = $parts[0]."_".$parts[1]."_".($parts[2]+1); else $preferredname = $parts[0]."_".$parts[1]."_1"; } this, believe work first matching usernames. problem checking database version of name highest number.. sql: ...

Which PaaS would be best for a Meteor JS app that needs to be scalable? -

i trying evaluate whether meteor js suitable future project incorporate live chat, , may need scalable. it can perform chat functions, don't want paint myself corner if traffic spikes , need provision app more resources in form of drones/dynos/instances. have read meteor app on heroku won't scale (perhaps not @ all?). not clear on whether heroku issue, or more current state of meteor js (0.6.2.1 @ time). i've not found more related nodejitsu or appfog. can clarify whether meteor js app can deployed on paas such resources (drones/dynos/instances) can scaled meet demand? if so, paas? if not, explanation (for 5-year-old), , there roadmap? personally i've set myself aws load balancer , ec2 instances, db on @ mongohq. the load balancer setup made easier following these instructions: http://www.ripariandata.com/blog/creating-an-aws-elastic-load-balancer i wrote script deploy single ec2 instance. wouldn't work add additional remotes in case have ...

jquery - Position:absolute misaligns div in Internet Explorer -

position: absolute used div misaligns div in internet explorer. works in mozilla firefox , chrome. can suggest workaround? code http://jsbin.com/uxerus/15/edit the solution wrap first input , hidden div in div, setting "wrapper's" position relative . position hidden div absolute including left , top css property. for start, see http://jsbin.com/uxerus/56/edit should like: css: .wrapper { position: relative; } div.first { position: absolute; top: 24px; left: 0; z-index: 10; width: 298px; border: 1px solid #000; background: #fff; } html: <div class="wrapper"> <input type="text" id="input" name="input" value="first div" /> <div id="content" class="first"> <span>option 1</span> <span>option 2</span> <span>option 3</span> <span>option 4</span...

Grails - How to exclude some jars for grails-app(war) package -

some unwanted wars being included while maven's grails-app packaging. need itext-2.0.8 , added in pom , added fine, below 3 jars getting added, , 1 duplicate itext-2.1.5 , should not come war file. i tried exclude tag in maven corresponding plugin(export). <exclusions> <exclusion> <groupid>com.lowagie</groupid> <artifactid>itext</artifactid> </exclusion> </exclusions> i tried adding excludes in buildconfig.groovy. excludes "com.lowagie:itext:2.1.5" excludes "com.lowagie:itextasian:2.1.5" excludes "com.lowagie:itext-rtf:2.1.5"

node.js - PassportJS NodeJS Display Error Messages on page -

i using locomotivejs , passportjs auth on project, , found code online handle register: accountcontroller.create = function() { var account = new account(); console.log("test"); account.email = this.param('email'); account.password = this.param('password'); account.name.first = this.param('first'); account.name.last = this.param('name.last'); var self = this; account.save(function (err) { if (err) { console.log(err); return self.redirect(self.urlfor({ action: 'new' })); } return self.redirect(self.urlfor({ action: 'login' })); }); }; however cannot figure out how display error messages on page such "username exists" or "passwords not match" etc. can them console.log(). know how can this? connect-flash pretty useful such situations: // in app's config: var flash = require('connect-flash'); ... app.use(flash()); ... // in #create co...

jquery - Get filename from URL using JavaScript -

i have script grabs filename url have problem. firstly, here's i've got far: var img = $('img').attr('src'), filename_index = img.lastindexof("/") + 1, filename = img.substr(filename_index); if url have ?format=foo after filename, part added. there way remove last part starting question mark leaving filename? try adding line end of code sample: filename = filename.replace(/[\#\?].*$/,''); // strips hashes, string.replace on mdn

css - "Domains, protocols and ports must match" Error + Fixed div freezing in Chrome -

i'm getting error below website in chrome google adsense, , it's causing fixed position div sidebar freeze. i've looked error on here, , seem it's problem on google's part (which seems odd it's not fixed), shouldn't affect anything; see no reason why freeze fixed div. it doesn't show in firefox or ie9, , doesn't cause problem i'm having there. error pops on browser console, sidebar stops moving. "unsafe javascript attempt access frame url -my url- frame url -google adsense url-. domains, protocols , ports must match." i'm not sure if i'm allowed post url demonstrate. think relevant code below ad , other sidebar. <div id="container"> <div id="leftercontainer"> <div id="lefter">sidebar.</div></div> <div id="contenter">content</div> <div id="rightercontainer"> <div id="righter" class="center"...

javascript - how to send post data in jquery using ajax -

i have simple form , want input field losses focus event fired check content if , replies accordingly that $("document").ready(function() $("#txt_email").blur(function() { var email=$("#txt_email").val(); $.post('ajax/tester.php', {chk:email}, function(data) { alert(data) ; }); }); }); so have done till it's showing nothing: no error, no output. using jquery 1.9.1 , want know how check value of post data on ajax/tester.php page right doing $tochk=isset($_post['chk'])?$_post['chk']:null; echo $tochk; i hope helps: $(function(){ $("#txt_email").blur(function() { var email=$("#txt_email").val(); alert('email: ' + email); var jqxhr = $.post('ajax/tester.php', {chk:email}); jqxhr.done(function(data) { alert(data); }); jqxhr.fa...

c# - LINQ Query to inner join DbContext Entities to IQueryable -

i have 2 tables, 'events' , 'services', have one-to-many relationship (each event has @ least 1 service). i'm writing c# console application extract subset of events , extract corresponding services. i have method extracts events iqueryable<event> object , it's working expected. when join iqueryable<event> object iqueryable<service> (as shown below) resulting object contains references different contexts , want contain iqueryable<service> results. is there better way this? here's 'extractservices' method: public iqueryable<service> extractservices(iqueryable<event> events) { using (var precertentities = new precertentities()) { iqueryable<service> services = s in precertentities.services orderby s.eventid select s; services = s in services join e in events on s.eventid eq...

web applications - Current user with ASP.NET Forms authentication app -

i trying retrieve current user in web application uses asp.net forms authentication. however, system.security.principal.windowsidentity.getcurrent().name returns domain\windowsuser, not username used in formsauthentication.redirectfromloginpage method. using forms authentication in config file: <authentication mode="forms"> <forms loginurl="views/login.aspx" name=".aspxformsauth" timeout="1" cookieless="useuri"> </forms> </authentication> <authorization> <deny users="?" /> </authorization> i trying follow microsoft's walk through , retrieve authentication ticket using following snippet: if (request.isauthenticated) { var ident = user.identity formsidentity; if (ident != null) { formsauthenticationticket ticket = ident.ticket; var name = ticket.name; } } however, ident n...

tree - Java: Inconsistent NullPointerException -

i having trouble method in java thats throwing error: exception in thread "main" java.lang.nullpointerexception @ familytree$familytreenode.access$9(familytree.java:5) @ familytree.displayfamilymember(familytree.java:166) @ familytreetest.main(familytreetest.java:28) the method in question is: public void displayfamilymember(){ boolean cascade = false; int memberidentifier; displayfamily(); memberidentifier = input.getinteger("input member id"); currentnode = ancestor ; if (currentnode.identifier == memberidentifier || currentnode.partner.identifier == memberidentifier){ cascade = true; if(currentnode.partner!= null){ system.out.println(currentnode.name + " id[" + currentnode.identifier + "] partner: " + currentnode.partner.name + " id[" + currentnode.partner.identifier + "]"); }else{ syste...

java - Synchronized Non-Final List -

this question has answer here: correct way synchronize arraylist in java 5 answers ok understand it, best create final static object use synchronization. however, read if object reference doesn't change, won't have concurrency issues. do following code violate synchronicity? class foo { private static arraylist<client> clients = null; public foo() { clients = new arraylist<>(); //add stuff list here.. } public void addclient(client c) { synchronized(clients) { clients.add(c); } } } do have make clients final or create final object if clients arraylist never exposed directly (only other through getters)? in other words, never provide set method clients array reference never changes. anyone creating instance of foo new foo() overrides clients array. not thread safe...

Executing a Powershell script in CMD.EXE from a location with "Illegal characters in path" -

i attempting call powershell script in cmd.exe , script in location looks this: c:data\foo - bar\location-1\shellscript.ps1 when calling script have tried using single , double quotes around path no luck. powershell.exe -file "c:\data\foo - bar\location-1\shellscript.ps1" arg1 arg2 from have read assumed above work did not work nor did single quotes. i appreciate ideas. thanks *edit * mistype on example path. sorry. one solution move powershell v3 works fine: ps> powershell.exe -file 'c:\temp\foo - bar\location-1\foo.ps1' arg1 arg2 made it!, args arg1, arg2 if need stay on v2 try escaping spaces e.g.: ps> powershell.exe -file "c:\temp\foo` -` bar\location-1\foo.ps1" arg1 arg2 from cmd.exe, should work: c:\> powershell.exe -command "& {& 'c:\data\foo - bar\location-1\shellscript.ps1' arg1 arg2}"

asp.net mvc - Class on validation message is empty -

normally write code this: @html.validationmessagefor(m => m.username) where username required property of model. show whatever message have configured. works, in particular case i'm working on, html gets generated not have class attribute set. gets set to: class="error" but code i'm seeing generated in project is: class="" so text user sees plain text. not decorated (red) css .error. any ideas why class name not being output html?

Java FileOutputStream Default Creation Path -

let's have below code: string filename = "name.txt"; fileoutputstream fileout = new fileoutputstream(filename); wb.write(fileout); this way, file created under bin folder of project. however, if specific filename @ whole path: string filename = "c:/temp/name.txt"; this file created @ c:\temp folder. am correct? , why happen, how fileoutputstream work? if don't specify absolute path, e.g. if specify file name, program or operating system somehow needs figure out, find file. reason running program has working directory. happens folder start from, default.

json - Map object and nested object to model using Ruby on Rails -

i have object {"result":[{ "links":[{ "urlto":"http://www.example.com/", "visited":1364927598, "firstseen":1352031217, "prevvisited":1362627231, "anchor":"example.com", "type":"text", "flag":[], "textpre":"", "textpost":"" }], "index":0, "rating":0.001416, "urlfrom":"http://www.exampletwo.com", "ipfrom":"112.213.89.105", "title":"example title", "linksinternal":91, "linksexternal":51, "size":5735 }]} and have model of keys. urlto, visited, firstseen, prevvisited, anchor, type, textpre, textpost, index, rating, urlfrom, ipfrom, title, linksinternal, linksexternal...

Django template translation with variable order -

i want translate string in django template: {% trans "thank you. may <a href=\"/logout\">log out</a> now." %} so in english, result be: thank you, may <log out> now. but - example in german, need: vielen dank. sie können sich nun <ausloggen>. where text in <> hyperlink. problem order of words has changed, , not find way how this. did see in documentation can done in python code, "placeholders". need in templates. there way it? also, ease translation, don't html in translation file. highly appreciated! as @fsw recommended, see this . you should not hardcode "/logout", have use {% url "urlname" %} tag. see here maybe that? (i didnt test it) {% url "logout" logoutvar %} {% blocktrans logoutvar logoutvar %} "thank you. may <a href="{{ logoutvar }}">log out</a> now." {% endblocktrans %}

android ndk - ARM and GCC Compiling -

hopefully hasn't been asked , answered already, had quick question on arm. specifically, if when compiling android (which has lot of c , c++), use gcc compile, doesn't create x86 based code? how arm processor, uses reduced instruction set, can interpret code , run does? thanks! gcc doesn't compile x86. compiles instruction set. if wanted create new 1 adding few files. and arm isn't reduced instruction set. different instruction set. there's things arm has x86 doesn't , vice versa.

c++ - Sifting Down From Heap Removal -

i'm trying work heap. i'm inserting few random numbers removing them make sure heap works. problem when i'm removing them duplicate numbers shouldn't exist in heap. pretty i'll insert following numbers , in return: 5 2 10 10 reason. my main looks this: #include <iostream> #include <fstream> using namespace std; #include "heap.h" int main(void) { heap<int> inlist(4); inlist.insert(5); inlist.insert(2); inlist.insert(3); inlist.insert(10); int test; while(inlist.remove(test)) cout << test << endl; } and heap looks this: #ifndef heap_h #define heap_h template<typename type> class heap { private: type* heapdata; int currsize; int capacity; void _siftup(int); void _siftdown(int); int _leftchildof(int) const; int _parentof(int) const; public: heap(int c = 100); ~heap(); bool viewmax(type...

c# - Can i use static analysis in VS2012 from VS2010? -

for comparability reasons on first stage want use vs2010 engine microsoft visual studio 10.0\team tools\static analysis tools\ in vs 2012... there way this? i able replace(fake) files of code analysis 11 10.. analysis works. can't see ca errors(number , discription) when heppens i have overrided codeanalysispath, codeanalysisstaticanalysisdirectory , codeanalysistargets 10.0 version , founded vs 2012 invokes fxcopcmd.exe /outputculture:1049 , vs 2010 /outputculture:1033 other parametrs same. reason. can't find outputculture pparametr in fxcopcmd help... vslang! (visual studio language)...it seems problem solved overriding codeanalysispath , using same language version of vs. because before had english vs 2010 , russian vs 2012. you should able working pointing vs 2010 fxcop folder within vs 2012 project (e.g.: .csproj or .vbproj): <codeanalysispath>c:\program files (x86)\microsoft visual studio 10.0\team tools\static analysis tools\fxcop\</cod...

linux - Perl Directory Finder doesn't work? -

i have script find directories , .tar.gz files. whatever reason (that's i'm hoping can me with) my if ( -d $file ) doesn't return it's directory!!! my script: # specify directory want start search $directory = $argv[0]; $directorycount = 0; # calling subroutine, searches file readdirectory($directory); sub readdirectory { $directory = shift; $searchfile = shift; @directories; $tarouput; # little bit output, in directory script # searching @ moment (the following line not necessary) print "searching in $directory\n\n"; # open , close directory opendir(dir, $directory) or die("error: couldn't open specified directory $!"); @files = readdir dir; closedir dir; shift(@files); shift(@files); print "------------------------------------------------------------------------ \n\n"; foreach $currentfile (@files) { print "current file:", ...

php - Send array in ajax query -

i'm trying send array javascript php $.post() method of jquery. i've tried jquery.serialize() , jquery.serializearray() , json.stringify() , of them didn't work. here code: $.post("ajax/"+action+"_xml.php",{'array': array},function(data){console.log(data);}); the array looks : array["type"] array["vars"]["name"] array["vars"]["email"] array["vars"] has more 2 elements. the result in php $_post variable empty array (length 0). i suggest following structure on data pass: javascript: var dto = { type: [1,2,3], vars: { name: 'foo', email: 'foo@bar.com' } }; var stringifieddata = json.stringify(dto); // result in: //{"type":[1,2,3],"vars":{"name":"foo","email":"foo@bar.com"}} $.post("ajax/"+action+"_xml.php",{'dto': str...

mysql - C# SQL Query Multiple LIKE -

currently i'm making something. using (var idatabasequery = lightningbolt.getdatabasemanager().createqueryobject()) { idatabasequery.setquery("select * catalogue_baseitems name '%hc2_%' or name '%hc3_';"); data = idatabasequery.fetchtable(); } that's use, want items beginning hc2_ , hc3_, however, items starting hc2_. in sql contains items starting hc3_ doesn't show while executing query. wrong? if want items beginning hc2_ or hc3_ , need make 2 changes: don't use % @ beginning, and escape underscore because masks "any 1 character" try this: select * catalogue_baseitems name 'hc2\_%' or name 'hc3\_%' note %hc2_% match of following examples: abchc2x (because of leading % , underscore match x ) hc23 (because underscore match 3 ) ... , on

ios - Is there a way to find pid of a process of socket peer? -

i have following case: two applications (mine , 3rd party) on ios need communicate on tcp/ip i can change code of app, not 3rd party app the protocol can't changed (because can't change 3rd party app). in app, want make sure talk correct app. i know how can peer port geetpeername what looking way figure out pid of process uses port. i found similar question: how determine pid of peer tcp connection on same ios device? however, in case, both ports in same app. disclaimer: fine private api. won't sent appstore. however, looking solution non jailbroken phone. update 1 i said need pid, because there known ways of getting association between pid , application bundle id (using sysctl). generally speaking, don't care pid per se. concern figure out application on other side of socket. i don't have solution this, if going try it, proceed in following way: on unix system, can use lsof command determine processes have files open. include...

Elasticsearch equivalent to Map-Reduce -

what equivalent of map-reduce in elasticsearch when processing client-side? there "streaming" client can reduce data output comes in? assume need join, or complex filtering @ client side, type might not fit in memory without map-reduce scheme. don't mind waiting long time response, dont want crush machine (client and/or server). how should go this? example, mappings: {"book":{"properties":{ "title":{"type":"string", "index":"analyzed"}, "author":{"type":"string", "index":"analyzed"}, } {"character":{"properties":{ "book_id":{"type":"string", "index":"not_analyzed"}, "name":{"type":"string", "index":"analyzed"}, ...

ruby on rails - CanCan not filtering @products in Index -

i working on rails 3.2 application devise , cancan. my user model user, , want restrict access product resource ones created user. relevant code snippets: app/models/ability.rb class ability  include cancan::ability  def initialize(user) if user can :manage, product, user_id: user.id end end end app/controller/products_controller.rb class productscontroller < applicationcontroller load_and_authorize_resource .. end config/routes.rb ... devise_for :products resources :products resources :sizes end ... everything working expected: users cannot see, edit, etc... products not created them. problem if user access product index @ /products all products visible. how can filter relevant products in index page? i have googling around, , try authorize! :index, ability in index action can :index, product, user_id: user.id , user cannot access @ @ index page. any appreciated. this not authorization issue. instead should scope q...

cognos - Use summary data in row calulations on a report? -

i using cognos report studio 8.4.1. i have list report want use query calculation create new column of data, calculation needs 2 numbers summary (subtotal) of data want calculation for. possible? if so, how do it? sample data: id # project # reg ot bonus 2716 20130405 41.6 1.6 2716 20130412 38.9 0.0 2716 20130419 52.3 12.3 2716 20130426 47.0 7.0 2716 b03-1304 $23.17 2716 b15-1304 $1.51 - - - - - - - - - - - - - - - - - - - - - 2716 4 $24.68 ------------------------------------------ 2717 20130405 39.9 0.0 2717 20130412 40.2 0.2 (etc) the query calculation want create each line be: [total(bonus)] / [count(reg)] / (reg) / 2 * (ot) (this not work) so in above example, result first row of data be: 24.68 / 4 / 41.6 / 2 * 1.6 = 0.12 (rounded) is there any way can this, or equivalent? completely re-writing report or cre...

jpa - What kind of transaction context does an injected EntityManager have in an EJB whose transaction context is TransactionAttributeType.NOT_SUPPORTED? -

suppose have ejb annotated with: @transactionattribute(transactionattributetype.not_supported) suppose further has entitymanager injected it: @persistencecontext private entitymanager em; if perform various operations on entitymanager , resource-local transaction started , committed each such operation? or there 1 of them? or behavior undefined jpa specification? not find suitable paragraph either way in either jpa 2.0 specification or ejb 3.1 specification. i understand there not jta transaction started ejb method, not clear on kinds of transactions in effect underlying entitymanager . presuming behavior undefined i'm hoping larger stackoverflow community knows better, or has insight area of specification, or discussions dealt area. below few excerpts jsr 318 & section 13.6.5 might clear of questions. 13.6.2.1 not_supported the container invokes enterprise bean method transaction attribute set not_supported value unspecified transact...

dataframe - Query and aggregate data based on conditions in R -

i have data frame , want mean of values of type b each year, if type a have values equal 1. year type value1 value2 value3 value4 value5 1 1 1 2 3 4 1 b 10 12 9 8 10 2 1 2 2 2 1 2 b 11 10 13 9 14 so final product looks this: year type_b_values 1 11 2 12.5 which averages of value1 , value2 year1 , average of value1 , 5 year2 . thanks! here approach using base functions. i'm guessing plyr or reshape may useful packages here i'm less familiar them: dat <- read.table(text="year type value1 value2 value3 value4 value5 1 1 1 2 3 4 1 b 10 12 9 8 10 2 1 2 2 2 1 2 b 11 10 13 9 14", header=true) dat_split <- split(dat, dat$year) # spl...

Running PLSR predictions parallel in R using foreach -

users, i looking solution "parallelize" plsr predictions in order save pprocessing time. trying use "foreach" construct "dopar" (cf. 2nd part of code below), unable allocate predicted values model performance parameters (rmsep) output variable. the code: set.seed(10000) # generate data... mat <- replicate(100, rnorm(100)) y <- as.matrix(mat[,1], drop=f) x <- mat[,2:100] ed <- dist(x, method = "euclidean") # distance matrix find close samples edm <- as.matrix(ed) kns <- matrix(na,nrow(x),10) # empty matrix allocate 10 closest samples (i in 1:nrow(edm)) { # identify closest samples in loop , allocate kns kns[i,] <- head(order(edm[,i]), 11)[-1] } so far consider code "safe", next part challenging me, since never used "foreach" construct before: library(pls) library(foreach) library(doparallel) cl <- makecluster(2) registerdoparallel(cl) out <- foreach(j = 1...