Posts

Showing posts from June, 2012

mysql - Sql Server default value average of x rows -

i have following trigger running on mysql: create definer=`root`@`%` trigger `before_insert` before insert on `table` each row set new.avg_column1 = (select avg(column1) (select column1 table order datetimecol desc limit 20) column1_a), new.avg_column2 = (select avg(column2) (select column2 table order datetimecol desc limit 20) column2_a), new.avg_column3 = (select avg(column3) (select column3 table order datetimecol desc limit 20) column3_a) basically goal here set automatic, default value in avg_columnx column, based on last 20 entries in columnx, whenever new row inserted. working fine in mysql using mentioned trigger. i in process of migrating project sql server express ms, , i'm trying same there. have pointers how accomplish this? using triggers, computed columns, etc? thanks input! the logic different in sql server because using inserted rather new . basically: update t set avg_row1 = tt.avg1, avg_row2 = tt.avg2, avg_row3 = t

google chrome - Meteor Dev Tools Auditor is marking collections as insecure -

i use meteor dev tools plugin in chrome, , i’ve noticed cool new feature, worrying me way i've coded app. audit collection tool telling me of collections insecure. i still using meteor 1.2 blaze 1. 1 of them meteor_autoupdate_clientversions 1.1. should worry one? 1.2. how protect it? insert , update , remove marked insecure. 2. have cycles collection, has marked insecure: update , remove collection updated on database , not supposed accessed frontend, , not meant related client interaction. for collection have these allow/deny rules in common folder (both client , server) i've tried applying these rules on server side, didn't see difference on audit results. 2.1. should these rules on server side? cycles.allow({ insert: function () { return false; }, remove: function () { return false; }, update: function () { return false; } }); cycles.deny({ insert: function () { return true; },

How to update Android in-app billing to the latest version? -

i using in-app billing 3 in apps. want update in-app billing 5. how do that? have searched without finding info. thing should update iinappbillingservice.aidl file? no other files need updated? the newer versions seem add functionalty existing api yes, believe need change aidl file use new features.

mysql - Retrieve database result and assign it to a string in C# -

