Posts

Showing posts from September, 2011

Define an array object in java -

i found class declaration works me, wonder if class written more "short": public class data implements comparable <data>{ public data (int category, string quality, string title ) { super(); this.category = category; this.quality = quality; this.title = title; } int category; string quality; string title; @override public int compareto(data d) { return this.getduration_value() - (d.getduration_value()); } } why have mention "category, quality title" ? , why "super()" ? have shorter. found other explanations, "complex structure". the "data" given these lines, , want not have declare in advance length of array: data[] mydataarray = { new data(0, // category "0" "***", // quality "mytitle1") // title new data(0,

how to find service_name that I deleted in oracle11g -

i changed , saved service_name in tnsnames.ora. cannot connect oracle , remember also. can tell me how find service_name if followed installation recommendations service_name should same sid.

angularjs - <!DOCTYPE html> - Document Type Declaration must appear only once -

my code looks this: <!doctype html> <html lang="en" class="light" ng-app="app" ng-controller="appcontroller" id="ngapp" xmlns:ng="http://angularjs.org" xmlns:ui="ui-router"> in visual studio 2013 gives problem in editor , doctype underlined in green message saying: document type declaration must appear once has else found solution problem. note simple <html> not happen. code works in browser versions of vs2013 update 1-4 see green squiggly line under doctype. check , see if there layout file. if using template mvc visual studio provides layout file located @ views/shared/_layout . there can see <!doctype html> has been inserted.

c# - Dropdownlist Change event with javascript, when using an EditorTemplate -

i have editortemplate - works great. inside it, have dropdownlist decorate class, , 2 divs <div> @html.dropdownlistfor(m => m.type, (selectlist)viewdata["typelist"], "-- select --", new { @class = "typeselector" }) @html.validationmessagefor(m => m.type) </div> <div class="emaildiv">emailstuffhere</div> <div class="calendardiv">calendarstuffhere</div> im trying show 1 of 2 divs based on selection of dropdown list the dropdownlist populates fine, shown dropdown list 2 items "calendar" , "email" i have following javascript: function checkselection() { $(".emaildiv").hide(); $(".calendardiv").hide(); var selecteditem = $(this).val(); if (selecteditem == "email") { $(".emaildiv").show(); } else if (selecteditem == "calendar") { $(".calendardiv").show();

javascript - AngularJS attribute directive. How to add another attribute directive on 'compile' -

i create attribute directive add icon on button when it's disabled. like fiddle however, add ng-disabled directive on compile (with same disabled-button value) what best way ? if add attribute ng-disabled on compile function, never compile. so, if re-compile element on link function, have remove ng-tranclude directive due error. more, events, ng-click , triggered twice. bonus question: possible restrict attribute directive html elements <a> or <button> ? thx i'm afraid cannot add directives dynamically element contains directive. reason compile function called after angular has processed directive's element , determined directives attached it. adding attribute @ point late, discovery has taken place. there may ways don't know of (and interested in seeing stable, non-hackish one). i can suggest alternative may suit you: manually place ng-disabled on button, brevity , consistency let expression of ng-disabled drive dire

How to dynamically include all template partials when using a module in AngularJS -

i have several modules require template partials loaded whenever module used. storing these files in folder called partials inside each module subfolder. starting point app meanjs , , storing partials file in public/modules//partials/*.html. i have seen several ng-include , directive examples, being new angularjs each sample read confuses me further best practice / angularjs appropriate way this. store partials whenever wants. load them use angular template cache . use grunt or gulp generate automatically. use gulp. here working example of 1 of project. install nodejs , npm npm intall gulp -g npm install gulp-angular-templatecache create gulpfile.js var templatecache = require('gulp-angular-templatecache'), watch = require('gulp-watch'); gulp.task('generate', function () { gulp.src('public/*/partials/*.html') .pipe(templatecache('templates.js', {module: 'yourmodulename', standalone: false})

login - python post data with requests in python -

if try login account , not successful have phrase try again in url source page. tried write python script login account , stuff: update token=...#by xpath session=requests.session('http://example.com') response=session.get('http://example.com') cook=session.cookies postdata={'token':token, 'arg1':'', 'arg2':'', 'name[user]': user, 'name[password]':password, 'arg3': 'sign in'} postresp=requests.post(url='http://example.com/sth', cookies=cook, data=post_data) print postresp.content is there wrong postdata or etc? i sat cookies. you don't want show url - , difficult hit bulls eye without it:-) here's try let me know if works or please comment error here after. please note following points: -try use user agent in headers -token needs fetched after calling url (in following case 5th line) session=requests.session() headers={"user-agent":"mozilla/

c++ - glTranslatef moves diagonally instead of on major axes -

i want move object on x axis on key press. looks moving diagonally(up left , down right) here code : key press code : switch(key) { case 'a': x++; break; case 'b': x--; break; } on opengl part : glmatrixmode(gl_projection); glloadidentity(); gluperspective(30, 1 , 1 , 1000); glmatrixmode(gl_modelview); glloadidentity(); glulookat(100, 100, 100, 0, 0, 0, 0, 1, 0); gltranslatef(x;0,0); why gltranslatef working strangely, how can fix this? thanks. you're rotating before translate. rotate entire coordinate space , "translation along x axis" different. in future, make sure translate, scale, rotate. way each transformation intend without being manipulated prior transformation. suggest matrices, coordinate spaces, , opengl bit more. also, gltranslatef , other matrix stack functions deprecated. modern opengl. edit: glulookat rotation face @ point. so, there rotation involved. switch them around if don't want this.

phantomJS and Google Chart getImageURI() -

i image/png;base64 (server side) of google chart phantomjs $base64 = exec('phantomjs myscript.js'); header("content-type: image/png"); echo base64_decode( $base64 ); myscript.js : page.onconsolemessage = function(msg, linenum, sourceid) { console.log( msg ); phantom.exit(); }; page.open('http://getpngchart.dev/chart.php'); chart.php: <html> <head> <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript"> google.load("visualization", '1', {packages:['corechart']}); google.setonloadcallback(drawchart); function drawchart() { var data = google.visualization.arraytodatatable( [['task', 'quantity'], ['critical', 35], ['routine', 6], ['adjust', 2]] ); var options = {colors: ['#e34036','#f7a500',&#

regex - Regular expression for grep to detect sdaa but not sda -

i want grep devices in linux system except /dev/sda. my devices f.e. /dev/sda /dev/sda2 /dev/sdb /dev/sdc /dev/sde /dev/sdg /dev/sdi /dev/sdk /dev/sda1 /dev/sdaa /dev/sdbb /dev/sdd /dev/sdf /dev/sdh /dev/sdj /dev/sdl at moment i'm using following command: ls /dev/sd* | grep '\/dev\/sd[b-z]' which not detect /dev/sdaa. i thought use regular expression this: http://regexr.com/39u99 , invert result of grep -v couldn't work either. i appreciate :) edit: ok many of :) great answers far. extend question case when want exclude /dev/sda1 , /dev/sda2 etc. meaning /dev/sda , /dev/sda1 /dev/sda2 /dev/sda3 etc. you there, below regex you. \/dev\/sd(a{2}|[b-z]+) $ grep -po '\/dev\/sd(a{2}|[b-z]+)' file.txt /dev/sdb /dev/sdc /dev/sde /dev/sdg /dev/sdi /dev/sdk /dev/sdaa /dev/sdbb /dev/sdd /dev/sdf /dev/sdh /dev/sdj /dev/sdl and here regex demo instead of regex can try bash negation feature this. $ ls !(sda[0-9]

jquery - Dropdown doesn't contain empty value, still gets selected -

this question has answer here: jquery 1.10.1 setting non existing value on select 3 answers i have weird issue. i have dropdown no empty value option i.e. <option value="">select</option> my dropdown: <select name="dropdown" id="dropdown"> <option value="0">option 0</option> <option value="1">option 1</option> </select> however, when set the dropdown value so: $('#dropdown').val("") the dropdown shows empty option eventhough there no such option available in list. why happen? i've checked code , html , don't find empty option or code sets empty option. what cause of this? if pass non existing value(it not necessary pass "" ) method clear select element since there no matching option. therefore use sele

Azure: A guide for an availability set for Virtual Machine with a Storage -

a goal of post find out guide on creating availability set in azure typical web-site running on virtual machine storage connected virtual machine. in best scenario, guide should developers running in azure reduce downtime of web-site in case of temporary failure in networking/storage, etc while retaining maintenance fees low possible. the questions are: is possible have 2 virtual machines , storages within availability set different regions synchronized , guide achieve that. is possible have 1 vm , storage asleep , woken upon alarm of network (or other) fail or known issue received azure support , guide that. any other questions community may faced , being added here later. it's not possible have availability set span different regions created inside container of cloud service. if want have high availability across different regions, need use traffic manager allows combine cloud services. require deploy 2 separate cloud services , sync data/storage in yours

c++ - QGraphicsView and QMouseMove Event -

i have borderless (no title bar) qwidget window qgraphicsview inside. i've overwritten mousepressevent , mousemoveevent move window on desktop, when press on qgraphicsview not works. below, code of mousepressevent , mousemoveevent: void widget::mousepressevent(qmouseevent *evt) { oldpos = evt->globalpos(); } void widget::mousemoveevent(qmouseevent *evt) { const qpoint delta = evt->globalpos() - oldpos; move(x() + delta.x(), y() + delta.y()); oldpos = evt->globalpos(); } i overwritten same code: void mousepressevent(qgraphicsscenemouseevent *evt); void mousemoveevent(qgraphicsscenemouseevent *evt); i tried with: setinteractive(false); setdragmode(scrollhanddrag); but nothing! is there way solve this?

html - Animating with to zero whilst maintaining contents positioning -

i have css class designed reduce 0 width in nice animated way. works apart content (text etc) wrap new width animates , looks terrible. how can force (in generic way, hopefully) containing div maintain contents positioning whilst animating width 0? .highlightedsubsection.closed { overflow:hidden; width: 0%; height: 0%; /* here stop text contents pushing height down width hits 0 */ opacity: 0; -webkit-transition: .5s ease-in-out; transition: .5s ease-in-out; } you can wrap .highlightedsubsection in other element , apply width animation on wrapper. need give .highlightedsubsection fixed width. here example (hover text see animation): .wrap p { width:880px; background:teal; color:#fff; padding:10px; } .wrap{ width:900px; transition: width .5s ease-in-out; overflow:hidden; } .wrap:hover{ width:0; } <div class="wrap"> <p>lorem ipsum dolor sit amet, consectetur adipi

Android Studio update not showing libs folder -

Image
i update android studio 0.9 , after update hide libs folder in project structure but in real folders see libs folder, , in gradle script compile libs have param

ios - In my iPhone application. why i am getting the "Received memory warning"? -

i getting warning in iphone app "[651:57011] received memory warning". can body please me solve problem. it due low memory space of device , inefficient memory management. select product --> analyse checking memory leaks. hope may you

Center fixed marker in android v2 mapview -

i want set fixed marker in center point of mapview while dragging map.it has been done @ android map v1 google mapview . it's deprecated.now question is, possible in android map v2 google mapview ?(i have tried.but map doesn't show) i'm betting used getmapcenter() which, per google maps android v2, no longer available use. no worries, use this: googlemap.getcameraposition().target it return latlng object represents center of map. can use reposition marker center every time there's drag event assigning oncamerachangedlistener googlemap . yourgmapinstance.setoncamerachangelistener(new oncamerachangedlistener() { @override public void oncamerachange (cameraposition position) { // center of map. latlng centerofmap = yourgmapinstance.getcameraposition().target; // update marker's position center of map. yourmarkerinstance.setposition(centerofmap); } }); there. hope helped!

Paypal Rest API and Permissions API from classic -

im trying implement paypal on website, want give site-users ability add paypal payment option there web shops. i'm using laravel, , found one, http://jslim.net/blog/2014/09/19/integrate-paypal-sdk-into-laravel-4/ , pretty that. question is, possible combine permissions api classic api , using rest api shop? , point me in right direction? currently adding paypal rest api , classic api sdks causing namespacing conflict issues, prevent breaking changes in rest api. work under way release 1.x version of rest apis allow work both rest , classic apis together.

Auto add days to datetime as each days passes in mysql -

i want make column in mysql database when user login first time in system, stores datetime in mysql table. , since day in other column days add according register date. 1, 2, 3,....and on. so, there way can achieve results? please guide me soon. you can 1 column (to hold registration / first login date) , datediff function: create table users ( id int(11) not null auto_increment, name varchar(20) not null, registered_at datetime not null, primary key (id) ); insert users set name = 'myname', registered_at = now(); select registered_at, datediff(now(), registered_at) days_since users name = 'myname';

Trying to solve consumer-producer in java with multithreading -

i'm trying solve producer consumer problem threads in java, code won't run in parallell/concurrently. producer fills buffer before consumer starts consume, , don't why. point trying using synchronized blocks, wait() , notify(). main : string [] data = {"fisk", "katt", "hund", "sau", "fugl", "elg", "tiger", "kameleon", "isbjørn", "puma"}; producerconsumer pc = new producerconsumer(5); thread[] thrds = new thread[2]; thrds[0] = new thread(new mythread1(pc, data)); // producer thrds[1] = new thread(new mythread2(pc)); // consumer thrds[0].start(); thrds[1].start(); for(int = 0; < 2; i++) { // wait threads die try { thrds[i].join(); } catch (interruptedexception ie) {} } system.exit(0); producerconsumer.java: import java.util.linkedlist; import java.util.queue; public c

html - Div does not extend to fill the screen vertically -

i can't life of me green (content) , purple (nav) divs take remained of height space fill screen. i know simple have taken leave of senses , can't see it! http://www.bestlincs.co.uk/new/ body { margin: 0; padding: 0; } #main { height: 100%; border:dashed #d82629 1px; } #content { overflow: hidden; width: auto; height: 100%; background-color:rgba(41, 171, 0, 0.5) } #nav { float: right; background-color:rgba(41, 0, 226, 0.5); width: 250px; height: 100%; } #footer { position: absolute; bottom:0; width: 100%; height: 200px; background-color:rgba(41, 171, 226, 0.5) } <div id="main"> <div id="nav"> <p>navnavnavnavnavnavnavnav</p> </div> <div id="content"> <p>contentcontent<br>gf dfg dfg dfg dfg df</p> </div> <div id="footer"> <p>footerfooter&

Kendo UI TabStrip Helper -

i newbie in telerik (kendo). want know how can hide or show tab based on roles or authentication per user. guess been done helper, not sure how it. please me regarding this. thanks in advance. regards, ds its bit difficult provide best answer without seeing have far, if initializing tabstrip using javascript have list if tabs in html: <div id="example"> <div id="tabstrip"> <ul> <li id="tabparis" class="k-state-active"> paris </li> <li id="tabnewyork"> new york </li> <li id="tablondon"> london </li> </ul> <div> <div class="weather"> <h2>17<span>ºc</span></h2> <p>rainy weather in paris.</p> </div> <span class="rainy"> </spa

Strange console output from (program):1 in google chrome -

i'm seeing strange output in developer console web application: [object object] (program):1 it's if object.prototype.tostring() being called on , output console can find no references code writing console.log's. know (program):1 means source file? clicking takes me new browser tab blank.

Would like to just display 3 rows from mySQL result in python -

so right have query returns 20 rows. need these later cur.execute(query) rows in cur.fetchall(): print(rows) cur.close() conn.close() how write loop write row in range 1-3? use slice notation first 3 items rows. http://www.pythoncentral.io/how-to-slice-listsarrays-and-tuples-in-python/ for row in cur.fetchall()[:3]: print row

database - Neo4j - understanding cypher querying -

i'm quite new neo4j , cypher. have written following query: match (tp: tpproduct_version {tpproductcode: "z1115"}) <-[:is_tpbomparent_of]-(pv: product_version) <-[:is_bomparent_of*..]-(parent: product_version) return parent, pv, tp here result: http://postimg.org/image/ve76qy977/ actually expecting product_versions have [is_tpbomparent_of] relation z1115 plus parents, no matter if have 1 or not. but instead got these product_versions wich have parents wich don't seem ignored. i hope can follow thoughts! lot! nice if me out! :) greetings schakron so want use optional match . your query forces neo4j match pattern. if pattern doesn't exist, don't matched data back. in case want product_version s, not ones have parents, ones don't. so try query instead: match (tp: tpproduct_version {tpproductcode: "z1115"})<-[:is_tpbomparent_of]-(pv: product_version) optional match (pv)<-[:is_bomparent_of*..]-(parent: prod

Compiling external C++ library for use with iOS project -

i'm new using c++ libraries, appreciate might bit specific case (let me know , can provide more details). i have external c++ library i'm trying use ios project. library follows configure, make, make build pattern output .a library file. when try , add library file xcode, following error: ignoring file /users/developer/ios/testproj/libpresage.a, file built archive not architecture being linked (i386): /users/developer/ios/testproj/libpresage.a based on this question , i've tried turning build active architecture no, , same error. makes me suspect i've compiled library incorrect architecture. running lipo -info on .a file gives: input file libpresage.a not fat file non-fat file: libpresage.a is architecture: x86_64 given isn't armv7s, armv7, or arm64, try , compile c++ library again following parameters: 1) try ./configure cc="gcc -arch armv7s" \ cxx="g++ -arch armv7s" \

depth first search - Python maze generator explanation -

welcome. can explain me happens in code? know how work (it comes http://rosettacode.org/wiki/maze_generation#python ). from random import shuffle, randrange def make_maze(w = 16, h = 8): vis = [[0] * w + [1] _ in range(h)] + [[1] * (w + 1)] ver = [["| "] * w + ['|'] _ in range(h)] + [[]] hor = [["+--"] * w + ['+'] _ in range(h + 1)] def walk(x, y): vis[y][x] = 1 d = [(x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)] shuffle(d) (xx, yy) in d: if vis[yy][xx]: continue if xx == x: hor[max(y, yy)][x] = "+ " if yy == y: ver[y][max(x, xx)] = " " walk(xx, yy) walk(randrange(w), randrange(h)) (a, b) in zip(hor, ver): print(''.join(a + ['\n'] + b)) make_maze() i know nothing maze generation, got curious how piece of code works. here insights: these 2 lines print maze: for (a, b) in zip(hor

c# - Environment.TickCount vs DateTime.Now -

is ever ok use environment.tickcount to calculate time spans? int start = environment.tickcount; // stuff int duration = environment.tickcount - start; console.writeline("that took " + duration " ms"); because tickcount signed , rollover after 25 days (it takes 50 days hit 32 bits, have scrap signed bit if want make sense of math), seems it's risky useful. i'm using datetime.now instead. best way this? datetime start = datetime.now; // stuff timespan duration = datetime.now - start; console.writeline("that took " + duration.totalmilliseconds + " ms"); use stopwatch class. there decent example on msdn: http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx stopwatch stopwatch = stopwatch.startnew(); thread.sleep(10000); stopwatch.stop(); // elapsed time timespan value. timespan ts = stopwatch.elapsed;

objective c - transition between is and iOS 8 using NSString imageURL -

new ios development, app worked fine in ios 7 upon release of ios 8, app wouldn't open, set breakpoit led me home screen , line. appears there issue pulling image url correct. xcode output - uiimageview setimagewithurl:placeholderimage:]: im struggling find solve it [cell.imagelabel setimagewithurl:[nsurl urlwithstring:imageurl] here bit more code setting data nsdatecomponents *components = [[nscalendar currentcalendar] components:nsdaycalendarunit | nsmonthcalendarunit | nsyearcalendarunit fromdate:[nsdate date]]; nsinteger month = [components month]; nsinteger year = [components year]; _images = @[[nsstring stringwithformat:@"http://w***.jpg?month=%i&year=%i", month, year], [nsstring stringwithformat:@"http://***.jpg?month=%i&year=%i", month, year], [nsstring stringwithformat:@"http://***.jpg?month=%i&year=%i", month, year], [nsstring stringwithformat:@"http://***.jpg

how does inheritance work with abstract classes in java -

i writing small pieces of code make sure understand java basics , have following. package teams1; public abstract class team1{ private string sport = new string(); public abstract string getsport(); public abstract void setsport(); } import teams1.*; abstract class footballteam1 extends team1{ public string getsport(){ return "football"; } public void setsport(){ this.sport="football"; } } it doesn't compile because sport private in super class, thought footballteam1 inherit it's own copy of sport because extending team1. appreciated. thanks! you have answered own question. footballteam1 not have access private fields of parent. ' protected ' scope used for. however, child footballteam1 have own copy of field. has copy of fields parent class has, can see cause confusion. the reason distinction modularity. subclass of parent class has access parts of parent class 1 has explic

sql - Can I avoid doing this Row by Row -

if have 2 tables columns shown below. want fill in actualstart , actualend times based on earliest , latest times scanned within shift. is there way in linq or set based way in sql? currently intend use cursor , go through each row in usersshifts earliest , latest fingerprint scan times within user's shift , update actualstart , actualend columns usersshifts usersshiftsid userid shiftstart shiftend actualstart actualend fingerprintscan userid scannedtime you can in sql adding time constraint join : select us.usersshiftsid, us.userid, us.shiftstart, us.shiftend, min(fs.scannedtime) actualstart, max(fs.scannedtime) actualend usersshifts left join fingerprintscan fs on us.userid = fs.userid , fs.scannedtime between us.shiftstart , us.shiftend group us.usersshiftsid, us.userid, us.shiftstart, us.shiftend

What preprocessing operations are performed by Tesseract OCR? -

i couldn't find detailed documentation , don't feel browsing source code. want not redo canny edge detection example if done tesseract engine. this document provides overview of engine: https://github.com/tesseract-ocr/docs/blob/master/tesseracticdar2007.pdf so looks don't need implement canny edge detection. tesseract uses otsu thresholding binarize image before processing https://github.com/tesseract-ocr/tesseract/blob/master/ccstruct/otsuthr.h edit: if want see binarized image create new config file in "\tessdata\configs\", add line: tessedit_write_images true , process image: tesseract your_image out your_config_file . tesseract saves binarized image tessinput.tif .

scala - flatMap on class with parameterized type wont compile -

can tell me why following: case class item[a, b, c](a : a, b: b, c: c) val s1 = seq(1, 2, 3) val s2: seq[item[_,_,_]] = seq(item(3, "q", "r"), item(4, "s", "t"), item(5, "u", "v")) s1.flatmap { => s2.find(_.a == i) match { case some(i2) => some(item(i2.a, i2.c, i2.b)) case none => none } } gives me following compiler errors , best way around it: - no type parameters method flatmap: (f: int => scala.collection.gentraversableonce[b])(implicit bf: scala.collection.generic.canbuildfrom[seq[int],b,that])that exist can applied arguments (int => iterable[item[_0]] forsome { type _0 }) --- because --- argument expression's type not compatible formal parameter type; found : int => iterable[item[_0]] forsome { type _0 } required: int => scala.collection.gentraversableonce[?b] - cannot construct collection of type elements of type b based on collection of type seq[int]. - c

mysql - generate random alphanumeric key in Ms. Access -

by having code on vb script private sub worksheet_selectionchange(byval target range) dim ltr, rnum, alphaltrs, selltr if not intersect(target, me.columns(2)) nothing , _ target.cells.count = 1 if target.value = "" alphaltrs = "abcdefghigklmnopqrstuvwxyz" selltr = application.roundup(rnd() * 26, 0) ltr = mid(alphaltrs, selltr, 1) rnum = application.roundup(rnd() * 999999, 0) target.value = me.range("a" & target.row) & "-" & ltr & rnum end if end if end sub i need create through ms. access, stock keeping products ms access table contains fields id [primary key] product title [short text] type [short text] sku [short text] image preview [attachment] price [number] availability [yes/no] what need sku auto generate keys new product, unique key, may button on form while inserting new entry or may new entry , key same excel code e.g. z401374 (alpha numeric) , once genera

How to pass variables in the MySQL connection string in php -

i have txt file contains log in credentials separated newline. want pick data file , set connection string according that. here's code that. $db = array(3); $myfile = "sqlaccess.txt"; $handle = fopen($myfile, 'r'); if(!feof($handle)) { for($i=0;$i<4;$i++) { $db[$i] = fgets($handle); echo $db[$i]; echo "<br>"; } } else { fclose($handle); } $dbhost = $db[0]; $dbuser = $db[1]; $dbpass = $db[2]; $dbname = $db[3]; the echo command displays correctly saved in file. connection string is: $conn = mysqli_connect($dbhost,$dbuser,$dbpass, $dbname); this not working. connection fails but connection succesful if hard code follows: $conn = mysqli_connect('localhost','root','password', 'newdb'); but hardcoding not practice. going wrong in code?? fgets not strip \n returned string, either need trim them yourself: $db[$i] = trim(fgets($handle)

r - Optimize a code combining title of a list -

i have list factor.lst composed of 16 elements. each element of list vector of characteres. obtain new vector of size [1:16] composed combinaison of each charactere string. manage obtain want using : col.titles <- c(paste(factor.lst[[1]], collapse=" "), (paste(factor.lst[[2]], collapse=" ") ... (paste(factor.lst[[16]], collapse=" "))) but that's lot of line reach 16 ! how can call list directly instead of each element within list ? thinking of that's not working. col.titles <- c(paste(factor.lst[[1:16]], collapse=" ")) sapply apply function each element of object, can use apply paste(x, collapse=' ') each element of factor.lst . try: sapply(factor.lst, paste, collapse=' ')

sql server 2008 - Updating a table instead of Insert Into -

i selecting data table , inserting if data in table not exist. declare @employeenumber nvarchar(100) set @employeenumber = 'emp001' if exists(select e.employeenumber [databaseone].[dbo].[employee] e e.employeenumber = @employeenumber) begin if not exists(select ut.employeenumber usertable ut ut.employeenumber = @employeenumber) begin insert usertable(employeenumber, surname) select e.employeenumber, e.surname [databaseone].[dbo].[employee] e e.employeenumber = @employeenumber end else begin --update end end if data exist want update existing data. how can update opposed insert into. kind regards you should use merge funcion. your query this: merge usertable target using (select e.employeenumber, e.surname [databaseone].[dbo].[employee] e employeenumber = @employeenumber) source on target.employeenumber = source.employeenumber when mathced update set target.surname = source.surname when not matched insert (em

ruby on rails - Is it bad practice for scripts to write over parts of themslves? -

i writing script (a rails runner, if matters) run periodically. uses gem query sql database. because database not update existing rows, merely adds new ones reflect changes data, script run query finds objects id greater id in database last time script run. in file should id stored? bad practice store in script , have script write on itself, , if so, why? store id in separate file. not script writing on more difficult correctly, practice confuse users, , result in whole host of other problems, such additional friction when trying version control script or update new version. under circumstances, data , code should separate.

java - How to dynamically set value of mask option of @Validate annotation -

here's code: somefile.properties string.regex="someregex" someactionclass.java @value("${string.regex}") private string regex=""; @validate(mask = regex) private string stringtovalidate; the file somefile.properties loaded on server startup , value "someregex" stored somewhere in session, available. the problem mask requires constant value, , if put final @ regex="" cannot overwrite init value string.regex one; on other hand if put final not initialize variable, java compiler complain it. is there way use mask option value retrieved file not know? is possible directly on jsp in smart way, since i've have several fields validate , not want perform check , write message error each one? annotation value can changed @ runtime using reflection. please take @ (see post marked answer) modify class definition's annotation string parameter @ runtime be careful approach, of caveats of described. als

haskell - Type inference interferes with referential transparency -

what precise promise/guarantee haskell language provides respect referential transparency? @ least haskell report not mention notion. consider expression (7^7^7`mod`5`mod`2) and want know whether or not expression 1. safety, perform twice: ( (7^7^7`mod`5`mod`2)==1, [false,true]!!(7^7^7`mod`5`mod`2) ) which gives (true,false) ghci 7.4.1. evidently, expression referentially opaque. how can tell whether or not program subject such behavior? can inundate program :: on not make readable. there other class of haskell programs in between miss? between annotated , unannotated one? (apart related question found on there must else on this) the problem overloading, indeed sort of violate referential transparency. have no idea (+) in haskell; depends on type. when numeric type unconstrained in haskell program compiler uses type defaulting pick suitable type. convenience, , doesn't lead surprises. in case did lead surprise. in ghc can use -fwarn-type-default

ios - Register for remote notifications in navigation controller -

i have many different views in app. while application state active have generic response remotenotifications not alertview. 1 way place notification observer in uinavigationcontroller rather in different view controllers , place notification element in navigationcontroller.view. however, far nothing appears in navigationcontroller.view when try add label there. has had success doing this? if understand correctly, seems want show view whenever app receives remote notification , want able display view anywhere inside app. if correct, best approach create new uiwindow object , display overlay on top of app's main window. answer describes how create uiwindow , display it. additionally, library similar you're trying accomplish.

twitter bootstrap - Typeahed.js not filtering -

i using following code based on examples https://twitter.github.io/typeahead.js/examples/ : var cararray = [{ carid: 1, fullname: 'opel' }, { carid: 2, fullname: 'bmw' }, { carid: 3, fullname: 'mercedes' }]; var cars = new bloodhound({ datumtokenizer: bloodhound.tokenizers.obj.whitespace('fullname'), querytokenizer: bloodhound.tokenizers.whitespace, //local: cararray, remote: '/api/cars' }); cars.initialize(); $(elt).typeahead(null, { name: 'car', displaykey: 'fullname', source: cars.ttadapter() }); uncommenting local works fine, remote list not filtered, items. so json returned remote : [{"carid":1,"optionone":"asd","optiontwo":"qew","fullname":"opel"}, {"carid":2,"optionone":"fas","optiontwo":"qew","fullname":"bmw"},{"carid":3,"opt

Using ! operator on a shell command -

i'm trying write script if particular string not present in file. i know in order check if string available, can like: if grep -qi "sms" $file; but how combine ! operator shell command? just add in front of condition make evaluate on contrary: if ! grep -qi "sms" $file; echo "yes"; fi ^ test $ cat hello bye $ if ! grep -qi "sms" a; echo "sms not found"; fi sms not found

c# - Invalid length for Convert.FromBase64String -

so i'm trying decrypt encrypted string, encrypts fine, , decrypts if i'm lucky enough string length long.. firstly here code called decryption method decrypted = decrypt(recieved, getstring(anarchyaes.key)); addtochat(decrypted); recieved encrypted string, , other parameter decryption key. here decrypt method.. public static string decrypt(string cipherstring, string securitykey) { var key = securitykey; var keyarray = encoding.utf8.getbytes(key); var tdes = new tripledescryptoserviceprovider { key = keyarray, mode = ciphermode.ecb, padding = paddingmode.pkcs7 }; var ctransform = tdes.createdecryptor(); var toencryptarray = convert.frombase64string(cipherstring); var resultarray = ctransform.transformfinalblock(toencryptarray, 0, toencryptarray.length); tdes.clear(); return encoding.utf8.getstring(resultarray); } it fails when does var toen

vb.net - Loop through all cells in Range using Interop -

i want loop through cells in range. dim rngtop, rngall excel.range 'set cell rngtop = directcast(_sheet.cells(1, 2), excel.range) 'set range top cell last cell in cells column rngall = rngtop.end(excel.xldirection.xldown) each cell excel.range in rngall if cell.value2 = "x" 'do stuff end if next cell.value underlined , gives me compil error cell.value2 object , cannot use operator (= in case) on it. me task accomplished? value2 should not object. i tried: dim cell excel.range = nothing dim integer = 1 rngall.rows.count if directcast(rngall.cells(i, 5), excel.range).value2 = "x" 'do stuff end if next but have same problem above. i guess have solution. problem here vb doesnt know type value2 deliver delivers object. why code give message =-operator cannot applied. using if cstr(cell.value2) = "x" ... works perfect. best write function che

sql - Reference a table from a scalar UDF - tied to schema name? -

due rollout/architecture of our system, create scalar udf use within select statement in stored procedure because our various dev/test/live environments have different schema names, ideally name udf dbo.myfunctionname, however, because function contains logic uses select statement values database table return answer means cannot use dbo must put under schema of database (ie: test) note - right, right? when calling function select statement, must provide two-part name, must use test.myfunctionname select name, age, test.myfunctionname(personid) people is there way parameterise schema name when roll out different schema, not need create function under each 1 and/or amend how called? ideally, i'm looking select name, age, schema_name().myfunctionname(personid) people but i'd not use dynamic sql if possible many thanks your question 2 questions: does function need have same schema tables it's selecting from? answer no . dbo.myfunction() can se

c# - Client Side Configuration in Silverlight -

i have silverlight app. need add config settings on silverlight app. thought there app.config file add. true? if so, how config values app.config file in silverlight app? thank you! i don't believe supported read application settings app.config file directly in silverlight. create xml file , read settings manually ( example code). if not run standalone desktop application (out-of-browser) make use of initialization parameters (initparams msdn ) can pass silverlight application using aspx page. keep dynamic, use querystring parameters. the aspx code run silverlight application initparams: <form id="form1" runat="server"> <div id="silverlightcontrolhost"> <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" id="xaml1" width="100%" height="100%"> <param name="initparams" value="k1=<

Not found StoryBoarding Tab in PowerPoint -

somehow, lost storyboarding tab in powerpoint. how can recover it? thanks. i using both powerpoint2010, , powerpoint2013 i had same issue. able resolve going to powerpoint options > add-ins there noticed team foundation add-in disabled. when enabled it, storyboard ribbon showed up. i'm using office 2013 vs 2013 update 4. good luck fix.

ios - Core Data - Insert based by parameter -

i have table called person. how make data entry based name, not repeat names. example: i have person named josh. can not have person named josh. similar function of pk. unfortunately, coredata doesn't have built-in way prevent dupes. first, fetch request predicate see if value exists. if not exist, insert new entity. example) let appdelegate = uiapplication.sharedapplication().delegate appdelegate let managedcontext = appdelegate.managedobjectcontext! let personname = "josh" let fetchrequest = nsfetchrequest(entityname: "person") let predicate = nspredicate(format: "name = %@", personname) fetchrequest.predicate = predicate var error: nserror? let fetchedresults = managedcontext.executefetchrequest(fetchrequest, error: &error) [nsmanagedobject]? if let results = fetchedresults { // if no results found, insert if results.count == 0 { let entity = nsent

Python scatter plot - how to see number of entries per point -

Image
i have data points repeat quite lot of entries (creating many overlapping (x,y) points) , i'm interested in knowing number of entries each point on graph. there easy way of doing (besides obvious of writing piece of code this?) first of points list of tuples: l = [(1,2), (0,0), (0,0), (1,2), (1,2), (3,4)] i'm assuming you're reading data in file or something, , not hard-coding did above, modify import routine give list of tuples, or post-process imported data form list of tuples. why going on tuples? because hashable, , therefore can used make set: s = set(l) print (s) set([(1, 2), (0, 0), (3, 4)]) now have unique points in data, yay! ... how many times each repeated? can done counting them in list... or being lazy list count its-self using lists count method: f = {} in list(s): f[i] = l.count(i) now f dictionary containing frequency table each of our (x,y) points f.keys() give of unique locations, , dictionary contains how many times each poi

javascript - php (#200) The user hasn't authorized the application to perform this action -

what should fix problem code using facebook graph api require_once("src/facebook.php"); // set right path $config = array(); $config['appid'] = '000000000000000'; $config['secret'] = '0000000000000000000000'; $config['fileupload'] = false; // optional // $config['publish_actions'] = true; $fb = new facebook($config); $params = array( // access token fan page "access_token" => "--------------------- access token --------------------------", "message" => "here blog post auto posting on facebook using php #php #facebook", "link" => "http://www.pontikis.net/blog/auto_post_on_facebook_with_php", "picture" => "http://i.imgur.com/lhkosih.png ", "name" => "how auto post on facebook php", "caption" => "www.pontikis.net",

java - NimbusLookAndFeel and serialization -

Image
hi want filter jtable in nimbuslookandfeel because when save program jtable change want show of thing nimbuslookandfeel use default jtable in class thank you! you see in before , after saving. want stop nimbuslookandfeel jtable.

Tracking changes in data with Firebase -

i'm interested in synchronized database paradigm championed firebase , others (couchbase sync gateway example). great job in replacing 80% of api does, storing , retrieving data. usually, that's not api does. while storing , retrieving data, doing non-data related stuff sending emails or push notifications. things, should able intercept data changes , when new record created, when existing record changed in way, or when record deleted. parse has great mechanism in cloud code ( https://parse.com/docs/cloud_code_guide#functions-aftersave ) couldn't find similar in firebase. did miss or thinking of wrong way? firebaseref.on('child_changed', function(childsnapshot, prevchildkey) { // code handle child data changes. }); this article : https://www.firebase.com/docs/web/api/query/on.html child_change event

c - How to print from 1 to 9 with three numbers in a line using loops -

i coding tic tac toe game in c. stuck @ making board this: 1 2 3 4 5 6 7 8 9 i want use loops dont have use printf function many \n 's , \t 's... here's attempt: for (i=0;i<=9;i++) { printf("\n\n\n\t\t\t"); (j=i;j<=i+2;j++) { printf("%c\t",boarddots[j]); } if (i==3) break; } something this, adapt actual needs: for(int = 1; <= 9; ++i) { printf("%d", i); // print numbers 1 one if (0 == % 3) printf("\n"); // start new line if current number divisible 3 } p.s. sorry possible typos

html - Replacing <br> within a table, using css -

is there way replace < br > tags within table char or string? can't access table itself, can use css decide how how table being displayed. < br> tags outside table work properly. white-space it's property values doesn't seem work. possible this? sorry if didn't mention important, i'm new css. you can change <br> tag character this: <style> br { content: ""; } br:after { content: ","; } </style> test <br> test in example decided display comma.

Android: difficulties referencing resources -

i'm still newbie android programming, tried tutorial create music app. @ stage in tutorial asked create new class extends base adapter , @ point in new class asked use layout inflater to inflate secondary layout, created. problem new class created when try inflating or referencing resource element @ all, errors. question : 1. impossible refer resources classes create ? 2. there error in ide(eclipse) or java thing. here's secondary layout xml file , class created. java lines * have errors. when inflating "r.layout.song","r.id.song_artist" , "r.id.song_title" import android.r; import android.r.*; import android.view.view; import android.view.viewgroup; import android.widget.baseadapter; import android.content.context; import android.view.layoutinflater; import android.widget.linearlayout; import android.widget.textview; import java.util.arraylist; public class songadapter extends baseadapter { private arraylist<song> songs; private l

ubuntu 14.04 - Is it possible to use OpenShift without using rhc? -

i trying application running on openshift after trying create ssh key on ubuntu using ssh-keygen ran permissions problems. because find have no need rhc client if automates process bloats computer (laptop) ruby installation. i find best have alternative ubuntu (linux) users. possible make happen or have go rhc way? you long way without rhc command line tool. can create ssh key , add/mange via openshift website. can create application there , add cartridges. when comes starting app, can jsut pushing git repository. last not least, can ssh onto openshift gear , lot there, example view log files. that said, rhc client 1 stop client (and more). if might not need right , task in fact done easier without it, still recommend install it. lot of information/tutorials using rhc , w/o enough experience not know how achieve task in different way.