Posts

Showing posts from August, 2014

Android String.format() Returns Question Mark (??) [FIXED] -

i have app downloads files internet. source file name dynamically generated depending on user selection. use following method create source file name. note fileid integer (1-99). final string filename = "file_" + string.format("%02d", fileid) + "_download.jpg"; the issue have seen users unable download files (and of course leave 1 start ratings :( ). when check server log see download requests came file names file_??_download.jpg . looks string.format() has returned ?? instead of 2 digit number. i searched everywhere , not find solution this. can tell me what's wrong code? not re-produce error on of devices. thanks! you have instead: final string filename = "file_" + string.format("%d", fileid) + "_download.jpg"; or final string filename = "file_" + fileid + "_download.jpg"; if want 2 last digits, it: int formattedfileid = fileid % 100; final string filename = "fil...

c - How to properly parse numbers in an arithmetic expression, differentiating positive and negative ones? -

i have assignment in data structures class in have program calculator solves arithmetic expressions 4 basic operations , parenthesis, input done via stdin buffer , same output. it easy @ beginning, teacher provided algorithms (how transform expression infix postfix , how evaluate it) , goal implement our own stack , use it, calculator not work quite well, , think because of parser. this algorithm , , code, used parse numbers, operators , parenthesis while putting them array store expression in way easier evaluate later. // saida array of pairs of integers, first value of pair value of info (the number or ascii value of operator) // second value indicator of whether number or operator (i = 0; < exp_size; i++) { c = expression[i]; // if current char digit, store helper string , keep going until non-digit found // atoi() used transform string int , store it. if (c >= '0' && c <= '9') { j = 1, k = i+1; tempint[0] =...

python - Preserving order of occurrence with size() function -

Image
i preserve order of dataframe when using .size() function. first dataframe created choosing subset of larger one: df_south = df[df['region_name'] == 'south'] here example of dataframe looks like: with dataframe count occurrences of each unique 'tempbin_cons' variable. south_count = df_south.groupby('tempbin_cons').size() i maintain order exists using sort column. created column based on order 'tempbin_cons' variable appear after counting. can't seem appear in proper order though. i've tried using .sort_index() on south_count , not change order groupby() creates. ultimately solution fixing axis ordering of bar plot creating of south_count. ordering difficult read , appear in logical order. for reference south_count, , subsequently axis of bar plot appears in order: try this: south_count = df_south.groupby('tempbin_cons', sort=false ).size() looks though data sorted string.

laravel - Edit active database on the fly -

so i'm working on little web application in can manage database. now can use following function retrieve databases db::select('show databases') but want able tables each of databases , more databases, figured if working wouldn't problem. normally you'd have different database in config, since want application work "any" database , make sure don't have manually add databases etc since that's kind of work want web app done me. i've tried tricking around bit without success example. db:select('use dbname; show tables'); db::select('select dbname(); show tables'); obviously didn't work, there "proper" solution this? thought editing .env variable on fly might've been option, can't seem find "legit" way either. you don't need this. i thought editing .env variable on fly might've been option, can't seem find "legit" way either. what need this ...

jboss - create ActiveMQ MQTT broker to connect to Moquitto broker -

i want use activemq create broker connect mosquitto broker. , then, can use activemq receive message mosquitto broker. what done is: integrate activemq jboss eap 6.3. create mqtt broker in activemq: http://activemq.apache.org/mqtt.html but after add networkconnector in broker-config.xml: <transportconnectors> <transportconnector name="openwire" uri="tcp://localhost:61616"/> <transportconnector name="mqtt" uri="mqtt://localhost:1883"/> </transportconnectors> <networkconnectors> <networkconnector uri="static:(tcp://mosquitto_server_ip:1883)"/> </networkconnectors> the server shows exception after starting: "network connection between vm://localhost#8 , tcp:///mosquitto_server_ip:1883@42688 shutdown due remote error: java.util.concurrent.timeoutexception" i try use "mqtt://..." connect, it's still failed: java.lang.illegalargumentexc...

regex - Is it possible to mark the n-th occurrence of a pattern with n in vim? -

say have text following. the man walking, , man eating. how should use substitution convert following? the man 1 walking, , man 2 eating. i know can use :%s/\<man\>//gn count number of occurrences of word man , know /\%(\(pattern\).\{-}\)\{n - 1}\zs\1 can find n-th occurrence of pattern. how mark n-th occurrence? any sincerely appreciated; in advance. you'll need have non-pure function counts occurrences, , use result of function. " untested let s:count = 0 function! count() let s:count += 1 return s:count endfunction :%s/man\zs/\=' '.count()/

android - Logical concurrency issue with Picasso in custom View -

i creating custom view displays image bitmap loaded picasso framework. initialize need both bitmap , view measure. struggling threading cannot predict thread finish earlier. the view starts picasso custom target in constructor. saves view's width , size in onsizechanged . public class figureview extends view { public figureview(context context) { super(context); target = new loadpicturetarget(); picasso.with(getcontext()).load(r.drawable.amalka).into(target); } protected void onsizechanged(int w, int h, int oldw, int oldh) { super.onsizechanged(w, h, oldw, oldh); tilesrect.set(0, 0, w, h); } and target sets bitmap , computes resized picture dimensions fit view's available space: class loadpicturetarget implements target { public void onbitmaploaded(bitmap bitmap, picasso.loadedfrom from) { basebitmap = bitmap; origpicturerect = new rect(0, 0, basebitmap.getwidth(), basebitmap.getheight()); scaledpicturerect = misc...

How to sort nested MongoDB collection using PHP -

[ { "trip": [ { "destination": "tokyo", "time": 8.56, "price": 80 }, { "destination": "paris", "time": 2.36, "price": 9 }, { "destination": "goa", "time": 4.56, "price": 30 } ] }, { "trip": [ { "destination": "tokyo", "time": 6.26, "price": 23 }, { "destination": "paris", "time": 7.46, "price": 45 }, { "destination": "goa", "time": 8.98...

How to Sort Nested Javascript Array -

i have array var a=[['test':'1','test1':'2','test2':{'test3':'3','test4':'4'}],['test':'2','test1':'2','test2':{'test3':'1','test4':'2'}]]; i can sort array using test , test 1 fields. have no idea sort using test3 or test4. how can array sorted. code [{"hotelid":18,"hotelname":"trader","hotelalias":"trader-hotel","hotelstreet":null,"address":"no.18","hoteldescription":"near shwedagone pagoda","hotellat":16.819910049438,"hotellng":96.130912780762,"cityid":33,"regionid":1,"breakfast":1,"lunch":0,"dinner":0,"snack":0,"wifi":1,"createdon":"2016-08-24 14:09:57","city":{"cityid":33,"cityname":"bah...

sql - Convert transitive closure table into adjacency list -

i have materialized transitive closures table called graph_tbl. code below i running oracle 11gr2. i want apologize providing incomplete data question. please see correct , more complete data below: my table create table "graph_tbl" ("parent_name" varchar2(80 char), "child_name" varchar2(80 char), "parent_id" varchar2(18 char), "child_id" varchar2(18 char), "relative_level" number(18,0) ); data: insert graph_tbl parent_name,child_name,parent_id,child_id,relative_level) values ('components','components','a044100000171bxaaq','a044100000171bxaaq',0); insert graph_tbl (parent_name,child_name,parent_id,child_id,relative_level) values ('processors','processors','a044100000171byaaq','a044100000171byaaq',0); insert graph_tbl (parent_name,child_name,parent_id,child_id,relative_level) values ('intel','intel','a044100000171bzaaq',...

c# - How to skip last 2 records and get all other records with linq? -

i have table called test : test: id, createdby, createddate now want list of test skip last 2 test . if have e.g. 10 test want 1 - 8 test , skip test 9 , 10 . this how trying that: var query = context.test.orderbydescending(t=>t.id).skip(2) // how take other records? in case: take(8) with take , skip can range want. e.g: var query = context.test.orderbydescending(t=>t.id); var allbutthelasttwoelements = query.take(query.count() - 2); safest way: var query = context.test.orderbydescending(t=>t.id).tolist(); var allbutthelasttwoelements = query.take(math.max(0,query.count() - 2)); or other way around (depending on requirements) var query = context.test.orderbyascending(t=>t.id).skip(2);

osx - Can not modify header cell of Table View -

Image
my cocoa app has view-based table view. the table displays week of calendar, each column day (say) sunday saturday. i highlight column corresponds "today" in way; ideally , give colored background textfield, rounded corners; this: (this trivial achieve in ios. on macos, cells etc. instead of views , layers, seems more complicated...) however, not able change header cell's text or background color. code below (swift 3) is executed, column headers displayed default colors : let columns = tableview.tablecolumns // (currentweek array of nsdate) (index, day) in currentweek.enumerated() { let column = columns[sundayindex + index] if shared.calendar.isdateintoday(day) { // these 2 lines executed, but... column.headercell.textcolor = nscolor.red // ...no effect column.headercell.backgroundcolor = nscolor.black // ...no effect } // works every row: column.headercell.stringvalue = formatter...

c# - What is the equivalent of [Serializable] in .NET Core ? (Conversion Projects) -

in many cases, when want convert current .net framework projects .net core equivalent, classes have serializable attribute . what should convert them in .net core ? (in time delete them !!!) edit consider code : using system; namespace dotliquid.exceptions { [serializable] // delete !!!!!!! public class filternotfoundexception : exception { public filternotfoundexception(string message, filternotfoundexception innerexception) : base(message, innerexception) { } public filternotfoundexception(string message, params string[] args) : base(string.format(message, args)) { } public filternotfoundexception(string message) : base(message) { } } } above code without [serializable] works in .net core without syntax problem. but want know when delete [serializable] what side effects ? what places should changed? when should use json.net (or ...) inst...

html - Highlight a row on Click not working. CSS precedence -

here's table in html file. have highlight row on click. <tbody> <!--display none--> <!--onclick--> <tr ng-repeat="case in lastten" ng-click="setselected(case.name)" ng-class="{selected: case.name === idselected}"> <td colspan="1">{{case.name}}</td> <td colspan="1">{{case.total}}</td> <td colspan="1">{{case.passed}}</td> <td colspan="1">{{case.failed}}</td> </tr> </tbody> css- initialtable class above table table.initialtable { table-layout: fixed; width: 100%; font-family: helvetica, arial, sans-serif; margin-top: 20px; margin-bottom: 20px; border-collapse: collapse; border-spacing: 0; } table.initialtable td, th { border: 1px solid transparent; height: 40px; transition: 0.3s; overflow: hidden; } table.initialtable th { font-weight: bold; text-align: center; vertical...

Python 3 - How to write specific row in same file csv? -

i want update fieldname called "done" in same file csv this structure of file csv: input: email done 1@gmail.com 2@gmail.com 3@gmail.com 4@gmail.com output: email done 1@gmail.com 1 2@gmail.com 1 3@gmail.com 1 4@gmail.com 1 what want like: import csv open(r'e:\test.csv','r', encoding='utf-8') f: reader = csv.dictreader(f,delimiter='|') row in reader: #do here# #then write "1" filename "done" f.close() how ? thank ! :) with simple change use simple pair of read , write files; read line, , write out addition. in [6]: open('test.csv','r') input: ...: open('test1.csv','w') output: ...: header=input.readline() ...: output.write(header) ...: line in input: ...: output.write('%s %8d\n'%(line.strip(),1)) in [7]: cat test1.csv...

c# - Filtering on Linq that contains Custom Type using ODataQueryOptions -

while implementing kendo grid in mvc perform server side operations, find myself in tricky situation, i.e., have filter, sort, paged data using linq. , information got in odataqueryoptions type. (not sure if necessary mention or not, sake of completeness, perform query operations through unitofwork pattern) so operation perform query copied below: public static list<t> gett(this irepositoryasync<t> repository, odataqueryoptions<t> options) { var query = repository.query().tracking(false).include(x => x.t2) .select(s => new { p1 = s.p1, p2 = s.p2, p3 = s.t2.p1 + "," + s.t2.p2 }) .select(s => new t1 { p1 = s.p1, p2 = s.p2, p3 = s.p3 }); if (options.skip != null) query = query.skip(options.skip.value); if (options.top != null) ...

vba - Access Get subfolder of shared folder meetings -

i have code below should let me retrieve meetings shared sub calendar, doesn't work. if try access main shared calendar works perfect, not sub calendars.. could point me right way? public sub getcalendardata(calendar_name string, sdate date, edate date, optional recuritem boolean = true) on error goto errorhandler dim ool outlook.application dim ons outlook.folder dim oappointments outlook.appointmentitem dim oappointmentitem outlook.appointmentitem dim strfilter string dim itemscal outlook.items dim olfolder outlook.folder dim fldcalendar outlook.folder dim icalendar integer dim nmsnamespace outlook.namespace dim objdummy outlook.mailitem dim objrecip outlook.recipient 'set objects set ool = createobject("outlook.application") set nmsnamespace = ool.getnamespace("mapi") set objdummy = ool.createitem(olmailitem) set objrecip = nmsnamespace.createrecipient("shared cale...

java - GSON different value for same key -

i using gson , retrofit android project automatically parse api needed me. however, realized api contains value in can boolean or object different types of data in api. for example ... { "media": false, }, { "media": { "mp4": "http://sample.com/something.mp4", "jpg": "http://sample.com/something.jpg", } }, ... how should gson model like? @serializedname("media") object images; nothing wrong using object parse. while using parsed data use instanceof check type data is. for ex: object instanceof boolean boolean. edit: create model class urls. : public class urls { @serializedname("mp4") private string mp4url; @serializedname("jpg") private string jpgurl; public string getmp4url() { return mp4url; } public string getjpgurl() { return jpgurl; } } now check if(parsedobject in...

server - Joomla Site was Slow -

i have project create elearning website using joomla , there videos , many images in site .i used hypervisor server specification processor : 1 core intel xeon e5640 , memory: 4 gb , when 50 user accessed site , loading page slow. recomendation server site? it won't server. unless have taken appropriate steps reduce images , videos reduced 70%, instantly speed things up check out following tiny jpg tiny png also google how reduce video size. look @ cdn (cross distribution network) serve content locally also sprite maps , optimization repeated elements buttons etc. use css replace things buttons.

how to draw points as textures/text on touch in opengl-es in android? -

Image
i want draw points on touch. each point loads textures/default text shown below.how start draw kind of stuff in opengl-es in android? to use texture point, can use these lines of code in fragment shader. lowp vec4 diffuse_color = texture2d(texture1, gl_pointcoord); gl_fragcolor = vec4(color.xyz, diffuse_color.x); make sure gl_pointsize in vertex shader large enough.

cypher - neo4j edit distance search -

i running neo4j 3.0.4 , want search on node property using edit distance of 1. searched documentation , couldn't find anything, closest found regex search. appreciated. you can use manual lucene index, e.g. via apoc procedure library. installation of library, see: https://github.com/neo4j-contrib/neo4j-apoc-procedures documentation: https://neo4j-contrib.github.io/neo4j-apoc-procedures/#_full_text_search call apoc.index.search("locations", "address.address:paris~") yield node addr match (addr)<-[:has_address]-(company:company) return company limit 50

java - ValidationHandler not called in metro -

i have sample project test schema validation in jaxws . use metro 2.3.1 , spring in server side. import javax.jws.webmethod; import javax.jws.webservice; import com.sun.xml.internal.ws.developer.schemavalidation; @schemavalidation(handler = myerrorhandler.class) @webservice public class testws { @webmethod public string firstmethod() { return "hi"; } } import org.xml.sax.saxparseexception; import org.xml.sax.saxexception; import com.sun.xml.internal.ws.developer.validationerrorhandler; public class myerrorhandler extends validationerrorhandler { public void warning(saxparseexception e) throws saxexception { system.out.println("warning"); } public void error(saxparseexception e) throws saxexception { system.out.println("error"); } public void fatalerror(saxparseexception e) throws saxexception { system.out.println("fatal"); } } then generate soa...

javascript - Fire event after searchbox user input -

ok want fire jquery event, after user types in search box. search box: <div class="input-group"> <input type="search" class="form-control ui-autocomplete-input searchfield-active ui-autocomplete-loading" placeholder="sök på dustin" name="filter.query" accesskey="s" autocomplete="off" id="searchbox"> <span class="input-group-btn"> <button type="search" name="search" id="searchtrigger" class="btn btn-default"> <span class="icon-search"></span> </button> </span> </div> after user types in searchbox fire jquery : $(".hidden").removeclass('hidden'); you can use onchange or onkeyup events call function <input type="search" class="form-control ui-autocomplete-input searchfield-active ui-autocomplete...

c# - How do I Inform user that an element does not exist in a table? -

i have details form, , know using try , catch way of validation here bad practice. how check see if custid exists , tell user entered not exist? apologies if silly question , it's obvious and..., i'm beginner. public void getdetails() { lblmessage.text = ""; if (txtcid.text == "") { lblmessage.text = "please enter customer id before obtaining details."; } else { command.connection.open(); command.connection = conn; command.commandtype = commandtype.storedprocedure; command.commandtext = "getcustomer"; sqlparameter param = new sqlparameter(); param.parametername = "@custid"; param.sqldbtype = sqldbtype.int; param.direction = parameterdirection.input; param.value = txtcid.text; command.parameters.add(param); adapter.selectcommand = command; adapter.fill(table); txtfname.t...

angular - Generic solution for disabling fields for non-authorized users -

i have project client side language angular 2. application has few pages , of them have different permissions. example, have employees page, books page, locations page, clocking page, etc. each of pages has canedit , canview permissions. logged in user may have canedit permission locations, may not have canedit permissions books page. i want make generic solution write on 1 place , work pages, don't want repeating code in pages. like: if user has canedit permissions current page, remove read-only attribute inputs, , if doesn't have canedit permissions, add read-only attribute. at moment there no roles in project i'm open suggestions. is possible done? the best solumtion can imagine create service status of canedit , canview of user. then, on html page, use : <button *ngif="userservice.canview">a button</button> to show/hide (in fact, make exist or not) elements want displayed

html - Font-awesome icons works only when puts a download link -

i'm having troubles getting icons font-awesome.css file, need use app without internet conexion, need these icons working in local server, when create new css file , linking on template shows rare characters chinesse letters. works fine when put line: <link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.0.1/css/font-awesome.css" rel="stylesheet"> what's wrong ?? i'm confused. download here: http://fontawesome.io/assets/font-awesome-4.6.3.zip copy css , fonts folder. then include css file. assuming working index.html <link href="css/font-awesome.min.css" rel="stylesheet">

how to Filter the Json data in ios objective c -

i have problem json parsing. json data , want display items matched restid . have tableview display different restaurant information , every restaurant have own comment cell comment restaurant. so,i filter json data. let each restaurant comment cell can own comment. this json: ( { comment = "very good"; food = chicken; name = tom; restid = 1; score = 4; }, { comment = nice; food = coffee; name = jack; restid = 3; score = 3; }, { comment = tasty; food = pizza; name = mary; restid = 17; score = 5; }, { comment = unlike; food = none; name = gigi; restid = 33; score = 1; }, { comment = delicious; food = juice; name = bruce; restid = 45; score = 5; } ) this code: can display data in tableview , same data in different restaurant comment cell. - (void)getcommentinfo:(id)sender { dispatch_async(dispatch_get_global_queue(dispatch_queue_priority...

python - pandas: pandas.DataFrame.describe returns information on only one column -

for kaggle dataset (rules prohibit me sharing data here, readily accessible here ), import pandas df_train = pandas.read_csv( "01 - data/act_train.csv.zip" ) df_train.describe() i get: >>> df_train.describe() outcome count 2.197291e+06 mean 4.439544e-01 std 4.968491e-01 min 0.000000e+00 25% 0.000000e+00 50% 0.000000e+00 75% 1.000000e+00 max 1.000000e+00 whereas same dataset df_train.columns gives me: >>> df_train.columns index(['people_id', 'activity_id', 'date', 'activity_category', 'char_1', 'char_2', 'char_3', 'char_4', 'char_5', 'char_6', 'char_7', 'char_8', 'char_9', 'char_10', 'outcome'], dtype='object') and df_train.dtypes gives me: >>> df_train.dtypes people_id object activity_id object date object activi...

ios - How to handle JSON returned from HTTP GET request - Swift? -

this code : let myurl = nsurl(string:"hostname/file.php"); let request = nsmutableurlrequest(url:myurl!); request.httpmethod = "get"; nsurlsession.sharedsession().datataskwithrequest(request, completionhandler: { (data:nsdata?, response:nsurlresponse?, error:nserror?) -> void in dispatch_async(dispatch_get_main_queue()) { if(error != nil) { //display alert message return } { let json = try nsjsonserialization.jsonobjectwithdata(data!, options: .mutablecontainers) as? nsdictionary if let parsejson = json { /* when app reach here , enter catch , out */ let userid = parsejson["id"] as? string print(userid) if(userid != nil) { nsuser...

java - How to iterate through all files in IntelliJ plugin project? -

i'm trying create intellij plugin iterates on files in project folder , parses .java files , makes changes in them. problem after reading documentation don't have clear idea how iterate files on whole project folder, think may use psi files not sure. know or has idea on how accomplish this? a possible way use allclassesgetter , this: processor<psiclass> processor = new processor<psiclass>() { @override public boolean process(psiclass psiclass) { // actual work here return true; } }; allclassesgetter.processjavaclasses( new plainprefixmatcher(""), project, globalsearchscope.projectscope(project), processor ); processjavaclasses() classes matching given prefix in given scope. using empty prefix , globalsearchscope.projectscope() , should able iterate classes declared in project, , process them in processor . note processor handles instances of psiclass , means won't have parse...

Ionic sortable list with options on drop place -

i wondering if there's can give me start following situation: have sortable list (standard ionic) need options on drop place. i'll try explain example. <ul> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> <li name="dropplace"> <span name="option1"></span> <span name="option2"></span> <span name="option3"></span> </li> <li>list item 4</li> </ul> depending on option user drops list item, actions needs happen. don't know how begin on following: - when dragging, create drop place options - link dragging list item 1 of options when hovering - action when dropping on 1 of options thanks in advance! greetings, leander i'm quite sure ionic not provide sortable widget out of box. can use this one , example, angularjs wrapper around jquery sortable widget. you'll able capture drop event , p...

Parallel writing from same DataFrame in Spark -

let's have dataframe in spark , need write results of 2 databases, 1 stores original data frame other stores modified version (e.g. drops columns). since both operations can take few moments, possible/advisable run these operations in parallel or cause problems because spark working on same object in parallel? import java.util.concurrent.executors import scala.concurrent._ implicit val ec = executioncontext.fromexecutor(executors.newfixedthreadpool(10)) def write1(){ //your save statement first dataframe } def write2(){ //your save statement second dataframe } def writealltables() { future{ write1()} future{ write2()} }

html - How to sort a complex list in Javascript? -

i'm stuck question while. have nested list, structure looks volume1 chapter4 chapter3 section3-6 section3-1 volume2... ... what want create sort function sort volume, chapter, , section. so, result may volume1 chapter1 section1-1 .... so got complex html, here whole html . i'm not sure how swap complex div i've tried element , put them array. var tosort = document.getelementbyid('volume5015').children; tosort = array.prototype.slice.call(tosort, 0); i made fiddle you. in code trimming whitespaces of text don't compared don't have if don't want. var $items = $("#to-sort").children(); var $resultlist = $("#list2"); sortmarkup($items, $resultlist); function sortmarkup($elements, $output) { $elements.sort(function(a, b) { var contenta = getpuretext(a).trim(); var contentb = getpuretext(b).trim(); var okay = contenta.touppercase().localecompare(contentb.tou...

c++ - OpenCV error using inverse -

i'm working sift implementation using visual c++. code throws error while taking inverse: /// load source image src = imread("c:/users/adithyaanirudhha/documents/visual studio 2015/projects/consoleapplication2/pa.jpg", 1); if (display_caption("original image") != 0) { return 0; } dst = src.clone(); width = src.size().width; height = src.size().height; size size(height,width); if (display_dst(delay_caption) != 0) { return 0; } cvtcolor(src, src, cv_rgb2gray); /// applying gaussian blur //for(int j=0;j<4;j++) //{ //resize(src, src, size / 2); k = 2 ^ (1 / 2); for(int i=0;i<3;i++) { //if (display_caption("gaussian blur") != 0) { return 0; } gaussianblur(src, dst, size(), 1.6*k, 1.6*k); if (display_dst(delay_blur*10) != 0) { return 0; } k = k * k; dst.copyto(dest[m]); //dest[m] = dst; m++; } //} width2 = dog[1].size().width; height2 = dog[1].size().height; size sizes(width2,height2); mat dog_inv(sizes,0,cv_64f); (int n = 0; n < 2; n...

excel 2010 time difference and message -

Image
how can compare time difference between 2 dates in excel? want 1 of following messages displayed (1-2 months, 2-4 months, 4-6 month, 6-9 months or 9 months+). if time difference either 2,4,6,9 months + days should rounded up. if number of months , days within correct time bracket should display message. here example list of dates , time difference output should say: start date end date desired message 21/06/16 29/08/16 2-4 months 12/20/16 29/08/16 6-9 months 06/06/16 29/08/16 2-4 months 28/02/15 29/08/16 9 months + so taking first on list: 21/06/16 - 21/08/16 = 2 months. 2 months + 8 days = 29/08/16 therefore 2 - 4 months. first of check date format. let's a1 start date , b1 end date. first month count between these 2 dates , keep these in c1 ((year(a1)-year(b1))*12+month(a1)-month(b1))*-1 then =if(c1=1,"1 - 2 months",if(and(c1>=2,c1<4),"2 - 4 months",if(and(c1<6,c1>=4),"4 -...

C# string format delimiter 12-3456789-0 -

i have below string. 1234567890 i want string. 12-3456789-0 i tried using below code. string.format("{0:0-#######-#}", "1234567890"); but result not want. 1234567890 fiddle the reason code not work because specifying number-formatting string. look: string.format("{0:0-#######-#}", "1234567890"); // "1234567890" string try instead: string.format("{0:0-#######-#}", 1234567890); // 1234567890 number incidentally, output want, format string needs {0:0#-#######-#}

javascript - ReactJS showing list of items -

i have array of objects(a list of comments item), , want display on page. not of comments! first 10 example. , below list wanna render kinda button. , if user wants see next 10 comments, needs click on button. something 'show more' in 'youtube'. i can render comments! don't need that. need display 10 comments ... each time button being clicked. can me please thanks so let's assume have 20 comments in array var comments = getcomments() // returns list of 20 comments then can use slice first 10 comments, map them actual html var commentsashtml = comments.slice(0, this.state.limitto).map(comment => { return <li key={comment.id}>{comment.text}</li> }); to add "load more" functionality, have limitto state limitto = 10; and each "load more" action, increment limit 10 example. onloadmore () { this.setstate({ limitto: this.state.limitto + 10 }); }

python - Optional keys in string formats using '%' operator? -

is possible have optional keys in string formats using '%' operator? i’m using logging api python 2.7, can't use advanced string formatting . my problem follow: >>> import logging >>> format = '%(asctime)-15s %(message)s %(user)s' >>> logging.basicconfig(format=format) >>> logging.warning("it works for:", extra={'user': 'me'}) 2016-08-29 11:24:31,262 works for: me >>> logging.warning("it does't work!") traceback (most recent call last): ... keyerror: 'user' logged file <input>, line 1 i want have empty string user if missing. how can that? i tried defaultdict , fails: >>> import collections >>> = collections.defaultdict(unicode) >>> logging.warning("it does't work!", extra=extra) traceback (most recent call last): ... keyerror: 'user' logged file <input>, line 1 by contrast, jinja2 , can d...

angularjs - angular validation within ng-repeat -

i have below validation texboxes within ng-repeat <div class="col-md-6 col-lg-2"> <div class="form-group"> <label for="country{{$index}}" class="control-label required">country</label> <div class="input-group"> <mc-lookup-dropdown data-lookup-name="countrytype" required data-model="contactaddress.country" id="country{{$index}}" name="country{{$index}}" class="form-control"></mc-lookup-dropdown> </div> <div data-ng-messages="memberdemographics.demographics.$error" class="validation-errors"> <div data-ng-message="country">{{ contactaddress.$servererrors.country }}</div></div> <div data-ng-messages="demographicsform.{{'country'+$index}}.$error" class="validation-errors"> ...

ios - Getting UTC time for any time and handling daylight saving as well -

i have written function utc time string corresponding time string passed argument function. +(nsstring *)getutctime:(nsstring *)selectedtime { nsstring *strformat; if ([self is24hourformat:selectedtime]){ strformat = @"hh:mm"; } else{ strformat = @"hh:mm a"; } nslocale *baselocale = [[nslocale alloc] initwithlocaleidentifier:@"en_us_posix"]; nsdateformatter *dateformatterlocal = [[nsdateformatter alloc] init]; [dateformatterlocal settimezone:[nstimezone systemtimezone]]; dateformatterlocal.locale = baselocale; [dateformatterlocal setdateformat:strformat]; nsdate *selecteddate = [dateformatterlocal datefromstring:selectedtime]; nsdateformatter *dateformatterutc = [[nsdateformatter alloc] init]; [dateformatterutc settimezone:[nstimezone timezonewithname:@"utc"]]; dateformatterutc.locale = baselocale; [dateformatterutc setdateformat:strformat]; nsstring *utcti...

Publish command for ASP.NET Core project only includes DLL files -

i'm trying publish asp.net core 1.0 project, in order able deploy azure (or other hosting environments) later on. my folder structure follows (not sure if matters): |_root |_foo |_bar -> contains project.json from root folder run publish command so: dotnet publish foo/bar -o artifacts\foobaroutput --configuration release this creates folder output publish command, only contains assemblies (dll files) , folder called refs containing referenced assemblies. my question is: how create complete publish package, including static resources such html, javascript, css, configuration files, etc? am missing in project.json file, or parameters publish command? must missing something, guess there must way specify src folder etc should included in output? my project.json file looks following: { "title": "my web app", "version": "1.0.0-*", "buildoptions": { "debugtype": "portable...

java - Error trying to put dates on Xaxis in a line chart -

package org.gillius.jfxutils.examples; import javafx.animation.animation; import javafx.animation.keyframe; import javafx.animation.timeline; import javafx.application.application; import javafx.event.actionevent; import javafx.event.eventhandler; import javafx.fxml.fxml; import javafx.fxml.fxmlloader; import javafx.scene.scene; import javafx.scene.chart.linechart; import javafx.scene.chart.xychart; import javafx.scene.control.label; import javafx.scene.control.slider; import javafx.scene.input.mousebutton; import javafx.scene.input.mouseevent; import javafx.scene.layout.region; import javafx.scene.layout.stackpane; import javafx.stage.stage; import javafx.util.duration; import org.gillius.jfxutils.jfxutil; import org.gillius.jfxutils.chart.chartpanmanager; import org.gillius.jfxutils.chart.fixedformattickformatter; import org.gillius.jfxutils.chart.jfxchartutil; import org.gillius.jfxutils.chart.stableticksaxis; import java.text.simpledateformat; import java.util.timezone; publ...

java - Proguard on ShareSDK. Got an Exception NoClassDefFoundError: com.mob.tools.utils.R -

i using proguard obfuscate android application. application using sharesdk library. while use share function. got noclassdeffounderror title. i have add proguard-rules in proguard-rules.pro below: -keep class cn.sharesdk.**{*;} -keep class com.sina.**{*;} -keep class **.r$* {*;} -keep class **.r{*;} -dontwarn cn.sharesdk.** -dontwarn **.r$* -keep class m.framework.**{*;} -keep class com.mob.**{*;} -dontwarn com.mob.** and have checked mapping.txt having sentences below: com.mob.tools.utils.r -> com.mob.tools.utils.r: float density -> density int devicewidth -> devicewidth java.lang.object rp -> rp void <init>() -> <init> ... so think class com.mob.tools.utils.r kept. can tell me how can find class? add proguard.pro file -keepclasseswithmembers class * { public <init>(android.content.context, android.util.attributeset); } -keepclasseswithmembers class * { public <init>(android.content.context, android.util....

html - Css background colour not working -

hello creating website , can't here code: body { font-family: "segoe ui", tahoma, sans-serif; font-size: 18px; background-color: ffffff; overflow: auto; } <body> <div class="main"> <img src=images\cat.gif></img> <table class="table"> <tr> <th style="text-align:left;"> <p id="output"><b>likes: 0</b> </p> </th> <th style="text-align:right;"> <button class="button" onclick="likebutton()">like</button> </th> </tr> </table> <script src="script.js"></script> </div> </body> i have idea wrong of guides i've seen have fixed syntax errors i've triple checked , sure don't have plus on other documents have same issue. may...

python - Send XML to activeMQ using Django -

i trying send xml file generated using 'elementtree' activemq server using python django 'requests' library .my views.py code : from django.shortcuts import render import requests import xml.etree.celementtree et # create views here. def index(request): return render(request,"indexer.html") def xml(request): root = et.element("root") doc = et.subelement(root, "doc") field1 = et.subelement(doc,"field1") et.subelement(doc, "field2", fame="yeah", name="asdfasd").text = "some vlaue2" et.subelement(field1,"fielder", name="ksd").text = "valer" tree = et.elementtree(root) headers = {} tree.write("filename.xml", encoding = "us-ascii", xml_declaration = 'utf-8', default_namespace = xml, method = "xml") url = 'http://localhost:8082/testurl/' headers = {'content-type...

c# - How to add resource files to CefSharp.Wpf as string -

i have c# wpf project, in want display web view chromium cefsharp.wpf. the content of webview should loaded sql database. i can display html page loadhtml(html, url) . but how can load resourcefiles (styles or scripts) string? example: loadresource(data, "./styles.css")