i have below table @ sql server. table name- userinfo name company_id task1 task2 task3 anna 123 true true false neeva 456 false true false i need know user task1, task2 , task3 status. e.g. anna has true task1 , task2. need below output. annas details string --> (task1, task2) neeva --> (task2) now using sql query, select case when ( substring (value, len(value), 1) = ',') substring (value, 1, (len(value) -1) ) else value end ( select (case when task1 = 1 'task1,' else ''end) + (case when task2 = 1 'task2,' else ''end) + (case when task3 = 1 'task3,' else ''end) value userinfo tab i following result in sql new column. (no column name) task1,task2 task1 instead of creating new column output needed, need pass output c#. e.g. if want know status of anna, query database , check user anna first. once done, check status. so @ c# side, need this s

r - find the max frequency per row in a matrix whith multiple max -

i have matrix this: mat=matrix(c(1,1,1,2,2,2,3,4, 4,4,4,4,4,3,5,6, 3,3,5,5,6,8,0,9, 1,1,1,1,1,4,5,6),nrow=4,byrow=true) print(mat) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [1,] 1 1 1 2 2 2 3 4 [2,] 4 4 4 4 4 3 5 6 [3,] 3 3 5 5 6 8 0 9 [4,] 1 1 1 1 1 4 5 6 i find out number of row of matrix in can find objects max frequency, have more 1 max. in case, obtein new vector this: [,1] [1,] "1" [2,] "3" or similar. focus on index of row more 1 max. we can use apply margin=1 loop on rows. frequency of each unique element tabulate , check whether equal max value ( == ) , use which numeric index. return max value if there ties. lst <- apply(mat, 1, function(x) {x1 <- tabulate(x) which(x1 == max(x1)) }) if there single max value per row, output vector or else list output. if need

excel vba - copying selected data from one workbook to another with readdressing cells -

guys need funky vba commands. have 2 spreadsheets, first labownik-mil-2dl8.xls , second zestawienie.xls , want select rows in first 1 copy second 1 not a1 a1. if selection rows 5270 5273 want example e5272 d7 , ak5272 e7 , on. nice if done button press in second spreadsheet (firstly making selection in first spreadsheet). makro should paste first empty row in second spreadsheet. have this: sub get_data() dim lastrowdb long, lastrow long dim arr1, arr2, integer sheets("zestawienie") lastrowdb = .cells(.rows.count, "d").end(xlup).row + 1 end arr1 = array("e", "ak", "b", "d", "f", "g", "h") arr2 = array("d", "e", "f", "h", "l", "m", "n") = lbound(arr1) ubound(arr1) sheets("labownik") lastrow = application.max(3, .cells(.rows.count, arr1(i)).end(xlup).row)

regex - match multiple slashes in url, but not in protocol -

i try catch multiple slashes @ ende or inside of url, not slashes (which 2 or more), placed after protocol (http://, https://, ftp:// file:///) i tried many findings in similar so-threads, ^(.*)//+(.*)$ or [^:](\/{2,}) , or ^(.*?)(/{2,})(.*)$ in http://www.regexr.com/ , https://regex101.com , http://www.regextester.com/ . nothing worked clear me. its pretty weird, can't find working example - goal isn't such rar. share working regex? here rule can use in site root .htaccess strip out multiple slashes anywhere input urls: rewriteengine on rewritecond %{the_request} // rewriterule ^.*$ /$0 [r=301,l,ne] the_request variable represents original request received apache browser , doesn't overwritten after execution of rewrite rules. example value of variable get /index.php?id=123 http/1.1 . pattern inside rewriterule automatically converts multiple slashes single one.

How to bind event on parent's element using Angular 2 -

i earlier adding button element inside child component's template due separation of code, had put button outside of child's template (in parent's template). i not sure how bind click event on button trigger function on child component. please suggest. parent: @component({ selector: 'app', template: ` <button>click me call child's showme()</button> <child></child> ` }) child: @component({ selector: 'child', template: `hi...` }) class child { public showme() { console.log("showme called..."); } } i don't want put event binding code in parent's template want pass button reference child component & bind event inside child component itself. you can use template variable reference siblings <button (click)="child.dosomething($event)">click me</button> <child #child></child>

list - How to dislpay only the names of the users when opening /etc/group in Python? -

this code: grouplist = open("/etc/group" , "r") grouplist f2: open("group" , "w+") f1: f1.write(f2.read()) f1.seek(0,0) command = f1.read() print print command what command can use make display names of users without ":x:1000:" you achieved target. little fix in code, here solution. open("/etc/group" , "r") source: open("./group" , "w+") destination: destination.write(source.read()) source.seek(0,0) user in source.readlines(): print user[: user.index(':')] nevertheless, show names, still copy original file. this way write names in new file. with open("/etc/group" , "r") source: open("./group" , "w+") destination: user in source.readlines(): u = user[: user.index(':')] destination.write('%s\n' % u)

nlp - Google Like Search Mechanism -

i want search mechanism similar google using nlp(natural language processing) in java. algorithm should able give auto-suggestions , spellcheck , meaning out of sentence , display top relevant results. example , if typed "laptop" relevant results shown ["laptop bags","laptop deals","laptop prices","laptop services" ,"laptop tablet"] is possible achieve nlp , semantics? appreciable if post reference links or ideas achieve. "get meaning out of sentence" - that's difficult task. don't believe google in search engine;) when talking searching getting meaning of query not important...but depends on mean "get meaning", anyway can buy "google search appliance" - private google search box. all other requirements quite straightforward. i'm java land soi'd suggest at: apache lucene - if developer, it's indexer created around full text searches elasticsearch it'

android intent give NullPointerException in gridview setonitemclickListener event -

android intent give nullpointerexception in gridview setonitemclicklistener event public class gridfragment extends fragment { gridview mgridview; private gridadapter mgridadapter; griditems[] griditems = {}; private activity activity; public gridfragment(griditems[] griditems, activity activity) { this.griditems = griditems; this.activity = activity; } @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { view view; view = inflater.inflate(r.layout.grid, container, false); mgridview = (gridview) view.findviewbyid(r.id.gridview); return view; } @override public void onactivitycreated(bundle savedinstancestate) { super.onactivitycreated(savedinstancestate); if (activity != null) { mgridadapter = new gridadapter(activity, griditems); if (mgridview != null) { mgridvie

Create dynamic <select> with PHP -

i have $_session variable $_session['invoicedate'] populated value representing yyyymm . i need dynamically build select element have 6 options going 'invoicedate' e.g. if $_session['invoicedate'] = 201602 output should be... <select id="invoicedate" name="invoicedate"> <option value="201602">feb 2016</option> <option value="201601">jan 2016</option> <option value="201512">dec 2015</option> <option value="201511">nov 2015</option> <option value="201510">oct 2015</option> <option value="201509">sep 2015</option> </select> my php basic... can split session value , assign first 4 digits $year , other 2 $month. loop 6 times... each time echo output <option> line concatenating year , month make value , subtracting 1 month , if month=0 take 1 year , make month 12.

c# - Get Properties.Settings from another WinForms App -

i have 2 win forms apps both deployed via same clickonce deployment. problem happening when both apps installed in release via clickonce. one dostuff app, other config app. dostuff app references config app , uses properties.settings have been added config app. this works fine far, dostuff app picks default settings config app. so, open config app , change of settings -> creates user.config file in appdata/local/config app/blurb/user.config it has saved settings , reads them correctly next time load config app, open dostuff app -> hasn't loaded config apps settings file , still grabs default settings present in config app. why isn't dostuff app grabbing correct settings config apps user.config file?

Create/Run IntelliTests automatically -

i have been working pex(intellitests) time , wondered if possible create tests via sort of command(or .exe) , not through ide(vs2015) right-clicking function. i have automated process builds projects , further runs tests. if intellitests not generated anew new implementation rather useless. this may seem basic question unfortunately not find information on internet. a command line intellitest not yet supported. if see supported, kindly add vote here: https://visualstudio.uservoice.com/forums/330519-team-services/suggestions/8623015-enable-intellitest-to-run-in-the-build-pipeline

ibm bluemix - IBM-containers: Retrieving client certificate for IBM containers failed -

Image
i newbie bluemix , have problems containers. installed docker toolbox (my os windows 7). afterwards installed bluemix plugin ibm-containers. (i checked both installations, seemed fine me.) logged bluemix (cf login -a ...). , run command: cf ic login. , got error message i've tried deploy sample java application bluemix before. worked ok, did not encounter network connection problems. don't understand cause of error. any ideas problem or how fix it? in advance. you need login using: ice login -k api_key -r registry-ice.ng.bluemix.net source: alaa youssef on developerworks

c# - Best design for long process in Web Service -

i have design question on how best approach process within existing dotnet2 web service have inherited. at high level process @ moment follows client user starts new request via web service call client/server app request , tasks created , saved database. new thread created begins processing request request id returned client (client polls using id). thread loads request detail , multiple tasks for each task requests xml via service (approx 2 sec wait) passes xml service processing (approx 3 sec wait) repeat until tasks complete marks request completed (client know finished) overall takes approximately 30 seconds request of 6 tasks. each task being performed sequentially inefficient. would better break out each task again on separate thread , when complete mark request completed? my reservation duplicating number of threads factor of 6-10 (number of tasks) , concerned on how impact on iis. estimate cut normal 30 second call down around 5 seconds if had eac

c++ - AfxMessageBox going on background -

in connection check showing modal dialog ensure connection. give people escape modal dialog want message box keep try connection or exit application. source code : void crobovibmainframe::opensystemsettingsdialog(int activetabindex /*= 0*/) { while (activetabindex >= 0) { m_settingsdialog = std::make_unique<settingsdialog>(this,activetabindex); m_settingsdialog->domodal(); activetabindex = getnotconnectedpsvcontrol(); if (afxmessagebox(polytec::text::tomessagestring(ids_psv_system_exit_window_msg), mb_yesno) == idno) { ::exitprocess(0); break; } } } but messagebox alway showing in background. want on front. wrong in code? please suggest. i able bring afxmessagebox front fix : cwnd::postmessage(wm_syskeydown); i not sure if way. fixed issues. can someone.

php - PHPExcel VLOOKUP not appearing -

i'm trying use phpexcel vlookup , sheet getting no formula appearing in cell. using formula, sum(), works fine. so i've programmatically created bunch of sheets. here's dummy sheet i'm testing: $newsheet = $objphpexcel->createsheet(); $lytabname = ($year-1).' wk '.$thisweeknum.' input data'; $newsheet->settitle($lytabname); $objphpexcel->setactivesheetindexbyname($lytabname); $objphpexcel->getactivesheet()->setcellvalue(a6,'00009'); $objphpexcel->getactivesheet()->setcellvalue(e6,'100'); if go first sheet: $objphpexcel->setactivesheetindex(0); then works: $objphpexcel->getactivesheet()->setcellvalue('d6', '=sum(\''.$lytabname.'\'!a6:a7)'); but doesn't, cell d6 on first sheet empty $objphpexcel->getactivesheet()->setcellvalue('d6', '=vlookup(a6,\''.$lytabname.'\'!a6:a7,5,false)'); i want formula in cell because wan

javascript - Use .bind method for down arrow key -

i enabled alert show whenever scrolled down mouse in <div> $('#divid').bind('mousewheel dommousescroll', function (event) { if (event.originalevent.wheeldelta < 0 || event.originalevent.detail > 0) { alert('scroll down scroll'); } }); what equivalent .bind method can use alert whenever scrolled down down arrow key in <div> my attempt (but doesn't work): $('#section1').bind('onkeydown', function (event) { if (event.keycode == 40) { alert('scroll down arrow key'); } }); i'd highly appreciate help. i've checked out solution from: javascript keycode values "undefined" in internet explorer 8 - this, can't seem have alert happen specific <div> , don't want effect lingering throughout whole document. i using .bind() , not other method, it's because when <div> want .unbind() previous, because in <div> want new .bind()

excel vba - remove any combinations of characters from vba string -

i have string value of ;00330508911=010403954? in excel vba remove characters except second set of digits, being 010402600. have tried many other alternatives no luck, appreciated. assuming question 'how strip out number between equals sign , question mark', it's basic string manipulation: public function secondnumber(inputstr string) string 'text after equals sign = mid(inputstr, instr(1, inputstr, "=") + 1, 100) 'and before question mark b = mid(a, 1, instr(1, a, "?") - 1) secondnumber = b end function

html - How to put radio button with a php value -

Image
i having trouble using radio button, i'm getting confuse because of output of codes. in left picture that's output like, in right picture want output that. when choose candidates both radio button can choose instead of 1 should can chosen. here's code: <?php $yearnow=date('y'); $dsds=$rowasa['posid']; $results = $db->prepare("select * candidates,student,school_year,partylist student.idno = candidates.idno , school_year.syearid = candidates.syearid , posid =:a , candidates.partyid = partylist.partyid , school_year.from_year $yearnow "); $results->bindparam(':a', $dsds); $results->execute(); for($i=0; $rows = $results->fetch(); $i++){ ?> //here's part confuse <input type ="radio"><input style="padding: 35px 50px 35px 80px; background:url('admin/candidates/images/<?php echo $rows['image'

android - Ionic - $state.go works on livereload but not on device -

i experiencing weird issue following. on livereload or on browser, state.go function works expected. when run app on device (without livereload), app not apply transition new state. this how call function: <ion-nav-buttons side="right"><a class="button button-clear navbuttons" ng-click="setselectedforedit(selectedchannel)">dÃœzenle</a></ion-nav-buttons> and controller: .controller('channelctrl', function($scope, $rootscope, $stateparams, $state, firebasedataservice) { $scope.setselectedforedit = function(channeluniqueid) { $state.go('app.channel-edit', {'channelid':channeluniqueid}); }; }) and route following: .state('app.channel-edit', { url: '/channels/:channelid/edit', views: { 'menucontent': { templateurl: 'templates/channeledit.html', controller: 'channeleditctrl'

How can I import MySQL database in neo4j on Windows? -

i continuously looking decent tutorial importing mysql database in neo4j didn't find applicable. using neo4j version 3.0.3 , mysql version 8.2. you can me tutorial or tool can dump mysql database directly neo4j, both of them should target windows os. thank you. h, michael has made such tool, have never used it. take @ repo : https://github.com/jexp/neo4j-rdbms-import usually make sql queries , save them csv file (@see how output mysql query results in csv format? ). after load them neo4j load csv (@see http://jexp.de/blog/2014/06/load-csv-into-neo4j-quickly-and-successfully/ ) cheers

Code metrics in TFS 2015 Build -

Image
do have option display code metrics details in tfs 2015 on-prem build? couldn't find option include values part of build. ideally display values below code coverage section (as show in pic). something similar this: https://blogs.msdn.microsoft.com/jamiedalton/2014/06/12/visual-studio-2013-code-metrics-and-tfs-builds/ http://www.dotnetcurry.com/visualstudio/1230/build-customization-code-metrics-utility-visual-studio-2015 in team foundation server 2015 update 2 or later, goal can achieved. can write own tfs extensions enable integration @ ui layer – surfacing relevant information in right places. check overview of extensions tfs/vsts: https://www.visualstudio.com/en-us/docs/integrate/extensions/overview good resources start using extension: https://github.com/robertk66/vsts-opencover https://github.com/microsoft/vsts-extension-samples

jquery - How can i change image after get data from database -

for function getdatafromdb() newest data database , want use val["id"] to define condition change image see on function getimage it's not success. can give me example ? <script> function getdatafromdb() { $.ajax({ url: "getdata.php" , type: "post", data: '' }) .success(function(result) { var obj = jquery.parsejson(result); if(obj != '') { //$("#mytable tbody tr:not(:first-child)").remove(); $("#mybody").empty(); $.each(obj, function(key, val) { var tr = "<tr>"; tr = tr + "<td>" + val["id"] + "</td>"; tr = tr + "<td>"

angular - Ionic 2 Cordova network information plugin reference error -

i've installed network information plugin per tutorial ionic 2 app: ionic 2 | how work cordova plugins however typescript won't compile because can't find reference "connection" in states array lines. idea how write import statement per platform, page etc? my class: import {navcontroller, navparams} 'ionic-framework/ionic'; import {page, viewcontroller, platform, alert, modal, events} 'ionic-framework/ionic'; import {forwardref} 'angular2/core'; import {oninit} 'angular2/core'; import {injectable} 'angular2/core'; import {todosservice} '../../services/todosservice'; import {mytodositem} '../../pages/my-todos-item/my-todos-item'; @page({ templateurl: 'build/pages/my-todos/my-todos.html' }) class todaypage { constructor( private platform: platform, private nav: navcontroller, private _events: events, private _todosservice: todosservice) { this._platform = platform

reverse of a number php error -

this question has answer here: reference - error mean in php? 30 answers <?php $revs=0; $no=123; while($no!=0) { $revs = $revs*10; $revs = $revs +( $revs%10); $no = ($no/10); } echo revs; ?> the code written above doesn't work shows following error "notice: use of undefined constant revs - assumed 'revs' in /opt/lampp/htdocs/testprojct/proj.php on line 26 you forgot $ in front of revs echo it.

css - HTML Text Appears Over Image On Hover -

i have been struggling while trying images animate when hover on them. have found lots of examples, have found them difficult implement , adjust how want them. here code: #box { width: 100%; border-radius: 5px; box-shadow: inset 1px 1px 40px 0 rgba(0, 0, 0, .45); background: url("http://placehold.it/1080x720"); background-size: cover; } #cover { background: rgba(0, 0, 0, .75); text-align: center; opacity: 0; -webkit-transition: opacity 1s ease; -moz-transition: opacity 1s ease; } #box:hover #cover { opacity: 1; } #text { font-family: arial; font-weight: bold; color: rgba(255, 255, 255, .84); font-size: 60px; } <div id="box"> <div id="cover"> <span id="text">comics</span> </div> </div> my difficulty comes when setting height, website needs able re-size image; before set width of image (rather background ima

github - Git: move local project into other repo, keeping history -

i need somehow move existing maven project under version control git, inside git repo project resides. why? in past few weeks, worked on project on own. use git locally (there no remote repository!) track changes. basic structure on side this: myrepo |--.git |--myproject |--.gitignore where myproject maven project. meanwhile, colleague of mine created repo himself, maven, project in it. repo remote, on github. structure looks this: commonrepo |--.git |--hisproject |--.gitignore |--pom.xml |--.project |--.settings so can see, idea there parent pom in repo specifies modules. hispoject 1 of these modules. i want move myproject there, maven module. don't want lose commit history in process. want final structure like: commonrepo |--.git |--hisproject |--myproject |--.gitignore |--pom.xml |--.project |--.settings i found approaches move 1 directory repo, seems none of these fit problem. looks solutions require myrepo have remote

java - Elements of a split string array can't be used as function inputs? -

here code: // bug - works. string[] lst = {"desk", "pencil"}; string lst0 = lst[0]; system.out.println("path: " + lst[0]); system.out.println("result: " + root.getdirectory(lst0).getfilename()); // bug - doesn't work. string[] ef = "desk/pencil".split("/"); string ef1 = ef[0]; system.out.println("path: " + ef1); system.out.println("result (without getfilename): " + root.getdirectory(ef1)); but in second case, function isn't called properly, ef[0] seems considered differently lst[0] compiler despite both being strings. assume becaue lst array resulted list splitting. there way fix/work around this?

osx - Get correct NSRect in NSTextView when image insert -

i use [nstextview firstrectforcharacterrange:actualrange:] , [nslayoutmanager boundingrectforglyphrange:intextcontainer:] cursor rect, works right when pure text in nstextview. but when insert image text view, [nstextview firstrectforcharacterrange:actualrange:] return wrong result(nsrectzero), , [nslayoutmanager boundingrectforglyphrange:intextcontainer:] return right value in textview convert superview wrong. only when image bigger textview bounds happen. anyone knows how resolve that?

ios - UIView center property is giving unexpected result -

Image
i trying design screen programmatically. first, setup navigation bar. after add table view , after add plain uiview . having trouble while using .center property of last added uiview . want add uiactivityindicatorview view. code follows (using default height , width of large white activity indicator, 37pt each): func setupactivityview() { let screen = uiscreen.mainscreen().bounds let view = uiview(frame: cgrectmake(0.0, self.navbar.frame.height, screen.width, uiscreen.mainscreen().bounds.height-self.navbar.frame.height)) view.backgroundcolor = uicolor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.80) //view.hidden = true self.activityview = view self.view.addsubview(view) let spinner = uiactivityindicatorview(activityindicatorstyle: .whitelarge) spinner.startanimating() spinner.hideswhenstopped = true self.spinner = spinner /*point:1*/ //spinner.center = view.center /*point:2*/ //spinner.frame.size = cgsizemake(37.0, 37.0) /*poin

html - Firefox throwing error while reading #hex color codes inside inline SVG -

this doesn't happen on chrome, happen on ff , ms edge, @ least. in ff, when try paint svg inside of css url() or object tag, if svg contains #hex color #ff0000 , crash. let me show example: <p>not using # colors</p> <object type="image/svg+xml" data="data:image/svg+xml;charset=utf-8,<?xml version='1.0' encoding='utf-8'?><svg version='1.2' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='70px' height='70px' viewbox='0 0 100 100' xml:space='preserve'><circle fill='red' cx='50' cy='54.7' r='15.72'/></svg>"> no svg utf8 </object> <p>using #hex colors (won't show on ff)</p> <object type="image/svg+xml" data="data:image/svg+xml;charset=utf-8,<?xml version='1.0' encoding='utf-8'?&

ruby on rails - Check Select year parameter -

i have select year wanna check if year matches: <%= select_year(date.today, {start_year: 2015, end_year: date.today.year} %> the default name date[year] , wanna compare value in query like: where("year(date) = ?", x) where x year, can't work. i'm passing controller like: @result = model.function(params[:date][:year]) but keep getting "undefined method `[]' nil:nilclass" though see passing "parameters: {"utf8"=>"✓", "date"=>{"year"=>"2015"}}"

database - Do web applications create a new table for each users data? -

sorry in advance if silly question, new web-application design. in web-apps users able create , manage own data, how database/back-end implementation work? e.g. in web-application: user able create list of tasks , time complete them by. should end creating new table *each user'*s tasks? i ask surely data different users should seperated each one? you can have table, containing tasks when user creates new task/list of tasks or whatever call them new entry added table

java - Giving Position to values in an ArrayList -

i'm working on assigning positions values in arraylist in java. for example arraylist containing {5,6,3,1,9,10,0,2,6} . how can correctly assign positions numbers have {5th,3rd,7th 2nd,1st,8th, 6th,3rd} . i have sorted arraylist containing numbers in java. am stuck @ giving position numbers. so work? public static arraylist<string> getpositions(arraylist<integer> list) { arraylist<string> positions = new arraylist<string>(); string[] endings = { "th", "st", "nd", "rd" }; integer last = 100; integer lastrank = 1; (int index = 0; index < list.size(); index++) { int position = index + 1; if (last == list.get(index)) { position = lastrank; } int remainder = position % 10; string rank = position + ""; string ending = endings[0]; if (remainder <= 3) { if ((position % 100) - remainder

javascript - How to structure a Node Js blog with marked md parser -

currently working on creating simple blog engine using nodejs / express4. want publish blog posts using markdown language. i have found marked: https://github.com/chjj/marked , perfect need, , have created real basic solution grab data md file , display in client. the issue having fitting solution correct mvc structure of nodejs application. here have produced, works 1 md file - in index.js: app.get('/test', function(req, res) { var path = __dirname + '/node_modules/marked/doc/todo.md'; var file = fs.readfilesync(path, 'utf8'); res.send(marked(file.tostring())); }); i have found solution recursively scan particular directory blog posts (in md) using walk: var walker = walk.walk('./node_modules/marked/doc', { followlinks: false }); walker.on('file', function(root, stat, next) { console.log(root + '/' + stat.name); next(); }); how can concatenate multiple md posts 1 html response in correct manor - other page req

ios - Parse to Heroku migration (MongoLab): PFRelation issue -

Image
i succeeded migrate parse parse-server mongolab. works expected, except when i'm logging pfuser mongolab, pfrelation object null. in appdelegate, when run code (official parse): [parse setapplicationid:@"xxxxxx" clientkey:@"xxxxxx"]; [pfuser enablerevocablesessioninbackground]; homeview.m: self.currentuser = [pfuser currentuser]; self.friendsrelation = [[pfuser currentuser] objectforkey:@"friends"]; nslog(@"%@", self.currentuser); nslog(@"%@", self.friendsrelation); after login, homeview log this: 2016-02-28 23:25:38.756 chilln[4131:57119] <pfuser: 0x7fe0b3e4fc10, objectid: mzdphaqbyr, localid: (null)> { friends = "<pfrelation: 0x7fe0b3e4f900, 0x7fe0b3e4fc10.friends -> _user>"; phone = "06 19 05 39 30"; surname = a; username = a; } 2016-02-28 23:25:38.756 chilln[4131:57119] <pfrelation: 0x7fe0b3e4f900, 0x7fe0b3e4fc10.friends -> _user> so ever

TFS 2012 upgrade to TFS 2015: Database sync from TFS2012 to TFS 2015 -

i upgrading tfs 2012 tfs 2015 in new hardware new configuration. stratagy copy db , upgrade them , after sometime switch on new tfs 2015. there time between actual switchover of tfs 2012 2015, (in case days). approach taken because cannot have production downtime of tfs. now time (days) taken, there lot of new data inserted in old tfs 2012 database. how migrate new additional data new tfs 2015. i having question because tfs 2015 versus tfs 2012 there table changes, taken care tfs upgrade. if want insert tfs2012 data tfs 2015 there issues? or there better approach upgrade? you should test migration understand how long upgrade take. once have information need take tfs offline upgrade. quick process can done in evening or weekend. the idea can't take server offline regular maintenance faulty 1 , unachievable. you can't insert data database ss break tfs. syncing data after fact prove difficult , time consuming.

text files - save data in android application even after app is closed without using SharedPreferences? -

this question has answer here: how save data in android app 8 answers hi guys wanted save data in android application dont want use shared preferences concept. can save data on text file in phone , perform read/write operations on evertime open app example update hall of fame everytime when game over? there's list of available options in officional developer guide: https://developer.android.com/guide/topics/data/data-storage.html the following options explained there: store data using shared preferences save data files on internal or external storage store data in sqlite databases store data on web

c - Enum data type memory allocation -

this question has answer here: what size of enum in c? 6 answers how enum allocate memory on c? 3 answers how memory allocated for"enum" data type, found total size of enum data type 4 bytes(linux) people answers there no memory allocation, 'macros' type(int) please explain how enum members function stored while accessing , data there in 4 bytes. thanks the memory shall not allocated enums . remember memory allocation , processing time (preprocessor time , compilation time) main difference between macro , enum. for example, while doing debugging(runtime) not able see value of macro,since memory not allocated macro , not able access memory location. know value of macro, have file defined. but enums, memory shall allocated. able access memo

Python: How to solve the issue : 'badly formed hexadecimal UUID string' in Django -

i have created 'post' model in included 'post_id' primary key field. when trying create post, raising error: 'badly formed hexadecimal uuid string'. appreciate helping me in solve this. here's code. models.py: class post(models.model): post_id = models.uuidfield(primary_key=true, default='uuid.uuid4', editable=false) user = models.foreignkey(settings.auth_user_model, default=1) from1 = models.charfield(max_length=20) = models.charfield(max_length=20) timestamp = models.datetimefield(auto_now=false, auto_now_add=true) objects = postmanager() def __unicode__(self): return self.post_id def __str__(self): return self.post_id def get_absolute_url(self): return reverse("posts:detail", kwargs={"post_id": self.post_id}) class meta: ordering = ["-timestamp", "-time"] views.py: def post_create(request): form = postform(reques

sql - Mapping rows to columns in different tables -

i stumped how elegantly map data rows columns in other tables. input table form_submission table - id = form identifier entry_id = question identifier response = response id entry_id response 4 24 john 4 25 doe 4 26 male 4 32 ny 4 30 life-threatening 4 30 other serious 4 30 hospitalization 4 28 tylenol 4 31 have headache. i need map couple tables patient_info , patient_outcome output tables patient_info report_id first_name last_name state gender complaint 4 john doe ny male have headache. patient_outcome report_id other_serious_ind life_threat_ind hospital_ind disability_ind 4 y y y n so there no direct way link rows columns, possible create mapping based on entry_id , column name? though know ind columns based on rows entry_id = 30.

php - Creating New Forms in Laravel 5 and Submitting Them -

i wish clarify steps new form submitted database using laravel 5.2 , bootstrap 3. i have login/register pages set using laravel's defaults, , work fine. want create user profile page accessible authenticated users. using 1 row in database of user info. fields filled in during registration, , want them have access additional fields (while restricting access registration fields user name). in example code below, there fields upload personal photo, enter first name, , enter last name. (none of these done during registration.) what have done (all code below): create view profile.blade.php create controller profilecontroller.php update routes.php in controller directory. a note: when try submit form appears below, get, type error: argument 1 passed app\http\controllers\profilecontroller::update() must of type array, none given. what next steps required page working properly? profile.blade.php: @extends('layouts.app') @section('content') <

sitecore7.2 - Ordering Sitecore search results -

i have iqueryable<t> object search results object. apply filtering , sorting on search object. before call getresults() , want order results based on 1 of field's (fieldname - priority ) value. items in iqueryable<t> object, want order them desc priority field, items has value field stay @ top , rest @ bottom. i have fieldmap entry priority field. search.orderbydescending(i => !string.isnullorempty(i.getitem().getfieldvalue("priority"))) the above command doesn't work. apparently, can't use sitecore extension methods iqueryable? if convert search.tolist() . ordering , convert asqueryable() , following error: there no method 'getresults' on type 'sitecore.contentsearch.linq.queryableextensions' matches specified arguments is there neat , quick way around this? cheers i think need add field searchresultitem , mark int. making assumption field int. make custom class inherits searchresultitem. public cl

osx - Android tablet freezes on connecting to Mac - OS X -

i have bit specific problem. developing android app tablets , 1 device got hands freezes every time connect mac , running adb. works, when don't have running adb. when try connect receive error macbook-pro-2:~ user$ adb devices list of devices attached * daemon not running. starting on port 5037 * adb e 65548 3480511 usb_osx.cpp:302] not clear pipe stall both ends: e0004051 adb e 65548 3480511 usb_osx.cpp:284] not find device interface * daemon started * this freezes. it doesn't happen on other devices. device chinese 1 , our firm use kiosk. has ethernet port , many more. when connect through wifi debugging works, curious, might problem. it's somehow improved allwinner a20. in android studio shows me name unknown softwinerevb. and 1 more thing. works on windows. if have clue, might problem, appreciated. thanks. a hard reboot (power off/on) hardware did trick me. or, toggling developer options works.

retrofit2 - Can I use a Custom Method Annotations in Retrofit 2.0? -

in retrofit 2.0 i know it's possible handler custom param annotations in converter.factory . but can handler custom method annotations customannotation in below: @customannotation @post("someurl") observable<myresponse> dosomething(@body body); i found way use proxy wrap service create retrofit: retrofit retrofit = new retrofit.builder() .baseurl("https://example.com/") .build(); apiservice rawservice = retrofit.create(apiservice.class); apiservice service = (apiservice) proxy.newproxyinstance(rawservice.getclass().getclassloader(), rawservice.getclass().getinterfaces(), new invocationhandler() { @override public object invoke(object proxy, method method, object[] args) throws throwable { if (method.getannotation(customannotation.class) != null){ //handler annotations }

python - django filter queryset based on __str__ of model -

i have following model: class subspecies(models.model): species = models.foreignkey(species) subspecies = models.charfield(max_length=100) def __str__(self): return self.species.species_english+" "+self.species.species+" "+self.subspecies def __unicode__(self): return self.species.species_english+" "+self.species.species+" "+self.subspecies notice foreignkey field, species used in __str__ , __unicode__ methods. had made filter query: l = list(subspecies.objects.filter(subspecies__contains=request.get.get('term')).order_by('subspecies')[:10]) this want, except not quite. want filter checks if __str__ representation of object contains group of characters, instead of checking subspecies field. instead of subspecies__contains=... __str____contains=... of course doesn't work. is possible? if how make query? thanks! filter generates query executed in db. __str__

c - Determined the PRIME numbers -

is 1 & 0 prime numbers ? because when input 1 & 0 says prime #include <stdio.h> int main(){ int num, i,y = 0; printf("enter number: "); scanf("%d",&num); for(i = 2; <= num /2; ++i){ if(num % == 0){ y=1; } } printf("the number %d ",num); if (y == 0){ printf("(prime)"); } if(num % 2 == 0){ printf("(even)"); }else printf("(odd)"); printf(" number."); } can me code no, neither 0 nor 1 considered prime numbers, is, lowest prime number 2. need change code into, instance: if (y == 0 && n >= 2) this covers both 0 , 1 along negative integers (thanks @mikecat)

date - Generate year from %tc variable in Stata -

how can generate year stata variable format 09sep1943 00:00:00 , it's stored %tc component? this amply documented. see help datetime , use yofd(dofc() . . clear . set obs 1 number of observations (_n) 0, 1 . gen double datetime = clock("09sep1943 00:00:00", "dmy hms") . format datetime %tc . gen year = yofd(dofc(datetime)) . l +---------------------------+ | datetime year | |---------------------------| 1. | 09sep1943 00:00:00 1943 | +---------------------------+

python - Reading from file into dictionaries, and strange eval() behaviour -

creating dictionaries file using eval() , or ast.literal_eval() (as suggested others) yields strange results, , i'm not sure why. my file, file.txt contains this: {0 : {1: 6, 1:8}, 1 : {1:11}, 2 : {3: 9}, 3 : {},4 : {5:3},5 : {2: 7, 3:4}} i read dictionary , print contents out such graph1 = {} graph1 = ast.literal_eval(open("file.txt").read()) and thing, {1:6} missing. {0: {1: 8}, 1: {1: 11}, 2: {3: 9}, 3: {}, 4: {5: 3}, 5: {2: 7, 3: 4}} i change contents of 'file.txt' this: {0: {2: 7, 3: 4}, 1: {1: 11}, 2: {3: 9}, 3: {}, 4: {5: 3}, 5: {2: 7, 3: 4}} and correct contents display! then change contents of file.txt this, rewrite 1:6 2:6 {0 : {2: 6, 1:8}, 1 : {1:11}, 2 : {3: 9}, 3 : {},4 : {5:3},5 : {2: 7, 3:4}} and output, {2:6} , {1:8} switch places! {0: {1: 8, 2: 6}, 1: {1: 11}, 2: {3: 9}, 3: {}, 4: {5: 3}, 5: {2: 7, 3: 4}} all want correctly read contents of file dictionary. going wrong? dictionaries can not have dup

php - Get json data from file at random locations -

i trying upload files json data php server @ web-hotel, on serverside php not able locate file i`m sending up. have tried this require_once 'db.php'; $jsondata = file_get_contents("movies.json"); $json = json_decode($jsondata,true); echo $json['movies'][0]['title']; $output ="<ul>"; foreach($json['movies'] $movie){ $output .="<h4>".$movie['title']."</h4>"; $output .="<li> year".$movie['year']."</li>"; $output .="<li> genre".$movie['genre']."</li>"; $output .="<li> director" .$movie['director']."</li>"; } $output .="</ul>"; echo $output; ?> which works fine if have file called "movies.json" in same directory php code, problem is, send file different raspberry pi´s,

sas - Sections and subsections in the same column with an ID, how to change structure -

i have dataset has sections , subsections in same column identified id, , need have in different structure divided in columns generate report. if don’t, proc report generate duplicate information. tried retain option keep last subsection of each 1 result wasn't expected. here dataset have , dataset want , report want have: data have; infile datalines delimiter=',' dsd; input id $ concept : $15. amount 15.; datalines; 1,store1,85.5 1.1,vend1,43 1.1.1,income,25 1.1.1.1,income 1,10 1.1.1.2,income 2,5 1.1.1.3,income 3,10 1.1.2,sales,18 1.1.2.1,sales 1,12 1.1.2.2,sales 2,6 1.2,vend2,42.5 1.2.1,income,2.5 1.2.1.1,comission 1,2.5 1.2.2,sales,40 1.2.2.1,sale 1,15 1.2.2.2,sale 2,15 1.2.2.3,sale 3,10 2,store 2,75.6 2.1,vend 1,18.3 2.1.1,income,15 2.1.1.1,income 1,7 2.1.1.2,income 2,8 2.1.2,sales,3.3 2.1.2.1,sales 1,3.3 2.2,vend 2,57.3 2.2.1,income,7.3 2.2.1.1,comission 1,5 2.2.1.2,comission 2,2.3 2.2.2,sales,0 2.2.3,others,50 ; run; want: data want; infile datalines d

smtplib - Python - sending an email through gmail servers -

when type following code idle works fine: >>> import smtplib >>> smtpobj = smtplib.smtp('smtp.gmail.com', 587) >>> smtpobj.ehlo() >>> smtpobj.starttls() >>> smtpobj.login("email", "password") >>> smtpobj.sendmail("email", "email2", "subject: test \nsent python!") >>> smtpobj.quit() but when try make program out of make easier emailing gives me syntax error (error 2 * on each side of it): import smtplib smtpobj = smtplib.smtp('smtp.gmail.com', 587) smtpobj.ehlo() smtpobj.starttls() email = input("what email?: ") password = input("what password?: ") **smtpobj**.login(email, password) print ("from: " + email) = input("to: ") subject = input("subject: ") message = input("message: \n") smtpobj.sendmail(email, to, subject + message) print ("email sent successfuly!!!") smtpobj.qui

python - Matplotlib.pyplot.hist() very slow -

i'm plotting 10,000 items in array. of around 1,000 unique values. the plotting has been running half hour now. made sure rest of code works. is slow? first time plotting histograms pyplot. to plot histograms using matplotlib need pass histtype='step' argument pyplot.hist . example: plt.hist(np.random.exponential(size=1000000,bins=10000)) plt.show() takes ~15 seconds draw , 5-10 seconds update when pan or zoom. in contrast, plotting histtype='step' : plt.hist(np.random.exponential(size=1000000),bins=10000,histtype='step') plt.show() plots , can panned , zoomed no delay.

mapreduce - hadoop - how would input splits form if a file has only one record and the size of file is more than block size? -

example explain question - i have file of size 500mb (input.csv) the file contains 1 line (record) in it so how file stored in hdfs blocks , how input splits computed ? you have check link: how hadoop process records split across block boundaries? pay attention 'remote read' mentioned. the single record mentioned in question stored across many blocks. if use textinputformat read, mapper have perform remote-reads across blocks process record.

git - Difference between master and gcloud branch -

after pushing local code using git google app engine. master branch update. gcloud branch still has old version. how merge branches? please use following command: git rebase master gcloud

node.js - How to use the istanbul API to load config from grunt -

i trying steer istanbul grunt without resorting .istanbul.yml file. idea run grunt-jasmine-nodejs unit testing , integrate istanbul custom reporter: module.exports = function(grunt) { grunt.initconfig({ jasmine_nodejs: { options: { specnamesuffix: 'spec.js', usehelpers: false, reporters: { console: {} }, customreporters: [ require('./tests/lib/istanbul-reporter.js')({ coveragevar: '__coverage__', dir: './tests/coverage' reports: ['text','json','html'] }) ] }, default: { specs: [ 'tests/unit/**' ] } } }); grunt.loadnpmtasks('grunt-jasmine-nodejs'); }; the jasmine reporter notifies sandboxed-module should instrument tested files. istanbul api doc gives idea loads configuration .loadfile() : module.exports = function (opt) { var istanbul = re