Posts

Showing posts from February, 2013

Convert EDT timestamp to PST with regex / JavaScript -

a third party providing me edt time-stamp in following format: mm/dd/yyyy hh:mm for instance: '08/19/2013 11:31' i need convert pst javascript (same date time format) , have been looking on can't find info doing this.. if can me example code appreciate it. if wanted manually, can try following: split space, have date , time. split time ":" , split date "/". create new date() , provide right values in right order. subtract 3 hours using proper methods, recreate format. here's example of this: var est = "01/01/2014 02:31", finaldate, pst; finaldate = parsedatestring(est); finaldate.sethours(finaldate.gethours() - 3); pst = formatdate(finaldate); console.log(pst); function parsedatestring(str) { var datetime, date, time, datesplit, month, day, year, timesplit, hour, minute; datetime = est.split(" "); date = datetime[0]; time = datetime[1]; datesplit = date.split("/"

java - Why would a module in a JAR not be found? -

i working in netbeans 7 python script using jython. trying build nasa worldwind example. i have added jars classpath, including 1 contains gov.nasa.worldwind. the code crashes, saying traceback (most recent call last): file "c:\users\wrightky\documents\netbeansprojects\ww\src\ww.py", line 4, in <module> import gov.nasa.worldwind wwj importerror: no module named gov i have both added jar "gov" classpath , added jar python package manually, under can see gov.nasa.worldwind. i add code not sure if it's relevant. why happen? from question it's not entirely clear whether you're compiling java class file or python, if java should know can't import x y in java. if have conflicting class names, you'll have use fully-qualified class name (ie gov.nasa.wordwind.someclass ) every time reference it. see question more details: change name of import in java, or import 2 classes same name

android - Listview item smaller than screen width so the activity background is visible on the sides -

i need know how modify list items layout don't fill screen width , activity background visible on sides. i tried various layout_width no success. i want know how it, i'll apply rule in case edit: xml code of list item <?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:orientation="vertical" android:layout_marginleft="20dp" android:cliptopadding="true" android:background="#ffffff" > <linearlayout android:layout_width="match_parent" android:layout_height="wrap_content" > <imageview android:id="@+id/post_logo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="

python - How to extract a number from a request.path in Django -

i'm looking way extract number request.path in django. number id of object. when print request.path gives me following: >>>print request.path /post/v2/delete-document/15/ i extract number 15 since id of object being deleted. make equal variable called object_id: object_id = 15 how can go doing this? how this? explanation: first, split string / character, , make sure, result doesn't contain empty strings (that's why have if i ) , last item list [-1] , convert integer builtin int() function code: object_id = int([i in str(request.path).split('/') if i][-1]) print(object_id) output: 15

serialization - Django REST framework flat, read-write serializer -

in django rest framework, involved in creating flat, read-write serializer representation? docs refer 'flat representation' (end of section http://django-rest-framework.org/api-guide/serializers.html#dealing-with-nested-objects ) don't offer examples or beyond suggestion use relatedfield subclass. for instance, how provide flat representation of user , userprofile relationship, below? # model class userprofile(models.model): user = models.onetoonefield(user) favourite_number = models.integerfield() # serializer class userprofileserializer(serializers.modelserializer): email = serialisers.emailfield(source='user.email') class meta: model = userprofile fields = ['id', 'favourite_number', 'email',] the above userprofileserializer doesn't allow writing email field, hope expresses intention sufficiently well. so, how should 'flat' read-write serializer constructed allow writable email at

theymeleaf inline javascript framework issue -

<script th:inline="javascript" type="text/javascript"> //expose list data javascript var listobject = /*[[${listobject}]]*/ []; </script> the replacement text printed file different jackson library's objectmapper does. with thymeleaf in above example, listobject be { "datatype":{ "$type":"datatype", "$name":"string" }, "friendlyname":"customer key" } if print object objectmapper(which used spring @requestbody/@responsebody), { "datatype":"string", "friendlyname":"customer key" } is there way can force thymeleaf compatible objectmapper. i think this has jackson , json inlining in thymeleaf. summarize, possibility switch custom textinliners considered 3.0 thymeleaf milestone. so, there no "clean" way switch jackson json serialization. what can however, sneak own textinl

wordpress - get contents and permalink base on the specified page title on the query -

below query supposed contents page specified page title <?php $page = get_page_by_title( 'about us' ); $content = apply_filters('the_content', $page->post_content); the_content_rss('', true, '', 100); ?> <a href="<?php the_permalink() ?>" title="read whole post" class="rm">read more</a> and yes display content , trim content 100, problem content , permalink not content , permalink of specified page pulled query, mean, content , permalink different page im pulling up. ideas whats going on? im trying play around code seems nothing works @ , im looking on web possible solution unfortunately, find nothing. ps: want display content , permalink of specified page im pulling through query above. could try following code? <?php $page = get_page_by_title( 'about us' ); $content = apply_filters('the_content', $post->post_content); echo

html - CSS: Floating IMGs inside floating divs -

i encountered problem , didn't find solution this. i'm pretty confused because thought simple requirement. there following elements: a surrounding div#wrapper div#a, floating left , fixed width div#b, floating left (right of #a) , dynamic width inside of div#b there plenty of images, floating left , fixed width (and height). depending on screen resolution there should 1, 2, 3, n columns of images on right part of screen (next div#a). instead of this, container #b aligned below container #a , uses full window width. my alternative attempt giving #b float:right , margin-left (which greater width of #a), didn't work. i avoid absolute positioning because height of surrounding wrapper should increase content. to visualize i'm talking about, made following diagram: http://abload.de/img/rezeptbilder1k8lsr.png many in advance! this happening because..you having dynamic width div#b ...ans there plenty of images , aligned next each other...so div#b

Using Say command on a breakpoint in Xcode -

i using xcode , set breakpoint speaks nsstring code. doing setting breakpoint, editing it. add "shell command" action. first argument say , second argument i'm having trouble. nsstring *mystring = @"this test"; if put @mystring@ second argument, reads out memory address. ex. 0x0b4be130 if try @[mystring utf8string] , gives me memory address. if dereference mystring, @*[mystring utf8string]@ , gives me first character of string. how do properly? lldb has inbuilt python interpreter, entire lldb library exposed it. can access script debugger command. this, can more grab string representation of variable in frame, , send os command. add debugger action: script os.system("say " + lldb.frame.getvalueforvariablepath("myvariable").description) to achieve want. can wrap python scripts new lldb "commands", can create debugger command called say explicitly says underlying objects description; have @ http://lldb.

SVG to PNG in javascript with filter support -

i've been using method convert svgs pngs using canvg: convert svg image (jpeg, png, etc.) in browser . however, canvg not have support fecolormatrix filters, need project. know of alternative conversion method, or fix issue? thanks!

javascript - sessionStorage isn't working as expected -

here code: sessionstorage.loggedin = true; if (sessionstorage.loggedin) { alert('true'); } else { alert('false'); } simple enough. there must small thing i'm not understanding how javascript evaluating these expressions. when put sessionstorage.loggedin = false , "false" alert shows correctly. however, when change sessionstorage.loggedin true, "false" alert still pops, after clearing session. not getting right expression? seems simple, maybe need pair of eyes on it. try change code to sessionstorage.setitem('loggedin',json.stringify(true)); if (json.parse(sessionstorage.getitem('loggedin'))) { alert('true'); } else { alert('false'); } and should work consistently across major browsers. the interface setitem / getitem methods how spec written, going way safer using shortcut of assigning properties. also, sessionstorage , localstorage textbased s

Python list is converted into integer -

while testing code errors appeared - after mathematical operation, list 'shrinks' down itself's last item in python 3.3 interpreter works fine... a = [a + b a, b in zip(a, b)] i'm using code add list items a = [1, 2, 3] b = [2, 3, 2] this works fine , returns >>> [3, 5, 5] >>> b [2, 3, 2] then wrote class handle more lists: class vector: def __init__(self, name = '', vector = []): self.__name = name self.__vector = vector def add_row_to_scalar_multiple(self, vector): self.__vector = [self.__vector + vector.__vector self.__vector, vector.__vector in zip(self.__vector, vector.__vector)] def __str__(self): vec = ('{0} = {1}'.format(self.__name, self.__vector)) formatted_vec = vec.replace(',', '') return formatted_vec when running code same lists above, 1 list reduced single integer vec_a = vector('a', [1, 2, 3]) vec_b = vector(&

actionscript 3 - How do I copy an instanced MovieClip multiple times programmatically? -

i'm extremely new flash/actionscript, i've done c#, java , c++... anyway, question is: if have movieclip called bird1, , need following: dostuff(bird1); dostuff(bird2); dostuff(bird3); where bird2 , bird3 exact copies of bird1, new instances.... how can until dostuff(bird30); without having copy 30 times , write out? thanks in advance.. you should assign class name symbol of bird in library: open library f11 select bird movie clip open symbol properties window (right click->properties) select "export as" check box assign class name symbol, instance mybird now can instantiate class many times want code: dostuff(new mybird());

javascript - jqPlot - Different color bars based on value range for each data point in series -

Image
i need change color of bar chart conditionally each data point in 1 series. 1 data point in series needs have different thresholds color other 4 data points. i tried implement suggestions found @ this post , i'm getting js error object doesn't have method get. this data i'm working with: series 2 needs have colors varied. data produce these series here threshold data contains [ [2,1], [4,2], [6,3], [3,4], [8, 5] ] results data contains [ [6,1], [6,2], [4,3], [6,4], [6, 5] ] the results data refer blue bar chart lines , threshold data orange line. for element 1 of results element 4, need following results: if first element of inner array >= 0 , <= 4, bar should red if first element of inner array >=5 , <= 7, bar should yellow if first element of inner array >=8 , <= 11, bar should green. for element 5 of results, need: if first element of inner array >= 0 , <= 5, bar should red if first element of inner array >= 6 , <= 11,

c# - WPF not calling TypeConverter when DependencyProperty is interface -

i trying create typeconverter convert custom type icommand if binding button command. unfortunetly wpf not calling converter. converter: public class customconverter : typeconverter { public override bool canconvertto(itypedescriptorcontext context, type destinationtype) { if (destinationtype == typeof(icommand)) { return true; } return base.canconvertto(context, destinationtype); } public override object convertto( itypedescriptorcontext context, cultureinfo culture, object value, type destinationtype) { if (destinationtype == typeof(icommand)) { return new delegatecommand<object>(x => { }); } return base.convertto(context, culture, value, destinationtype); } } xaml: <button content="execute" command="{binding customobject}" /> converter invoked if bind content like: <button content="{binding customob

javascript - how to retrieve xml from rss url using js ( jquery) -

how can use .ajax request in jquery retrieve xml data link: http://open.live.bbc.co.uk/weather/feeds/en/2643743/3dayforecast.rss with data being assigned variable string: var xml = ''; you can't! javascript has same origin policy, , service not seem support cors, , it's xml, jsonp isn't option. you'll have on serverside, , ajax call own webserver or use yql or similar.

node.js - Initializing client javascript variables from nodejs -

i trying send data client using nodejs @ same time server sending html and/or javascript. i'm pretty new web development , overlooking core concept. here's do. require('http'); var somevar = 'some data'; http.createserver(function(req, res){ res.writehead(200, {'content-type': 'text/plain'}); res.write(somewebpage); res.sendthisdatatoclient(somevar); res.end(); }).listen(4000); and client var somevar = getdatasentwiththispage(); // stuff i did find way solve specific problem had in different way although still know how / if possible / if javascript way. you use templating engine , send data so: res.render('index.html', { myvar : somevar }): and in index.html you'd have expression evaluating myvar , example <% myvar %> in ejs, or span=myvar in jade.

sybase - How to add two columns to a table -

i have table. want add 2 columns table. i tried this: select * dbo.mytable_audit dbo.mytable but, need 2 colums mytable_audit, how add them in sybase 15-2 ase? you columns in new table, have in existing one. name, type , order inherited dbo.mytable . add additional column output, add column select: select 0 col1, * dbo.mytable_audit dbo.mytable; this adds column of type integer first column in new table.

Facebook Graph Search API: type=post, can you limit by location? -

i'm wondering if there way have graph search call of type=post restrict results geographic location can when you're searching location example? i tested using same parameters can use limit place search (center , distance) , didn't work. i'm wondering if can suggest trick here? i know posts don't contain geo data why isn't enabled. any suggestions? thanks. from facebook graph api docs docs when retrieving posts via /home, /feed, or /posts connection, can restrict results location attached adding with=location url parameters: /me/home?with=location checkins: /search?type=checkin (this request returns or friend's latest checkins, or checkins or friends have been tagged; currently, not accept q= parameter.) objects location. following return information objects have location information attached. in addition, returned objects in or friend have been tagged, or objects created or friends. there important behavioral differences in result

c# - Comparing a list against a dataset -

i writing vs 2012 c# winforms app has list of data need match against database. list have solely contains "propnum" values string such as, i8kj7snrxy. want able loop through list , database in order find out if there corresponding entry propnum in list. here code puts of information list, con7 = new oledbconnection(@"provider=microsoft.ace.oledb.12.0;data source=" + filepath); ad7.selectcommand = new oledbcommand("select b.propkey [project] inner join [projlist] b on a.projkey=b.projkey a.name = '" + (string)combobox2.selecteditem + "'", con7); ds7.clear(); con7.open(); ad7.selectcommand.executenonquery(); ad7.fill(ds7); con7.close(); list<string> propnumlist = new list<string>(); foreach (datarow drrow in ds7.tables[0].rows) { (int = 0; < ds7.t

css - Put a footer on a jqueryui autocomplete list -

i attempting put footer on list of autocomplete. able put li element in list, can't stay @ bottom. i made fiddle showing basic html structure of list. problem is, css have, footer scrolls overflow area. how can keep pegged bottom? http://jsfiddle.net/jcbpz/1/ <ul> <li>item1</li> <li>item2</li> <li>item3</li> <li>item4</li> <li>item5</li> <li>item6</li> <li>item7</li> <li>item8</li> <li>item9</li> <li>item10</li> <li class="footer">footer</li> </ul> ul{ display: block; height: 100px; overflow: auto; position: relative; list-style: none; } li.footer{ position: absolute; bottom: 0; left: 0; right: 0; background: gray; color: white; } demo here.. based on update: edit: demo works how want to, try out.. position of footer ab

jquery - Issues with ajaxSubmit and serialize -

i'm having issues posting textarea contents database using ajax. i've tried use both jquery.form.js plugin malsap, ole fashon ajax, , cannot either post values out textareas. heres code: html: <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script type="text/javascript" src="javascript/jquery.form.js"></script> <form id="defaultemail-ebook-form"> <label for="defaultemail-ebook">email ebook:</label><br> <textarea id="defaultemail-ebook" name="defaultemail-ebook"></textarea> <br> <div id="defaultemail-ebook-submit-div"> <input type="button" id="defaultemail-ebook-submit" value="set email"> </div> </form> defaultemails.php mysql_connect("$host", &q

php - How to optimize an if else if statement where previous ifs are not used in loop? -

this hypothetical code, assuming have following: let's have array , has lots of data, integers in sample question, can type of data that's sorted in fashion in regards if statements. $a = array(0,0,0,1,1,1,1,1,1,2,2,2,2,3,3,...,9,9,9); let's have loop numerous if else if statements, , can have criteria doing something. for($i=0; i<count($a); i++) { // these if statements can , may or may not related $a if($a[$i] == 0 && $i < 10) { // } else if($a[$i] == 1 && $i < 20) { // } else if($a[$i] == 2) { // } else if($a[$i] == 3) { // } // , on } now question, after first if statement iterations done, it's never used. once loop starts using next if statement, previous if statement(s) don't need evaluated again. can use first if statement n amount of times , on , forth. is there way optimize doesn't have go through previous if else if statements it's loo

c# - How do I define a web service request structure? -

i have create webservice receives string parameter, , have been asked team define how structure requests web service, , send them. am correct in saying: https://www.oursite.com/webservicename.asmx?op=webservicemethodname?employeeid=string is they're asking?

jquery - Bootstrap tooltip not visible in rails app -

i trying implement bootstrap tooltip, seems hidden behind other content. when hover element rel="tooltip", tooltip div generated dom, not visible in browser. have z-index not causing problem. appreciated:) here code: //= require jquery //= require jquery_ujs //= require jquery.ui.all //= require modernizr //= require bootstrap //= require bootstrap-multiselect //= require bootstrap-scroll-modal //= require i18n //= require i18n/translations //= require flashy //= require colorfont // //= require avatars_for_rails // //= require_self //= require_tree ./social_stream icon tooltip: <i class="icon-ok-sign" rel="tooltip" title="tooltip"></i> tooltip init: jquery -> $("[rel=tooltip]").tooltip({ delay: { show: 400, hide: 100 }, container: "body", animation: "true"}) result in dom console when hovering: <div class="tooltip" style="display: block; position: absolute; top:

sql server - pyodbc - previous sql was not a query -

i above error while trying insert data table, tried set nocount on option , still have same problem, import pyodbc p connstr= 'driver={sql server};server=sqlexpress;database=test;trusted_connection=yes;unicode_results=false' conn = p.connect(connstr,charset='utf-16') print conn cursor = conn.cursor() try: result = cursor.execute("""select col1 tb2 (select 1 col1) tb1""") except exception error: print error each in result.fetchall(): print each you need execute first select [xxx] [new_tablename] [yyy] tsql statement, read newly created tb2 table. import pyodbc p connstr= 'driver={sql server};server=.\sqlexpress;database=test;trusted_connection=yes;unicode_results=false' conn = p.connect(connstr,charset='utf-16') print conn cursor = conn.cursor() try: result = cursor.execute("""select col1 tb2 (select 1 col1) tb1""") except exception error: print erro

arrays - Replace number by sum of other numbers in a list without subtraction -

i asked: replace each number in list sum of remaining elements, list not sorted. suppose if have list of numbers {2, 7, 1, 3, 8} , replace each element sum of rest of elements. output should be: {(7 + 1 + 3 + 8), (2 + 1 + 3 + 8), (2 + 7 + 3 + 8), (2 + 7 + 1 + 8), (2 + 7 + 1 + 3)} == {19, 14, 20, 18, 13} i answered obvious solution: first evaluate sum of numbers subtract each element sum . above list sum 2 + 7 + 1 + 3 + 8 = 21 , output like: {sum - 2, sum - 7, sum - 1, sum - 3, sum - 8} {21 - 2, 21 - 7, 21 - 1, 21 - 3, 21 - 8} == {19, 14, 20, 18, 13} it needs 2 iterations of list. then interviewer asked me: without subtraction? , couldn't answer :( is other solution possible? can share other trick? better trick possible? lets memory space can used (i asked after few minutes of try, couldn't answer). one possibility compute prefix , suffix sums of array , combine appropriate entries. still o(n) needs more memory space thi

c++ - Calling an object-specific function on a STL vector of polymorphic objects -

so have class hierarchy has entity class parent abstract class , bunch of other classes derive it, such door , player , ground , etc. i have three-dimensional vector stores pointers objects of type entity , fill vector derived objects. within door class have method called isopen() returns bool . function specific door class , neither found in entity class nor in other derivations of (as don't need check whether, example, ground object open or not). now, knowing there exists object of type door @ vector position i , j , k , call method isopen so: vector[i][j][k]->isopen() . unfortunately, when this, compiler returns class entity has no member named isopen() . understandable since function isopen() exclusive door class, can in order make sort of call possible? one way solve down cast door * first. however, in order down cast type safe, should use dynamic_cast<door *>() . if entity not have virtual method, can add virtual destructor. class

c# - How to make AvalonDock's floating child window dock when user double-clicks its title bar? -

i relatively new avalondock 2.0 heard 1 can change behavior of title bar double-clicked in floating child window new version. can't find clue on google or own site. possible? i ended modifying source of avalondock because it's addition of 6 lines. if know better way, please post answer. in switch statement of filtermessage method of layoutanchorablefloatingwindowcontrol.cs case win32helper.wm_nclbuttondblclk: _model.descendents().oftype<layoutanchorablepane>().first(p => p.childrencount > 0 && p.selectedcontent != null).selectedcontent.dock(); break; in switch statement of filtermessage method of layoutdocumentfloatingwindowcontrol.cs case win32helper.wm_nclbuttondblclk: _model.rootdocument.dock(); break;

Visual C++ CRT debugging -

hello explain me point in using define debug, ndebug... , can provide me example. idea idea, help, suggetion appreciated. so point in: #define debug or #define ndebug these preprocessor definitions inserted compiler in debug build, utilize it. example, may want print debug statements in debug build, , not include them in release build. can achieve using preprocessor: #ifdef _debug printf("debug statement here, or other piece of code"); #endif this printf statement included in debug build. see this question differences between these two. more explanation: before cpp file compiler, passed program named preprocessor. task prepare file compiling by, example, replacing #include directives appropriate file's content, replace macros in code, , on. one of things preprocessor capable decide or not include blocks of code wrapped between #if(def) #else #endif# blocks (please note - not if/else c++ statement - these preprocessor directives. let

delphi - Convert an Octal number to Decimal and Hexadecimal -

i writing program converts octal number decimal , hexadecimal. wrote function called octtoint . function octtoint(value: string): longint; var i: integer; int: integer; begin int := 0; := 0 length(value) begin int := int * 8 + strtoint(copy(value, i, 1)); end; result := int; end; i call function in way: var oct:integer; begin oct:=octtoint(edit13.text); edit15.text:=inttostr(oct); end; when type 34 (octal) decimal number should 28 program gives me 220. know why? also, have idea converter octtohex? you have change start of "your" for 1. function octtoint(value: string): longint; var i: integer; int: integer; begin int := 0; := 1 length(value) //here need 1, not 0 begin int := int * 8 + strtoint(copy(value, i, 1)); end; result := int; end; the conversion octal-hexadecimal hard do, suggest way: edithexadecimal.text:=(inttohex(strtoint(editinteger.text),8)); as can see here, code edithexadecimal edit put

c# - Create Mono Installer Package (OSX) -

i have c# winforms application developed in mono on osx. i create installer package install application on osx computer. how create installer package ? thanks this blog entry explains how package gtk# app. if you're not using gtk, can still possibly reuse many of know-how of post.

javascript - how to detect window.print() finish -

in application, tried print out voucher page user, used: var htm ="<div>voucher details</div>"; $('#divprint').html(htm); window.settimeout('window.print()',2000); ' divprint ' div in page store information voucher. it works, , print page pops up. want further proceed application once user click ' print ' or ' close ' pop window. for example, i'd redirect user page after pop window closed: window.application.directtoantherpage();//a function direct user other page how determine pop print window closed or print finished? in firefox , internet explorer can listen after print event. https://developer.mozilla.org/en-us/docs/web/api/window.onafterprint window.onafterprint = function(){ console.log("printing completed..."); } it may possible use window.matchmedia functiionality in other browsers. (function() { var beforeprint = function() { console.log('func

Class-wise profiling of Java memory consumption -

i have java project initializes thousands of objects in tree-like hierarchy. initially, programming performance in mind , didn't mind storing lot of computable properties in class fields(variables).. however, recently, started trying estimate memory footprint of project , found large. i'm trying identify class consumes memory guess can narrow down field consuming (probably strings) i have come across java's instrumentation package , getobjectsize i tried understanding documentation, i'm not sure if instrumentation suited task. have noticed getobjectsize not recursively find sizes. i thinking of creating class extends object , contains static map of instance -> instancesize , , making classes extend class , updating constructors is approach correct? 'java' way of accomplishing this? um, put down coding tools , pick memory profiler. there great free ones out there.

liferay - AlloyUI - difference between node.attr("id") and node.getAttribute("id") -

in aui, difference between node.attr("id") and node.getattribute("id") where node object of type node. the documentation on getattribute says "allows getting attributes on dom nodes, normalizing in cases." don't understand normalizing means, , in case applied. thanks, alain node.attr both getter , setter. if pass second argument attr, set value of attribute (the first argument). node.getattribute getter. node.getattribute normalizes value ie , ie < 8. without falling in many details, means may pass w3c standard attribute , work on browsers. hope helps!

c++ - Personal SSE library -

ok, i've been using operator overloading of sse/avx intrinsics facilitate usage in more trivial situations vector processing useful. class definition looks this: #define float16a float __attribute__((__aligned__(16))) class sse { private: __m128 vec __attribute__((__aligned__(16))); float16a *temp; public: //================================================================= sse(); sse(float *value); //================================================================= void operator + (float *param); void operator - (float *param); void operator * (float *param); void operator / (float *param); void operator % (float *param); void operator ^ (int number); void operator = (float *param); void operator == (float *param); void operator += (float *param); void operator -= (float *param); void operator *= (float *param); void operator /= (

How to make a collapsible Div collapsed by default on page load using Twitter Bootsrap -

i have collapsible div on web page works fine when toggling between collaplse: the problem when web page loads "plcollapse" div opened default. how can closed div on page load <button type="button" class="btn btn-success" data-toggle="collapse" data-target="#plcollapse"> create list </button> <br/> <br/> <div id="plcollapse" class="collapse in"> <form > <fieldset> <div class="control-group"> <label for="title">title</label> <input type="text" class="form-control" ng-model="pltitle" value="{{pltitle}}" id="titleinput" placeholder="enter title"> </div> <div class="control-group"> <label for="description">description</label&g

c# - How to Highlight a Selected Item in LongListSelector -

i show border around selected item in longlistselector. have set itemtemplate longlistselector, unsure of how modify border selected item contains border. mainpage.xaml <phone:phoneapplicationpage.resources> <datatemplate x:key="itemtemplate"> <!-- borderbrush of items set phoneaccentbrush, need selected item! --> <border x:name="brd" cornerradius="10" borderbrush="{staticresource phoneaccentbrush}" width="auto" borderthickness="3"> <viewbox width="108" height="108"> <image x:name="recentimage" source="{binding source}" margin="6,6" width="108"/> </viewbox> <toolkit:contextmenuservice.contextmenu> <toolkit:contextmenu x:name="imglistcontextmenu" background="{staticresource phonechromebrush}">

linux - How to change the default size of a font file? -

is possible change default size of font file. i'm talking ttf files. on kindle paperwhite, installed couple of new fonts. of them works great, while other appears small, enlarge in kindle menu results in larger font not read. i'm wondering whether tweak font file default size bigger. i work under linux environment. i've googled way using fontforge. fontforge change font size after installation, open font file want change. detailed steps follow: go to: edit>select>selectall (all characters should selected) go to: element>tansformations>transform on transform menu, have chosen increase 20%...make sure boxes below checked. click ok it should render them 20% larger (or whatever choose) go to: file>generate fonts make sure change filename keep original clean , de-select validate - otherwise 200 warnings click ok...there couple of warnings appear, have not found visible font issues or errors-you can ignore them - hat it. when close

java - Method Created Objects Deleted on Exit -

this question has answer here: garbage collection on local variable 3 answers are objects / fields created in method deleted upon exit of specific method? example: public static void createfolder() { file folder = new file(c:\example\path "foldername"); folder.mkdir(); } would memory used store file "folder" deleted upon exit of "createfolder" method? the file object referred folder becomes eligible garbage collection upon exit method since reference ( folder ) goes out of scope @ point. when garbage collected impossible tell exactly, sometime after point. more generally, local variables in method allocated on stack , deleted when go out of scope. if primitives (int, float, long, etc) cease exist immediately. if references (as in case) reference ceases exist object referred continues exist long reference e

model - Rails ActiveRecord insert a count field in record result -

hi : class user < activerecord::base attr_accessible :label, :description, :number has_many :user_posts has_many :posts, through: :user_posts after_initialize :count protected def count self.number = posts.count end end i whant field :number count of posts of user (i think must defined in function count created in model. notice :number field not in db in model, want available in record returned user.last exemple. i'm new activerecord maybe it's not way need go, i'm open sugestion. try this: class user < activerecord::base attr_accessible :label, :description attr_accessor :number has_many :user_posts has_many :posts, through: :user_posts after_initialize :count protected def count self.number = posts.count end end you don't need specify :number in attr_accessible list not taking value of number uer right? for model attributes (not persistent) easiest way is, use attr_accessor

javascript - How to add multiple event delegation in jquery with focusout -

i trying execute 2 events 1 "on" function. have code: <input type="text" id="lesson" /> $('#lesson').on("focusout keyup",function(e){ var $change_education = $(this); if(e.which === 188){ var current_value = $(this).val(); add_edit_tags(current_value, $change_education); } }); the keyup event working focusout not. can't see web how solve this. thanks the problem seems checking e.which === 188 not set if focusout event, change condition below , check $('#lesson').on("focusout keyup",function(e){ var $change_education = $(this); if(e.type == 'focusout' || e.which === 188){ var current_value = $change_education.val(); add_edit_tags(current_value, $change_education); } }); demo: fiddle

backbone.js - HandleBars Compile w/ RequireJS and BackboneJS -

requirejs configuration: require.config({ baseurl: '/js/', paths: { jquery: './libs/jquery/jquery-1.10.1.min', underscore: './libs/underscore/underscore-min', backbone: './libs/backbone/backbone-min', handlebars: './libs/handlebars/handlebars', templates: '/templates' }, shim: { underscore: { exports: '_' }, backbone: { deps: ['jquery', 'underscore'], exports: 'backbone' } } }); view: define([ 'backbone', 'handlebars', 'text!templates/mytemplate.html' ], function(backbone, handlebars, template){ myview = backbone.view.extend({ tagname: 'li', template: handlebars.compile(template), render: function() { this.$el.html(this.template(this.model.tojson())); return this; } }

How to send email in ASP.NET C# -

i'm new asp.net c# area. i'm planning send mail through asp.net c# , smtp address isp : smtp-proxy.tm.net.my below tried do, failed. <%@ page language="c#" autoeventwireup="true" codefile="default.aspx.cs" inherits="sendmail" %> <html> <head id="head1" runat="server"><title>email test page</title></head> <body> <form id="form1" runat="server"> message to: <asp:textbox id="txtto" runat="server" /><br> message from: <asp:textbox id="txtfrom" runat="server" /><br> subject: <asp:textbox id="txtsubject" runat="server" /><br> message body:<br> <asp:textbox id="txtbody" runat="server" height="171px" textmode="multiline" width="270px" /><br>

Display Google Map based on ASP.NET/SQL database fields Address, City, Country, Postcode? -

we have backend sql database on our asp.net website holds each customer's: business name, street address, city/town, country, postcode/zip we want create contact.aspx?customerid=123456 webpage displays these details (depending on customer profile chosen) , medium sized map address underneath contact details. we can asp.net write html code page depending on customer. what should asp.net write html? need ask customer latitude , longitude co-ordinates first , load them database profile? or can pass address fields above page? tia mark you can use google maps geocoding service convert addresses lat/lng points can transferred map parameter.

android - runtime error about FriendsDBHelper -

this logcat error 08-20 10:37:52.463: e/database(1361): failure 1 (near "create_tablefriends": syntax error) on 0x9f418b8 when preparing 'create_tablefriends(id integer primary key autoincremaent,fname text(20), lname text(30), nickanme text(20))'. 08-20 10:37:52.481: d/androidruntime(1361): shutting down vm 08-20 10:37:52.481: w/dalvikvm(1361): threadid=1: thread exiting uncaught exception (group=0xb60084f0) 08-20 10:37:52.527: e/androidruntime(1361): fatal exception: main 08-20 10:37:52.527: e/androidruntime(1361): java.lang.runtimeexception: unable start activity componentinfo{com.example.sqlite/com.example.sqlite.insertactivity}: android.database.sqlite.sqliteexception: near "create_tablefriends": syntax error: create_tablefriends(id integer primary key autoincremaent,fname text(20), lname text(30), nickanme text(20)) 08-20 10:37:52.527: e/androidruntime(1361): @ android.app.activitythread.performlaunchactivity(activitythread.java:1647) 08-20 1

ios - XMPPFramework - How to transfer image from one device to another? -

i have made one-to-one chat using xmpp protocol. now, send image , video in application. researched file transfer didn't find solution. have used code below socket connection. please advice me on how can go doing this. [turnsocket setproxycandidates:@[@"myserverhost-desktop"]]; xmppjid *jid = [xmppjid jidwithstring:@"1254225445@myserverhost-desktop"]; turnsocket *turnsocket = [[turnsocket alloc] initwithstream:[[self appdelegate]xmppstream] tojid:jid]; [app.turnsocketarray addobject:turnsocket]; [turnsocket startwithdelegate:self delegatequeue:dispatch_get_main_queue()]; [turnsocket release]; - (void)turnsocket:(turnsocket *)sender didsucceed:(gcdasyncsocket *)socket { } - (void)turnsocketdidfail:(turnsocket *)sender { } every time connection fail method call.. thanks. you need push image server , reveice url server .then can send url device xmpp protocol. in end. download image server received url. xmpp can send image . that's b

android - MotionEvent.getX() and getY() not return correct value -

Image
the description of question in image below: the real display area specifies part of display contains content including system decorations. so, real display area may smaller physical size of display if window manager emulating smaller display using (adb shell display-size). use following methods query real display area: getrealsize(point), getrealmetrics(displaymetrics). a logical display not represent particular physical display device such built-in screen or external monitor. contents of logical display may presented on 1 or more physical displays according devices attached , whether mirroring has been enabled.

types - Create data for Image column in SQL Server -

i need create data test limit of image datatype in sql server. able hold variable-length binary data 0 through 2^31-1 (2,147,483,647) bytes. using following directly in sql server: insert employees (id, name, photo) select 10, 'john', bulkcolumn openrowset( bulk 'e:\photo.jpeg', single_blob) employeepicture my question is, how ensure max size (2,147,483,647 bytes) being inserted column? find image of size 2g , insert column? there way this? thanks in advance. most jpeg viewers ignore bytes after image data. following code tack on enough bytes make file whatever size want. tested , resulting image opened in windows image viewer, paint.net, , photoshop. should able create test files it... long desiredsize = 200000; byte[] buffer = new byte[1]; string filename = @"c:\temp\sample.jpg"; using (var fs = new filestream(filename, filemode.open, fileaccess.readwrite)) { fs.seek(desiredsize - fs.length - 1, seekorigin

bluetooth - Does Android 4.3 support multiple BLE device connections? -

i working on android 4.3 bluetooth low energy, able connect device, services, read/write service. when try connect second device, services of second device received , first device services lost. when try connect write/read characteristic of first device, nothing works. has 1 tried connecting multiple devices. how initialize gatt 2 devices? i think samsung ble api , google's api have broadcom ble stack , broadcom stack not supported multiple ble device currently.

regex - .htaccess rule for getting requested file size -

i wonder if there can such thing. wanna check size of file , htaccess rules based on it. example: # line checkif {requested_file_size} 50 # mb authname "login title" authtype basic authuserfile /path/to/.htpasswd require valid-user it's clear want make files specific file size available users (using authentication) any idea appreciated. update #1 should done in htaccess update #2 there many files , urls posted in blog. can't separate larger files folder , update each post, limitation of file size may change in future. update #3 it's windows server php & helicon app installed update #4 some people got confused real issue , didn't clear either. .htaccess + php file authentication (uses api) , checking file size + downloadable files in same server but our website hosted on different server. obviously .htaccess cannot check requested file size , act accordingly. can possibly make use of external rewriting program feature

jquery - Adding blank Data to an HTML Tag -

i wanting result adding data attribute through jquery. <li class="uk-pearent" data-uk-dropdown=""> the code using $('.uk-pearent').data('data-uk-dropdown'); this returns data attribute have not assigned yet; question is, how assign blank data attribute html tag using jquery. thanks in advance how assign blank data attribute html tag using jquery. you can pass value of data attribute second argument of data() $('.uk-pearent').data('uk-dropdown', ''); to value of data have remove data- before key var uk-dropdown = $('.uk-pearent').data('uk-dropdown');' syntax .data( key, value )

c++ - changing std::vector<double> debugger view -

it possible extend visual studio (2012) debugger shown in many places (e.g. here , here , important here ). i'm trying change how debugger shows std::vector<double> . goal when copy paste data vector in watch window program (e.g. matlab, excel,etc) data appear list of values instead of table additional data. for example, in current status when copy-paste data vector this: [0] 94.024513667772339 double [1] 104.70544392511518 double [2] 121.33423324928492 double [3] 132.01724343105604 double [4] 148.59977457595494 double what i'm trying achieve this: 94.024513667772339 104.70544392511518 121.33423324928492 132.01724343105604 148.59977457595494 can accomplished using custom debugger?

javascript - Plugin for jquery for date clears textbox -

i use jquery plugin date i have input in updatepanel <input id="datemask" type="text" /> and js code: function setd() { alert(1); $("#datemask").mask("99/99/9999", { placeholder: "_" }); } $(document).ready(function () { setd(); }); it supposed mask date when press enter inut clears text if click on input text remains. problem? upd: jquery version: <script src="/scripts/jquery-1.9.1.js" type="text/javascript"></script> <script src="/scripts/jquery-ui.js" type="text/javascript"></script> upd2: i've changed input textbox , worked hell?? how many of inputs have id of datemask ? change them classes , problems vanish. <input class="datemask" type="text" /> function setd() { alert(1); $(".datemask").mask("99/99/9999", { placeholder: "_" });

javascript - Extracting validation logic into a method for reuse? -

i using jquery validation plugin , working fine. have validation logic duplicated in 2 places 1 on form submit , other on focus out. trying extract method , reuse whereever required. trying below. $(document).ready(function() { validateform(); function validateform(){ $("#myform").validate({ onfocusout: function(element) { jquery(element).valid(); } , rules:{ attribute: "required" }, messages:{ attribute: "required field" } }); } $('#myform #submit').click(function(e) { e.preventdefault(); var validator = validateform(); //here shows error line if(validator.form()){ //do } }); }); if extract logic above getting script error below. error: 'undefined' null or not object do need return method? thanks! i don't have experience validati

java - Accessing properties of Objects within <#list> -

solution i had tried adding accessors lineitem class like public string getitemno() { return itemno; } and changing ftl ${lineitem.itemno} ${lineitem.getitemno()} didn't work. solution add accessors not change ftl (keep ${lineitem.itemno} . background i'm using freemarker format emails. in email required list number of lines of product information on invoice. goal pass list of objects (within map) may iterate on them in ftl. having issue unable access objects properties within template. i'm missing small, @ moment stumped. java class using freemarker this more simplified version of code in order more point across. lineitem public class public properties (matching names used here), using simple constructor set each of values. have tried using private variables accessors didn't work either. i storing list of lineitem objects within map use map other key/value pairs. map<string, object> data = new hashmap<string, object>(); list

c# - Unity 3.0 and Exception Logging -

need sample project unity exception logging. my requirement putting putting class attribute return parameter class , let unity work. such want method logged in customexceptionhandler , return -1 [customexceptionhandler(-1)] public static int process(){ throw new exception("test"); } firstly, not able intercept static method using unity. take @ developer's guide dependency injection using unity . specifically, chapter on interception using unity . modifying , tailoring code in guide might end like: class customexceptionhandler : icallhandler { public imethodreturn invoke(imethodinvocation input, getnexthandlerdelegate getnext) { writelog(string.format("invoking method {0} @ {1}", input.methodbase, datetime.now.tolongtimestring())); // invoke next handler in chain var result = getnext().invoke(input, getnext); // after invoking method on original target if (result.exception != null) {

shell - for loop in UNIX Script is not working -

for in `cat ${dir}/${indicator_flist}` x=`ls $i|wc -l` echo $x echo $x>>txt.txt done i have code check if file present in directory or not not working , gives error this: not foundtage001/dev/badfiles/rfm_dw/test_dir/sales_crdt/xyz.txt you can see there no space between not found , file path. i have code check if file present in directory or not ... it seems you're trying read list of files ${dir}/${indicator_flist} , trying determine if actually exist. main problem is: you're trying parse ls in order figure whether file exists. this results in sort of output see; mix of stderr , stdout . use test operator instead given below. the following give tell whether file exists or not: while read line; [ -e "${line}" ] && echo "${line} exists" || echo "${line} not exist"; done < ${dir}/${indicator_flist}