Posts

Showing posts from January, 2015

java - How to access arrays from multi-thread? -

simply speaking, problem follows: i have class named test , has 3 double arrays,named array1, array2,array3 respectively(assuming have same length).it has major function named estep, , need implement function multi-threading improve speed. in estep, need modify array1 , array2, , array3 read .i define indicator variable named which_array indicator array modify.i passed 3 arrays estep , modify array1 , array2. my code follows , test , it works fine modification of array1 , array2 in estep can seen in test class . still have doubt if absolutely right. i'm wondering if should add volatile 3 array1 in test class or should need synchronization mechanism?. any advice appreciated! public class test{ double[] array1; double[] array2; double[] array3; //for simplifization, omitted code allocation , initialization of the arrays. public void estepintest() { final countdownlatch countdown = new countdownlatch(2); estep modifyarray1 = new est

multithreading - Android ListView when get data -

i upload data listview data internet takes bit time. have wait it. how can give datas listview . ofcourse comes threads , dont know how handle this? im using simpleadapter. idea? use asynctask populate data internet listview . more asynctask here asynctask onpreexecute show progress dialoge. doinbackground fetch data internet onpostexecute populate listview

changing the button background color based upon the button text value in android -

i've created android application creates 50 button dynamically,which works perfectly, problem when press 1 button defined statically results in changing button (text named 5) background color yellow. can please tell me solution code given below android platform 2.3.3 import android.app.activity; import android.os.bundle; import android.view.viewgroup.layoutparams; import android.widget.button; import android.widget.linearlayout; public class mymain extends activity { button change; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); change= (button) findviewbyid(r.id.change); setcontentview(r.layout.mymain); createcalender(); change.setonclicklistener(new view.onclicklistener() { public void onclick(view v) { // write here in order change color of button titled 5 yellow background color } }); } public void createcalender() {

cocoa - CGEventPost - hold a key (shift) -

i'm looking way design little panel modifier keys on (shift, command example) , have possibility click on virtual keyboard. i'd have behavior : click on virtual key (shift). the shift button holds, , keeps being pressed. type standard keyboard. click time on virtual shift key release it. here code i'm using : cgeventsourceref source = cgeventsourcecreate(kcgeventsourcestatehidsystemstate); cgeventref shiftkeydown = cgeventcreatekeyboardevent(source, (cgkeycode)56, yes); cgeventref shiftkeyup = cgeventcreatekeyboardevent(source, (cgkeycode)56, no); cgeventpost(kcgannotatedsessioneventtap, shiftkeydown); cgeventpost(kcgannotatedsessioneventtap, shiftkeyup); cfrelease(shiftkeyup); cfrelease(shiftkeydown); cfrelease(source); i can't find way keep pressed until click on time. though "push on push off" button cell type key unfortunately no. :-) any ? thanks in advance. a shift key virtually pressed way, released automatically when f

android - Path of PDF Viewer Library -

i using pdf viewer library view pdf inside android app. i've browsed through lot of tutorials, 1 of dipak's tutorial . want access pdf file stored in assets folder instead of accessing external storage. problem is, can't "path" right. return file not found. i've tried following, still yields same result: this.getassets() file:///android_assets/file_name.pdf file:///android_asset/file_name.pdf you can't path asset, have right in sd or internal memory path. for sd card first take permission <uses-permission android:name="android.permission.write_external_storage" /> then write in card file f = new file(environment.getexternalstoragedirectory() + "file.pdf"); if (!f.exists()) try { inputstream = getassets().open("file.pdf"); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); fileoutputstream fos = new fileoutputstream(f); f

java - Normalize the PCM data -

i using following code normalize pcm audio data, correct way normalize? after normalization applying lpf. order matters whether lpf first , normalization on output or current order better if matters. targetmax set 8000 used on of forum's posting. optimal value it. input 16 bit mono pcm sample rate of 44100. private static int findmaxamplitude(short[] buffer) { short max = short.min_value; (int = 0; < buffer.length; ++i) { short value = buffer[i]; max = (short) math.max(max, value); } return max; } short[] process(short[] buffer) { short[] output = new short[buffer.length]; int maxamplitude = findmaxamplitude(buffer); (int index = 0; index < buffer.length; index++) { output[index] = normalization(buffer[index], maxamplitude); } return output; } private short normalization(short value, int rawmax) { short targetmax = 8000; double maxreduce = 1 - targetmax / (double) rawmax; int abs = math.abs(value)

ios - Put 2 NSAttributedStrings in one Label -

is possible put 2 nsattributedstring s in 1 label? for example: nsstring *a = [car valueforkey:@"name"]; nsstring *b = [car valueforkey:@"version"]; nsattributedstring *title; title = [[nsattributedstring alloc] initwithstring:a attributes:@{ nsfontattributename : [uifont fontwithname:@"noteworthy-bold" size:36], nsunderlinestyleattributename : @1 , nsstrokecolorattributename : [uicolor blackcolor]}]; //1 nsattributedstring *title2; title2 = [[nsattributedstring alloc] initwithstring:b attributes:@{ nsfontattributename : [uifont fontwithname:@"noteworthy-bold" size:36], nsunderlinestyleattributename : @0 , nsstrokecolorattributename : [uicolor blackcolor]}]; //2 cell.textlabel.attributedtext = //what should write here? you can use -appendattributedstring:(nsstring *) method append 1 attributed string other. since can make both of attributed strings mutable, can include separators (semicolons, commas) differen

How did Tibco BW HTTP Receiver accept a REST Web Service Request? -

how did tibco bw http receiver accept rest web service request??? how configure it?? how did tibco bw expose rest web service??? now using tibco bw5.9; thanks from http point of view, there nothing special rest requests. there examples how receive , process rest requests in rest4bw

c++ - How to put osgEarth's ViewerWidget into an tabbed MdiArea? -

is there special putting osgearth's viewerviewer qmdiarea ? created qmdiarea central widget (called setcentralwidget ) instead of taking osgearth 's viewer directly central widget. qmdiarea *mdiarea = new qmdiarea(this); setcentralwidget(mdiarea); // call qmainwindows method, snippet taken app's mainwindow mdiarea->addsubwindow(viewerwidget); // doesn't work, globe not drawn everything tried didn't worked... except osgearth's viewerwidget set central widget of mainwindow . tried multiviewerwidget without success because need 1 view viewerwidget should ok, or not? i had examples didn't succed use 1 of them starting point. any hints? thank's in advance. you can try this, form1 qdialog in main.cpp int main() { qapplication a(argc, argv); form1 w=new form1();//qdialog .................//do initial map w.loadwidget(viewerwidget); w.show();//the order of loadwiget() , show() important!!!!! a.exec();

opengraph - Facebook story without external page -

is there way use facebook stories , custom actions without creating external page ogp markup? which sdk use? with ios sdk can make object below. nsmutabledictionary<fbopengraphobject> *object = [fbgraphobject opengraphobjectforpostwithtype:@"[yourappname]:[yourobjectname]" title:title image:thumbnail image url:urlstring description:description]; for general graph api check link. https://developers.facebook.com/docs/opengraph/using-objects?locale=ko_kr#objectapi-creatingapp

numpy - efrc gives error length-1 array can be converted to python -

i'm trying calculate bit error rate in python numpy. code looks this: ebbyno = arange(0,16,1) ebno = 10**(ebbyno/10) ber2 = (3/8)*erfc(cmath.sqrt(ebno*(2/5)))+(1/4)*erfc(3*sqrt(2/5*ebno)) but it's giving me error: ber2 = (3/8)*erfc(cmath.sqrt(ebno*(2/5)))+(1/4)*erfc(3*sqrt(2/5*ebno)) typeerror: length-1 arrays can converted python scalars cmath not support numpy arrays: ber2=(3/8)*erfc(sqrt(ebno*(2/5)))+(1/4)*erfc(3*sqrt(2/5*ebno)) you seem importing lot of functions from foo import * can trip up. using ints (for example 2/5 ) instead of floats equation above returns array of zero's: >>> 2/5 0 >>> 2./5 0.4 i suggest: >>> import numpy np >>> import scipy.special sp >>> ebbyno=np.arange(0.,16.,1) >>> ebno=10**(ebbyno/10) >>> ber2=(3./8)*sp.erfc(np.sqrt(ebno*(2./5)))+(1./4)*sp.erfc(3*np.sqrt(2./5*ebno)) >>> ber2 array([ 1.40982603e-01, 1.18997473e-01, 9.77418560e-02,

d3.js: add elements according to data-attribute value -

i simplified example as possible. have data.csv file , want create elements below (result). there elegant way? thank you. data (data.csv): id, name, value 1, fruits, apple 2, fruits, pear 3, fruits, strawberry 4, vegetables, carrot 5, vegetables, celery ... result: <g class="groups" id="fruits"> <circle class="some" id="apple"/> <circle class="some" id="pear"/> <circle class="some" id="strawberry"/> ... </g> <g class="groups" id="vegetables"> <circle class="some" id="carrot"> <circle class="some" id="celery"> ... </g&gt i tried this: d3.csv("data.csv", function(data) { var svg = ... var groups = svg.selectall(".groups") .data(data) .enter().append(&q

How do I add a custom method to a Ruby library? -

i'm using restforce library salesforce queries. queries, following: client = restforce.new :username => 'user', :password => 'pass', :security_token => 'token', :client_id => 'client_id', :client_secret => 'client_secret' and call client.query query salesforce. i want create custom method called query_with_alises can call client.query_with_aliases custom functionality. how without editing source code of library itself? you can open class again , add method want. though exact meaning matter of debate, called monkey-patching . consider monkey-patching overriding/redefining existing methods (which can kinda dangerous), other consider kind of opening existing classes , adding anything, if new methods. in specific case, can monkey-patch client class restforce that: class restforce::data::client def query_with_aliases # put code here end end every other method inside client keep existin

HTML select not inflating correctly from PHP array -

i trying create drop down menu of usernames or <select> it's known in html . getting last value array , can't figure out why. php function getusername($db) { try { $sql = 'select members.name members'; $query_an = $db->query($sql); $count = $query_an->rowcount(); if ($count > 0) { while ($row = $query_an->fetch(pdo::fetch_assoc)) { $names = array(); $names[] = $row['name']; } return $names; } } catch(pdoexception $e) { die($e->getmessage()); } } html <select> <?php $names = getusername($db); foreach($names $key => $value) { ?> <option value="<?php echo $key ?>"><?php echo $value ?></option> <?php }?> </select> i'm sure html section of co

sql - How to implement pagewise loading in MSAccess -

in application using msaccess db, need implement pagewise loading sql query. i know how load first 10 records, thats by select top 10 * product order dateadded desc but how can pick record 10 20. any idea? it's possible in access sql, not straightforward in other database products. (for example mysql, limit 10,10 ) check out answer here: how ms access database paging + search? (the code build sql statement in c#, of course can in other language well. if don't know c# , need understanding answer, leave comment here)

python 3.x - tkinter progress bar with file list -

i have loop read files in python below: def rfile(): filename in filelist: …. how can add tkinter progress bar linked loop , size of filelist (start before loop , close after loop)?. thx this little script should demonstrate how that: import tkinter tk time import sleep # truncation make progressbar more accurate # note no progressbar perfect math import trunc # need ttk module tkinter import ttk # demonstrate filelist = range(10) # how increase each iteration # formula in proportion length of progressbar step = trunc(100/len(filelist)) def main(): """put loop in here""" filename in filelist: # sleeping represents time consuming process # such reading file. sleep(1) # demonstrate print(filename) # update progressbar progress.step(step) progress.update() root.destroy() root = tk.tk() progress = ttk.progressbar(root, length=100) progress.pack() #

layout - CSS table height of rows not even -

i trying create 4x4 array of content using css tables. cells should evenly sized. got fix problem cells going out of parent div . broke height of cells. what wrong here? rows should 25% of container, cells inheriting that. seems happen first row grows as can, , 3 remaining ones scale according content... why? <html xmlns="http://www.w3.org/1999/xhtml"> <head> <style type="text/css"> html,body { display: block; height: 100%; width: 100%; } div { display: block; } #container { background-color: #ccf; position: absolute; height: 100%; width: 100%; } .sidebyside { position: absolute; float: left; top: 0px; height: 100%; } #galleria { background-color:#0c0; left: 0px; right: 300px; width: auto; } #tagit { background-color: #099; right: 0px; width: 300px; } #table { position: absolute; display: table; height: 100%; width: 100%; } .table-row {

restkit - Mapping XML succeeds but object has empty values -

i'm using rkxmlreaderserialization , trying map xml response server object. succeeds, object mapping result has empty values. here's text/xml response i'm trying map server: <provision version="1.0"> <fileinfowrapper> <fileurl>somefile.zip</fileurl> <filename>somefile.zip</filename> <filesha1>oi7nk/rfll6dxqcu7ahanfksgke=</filesha1> <filesize>52220448</filesize> <version>13</version> <vital>true</vital> </fileinfowrapper> </provision> here's model object: @interface fileinfowrapper : nsobject @property nsstring *fileurl; @property nsstring *filename; @property nsstring *filesha1; @property long filesize; @property nsstring *version; @property bool vital; @end i've added rkxmlreaderserialization: [rkmimetypeserialization registerclass:[rkxmlreaderserialization class] formimetype:rkmimetypetextxml]; [[self objectmanager

c# - Retrieving data from the operating system and storing it in the program -

if text file stored lots of words in cat, rat, hat, bat stored in words.txt , notepad how can retrieve each word separately , them stored in string array string [] myarray using filestream , streamreader object. has stored myarray[0] = "cat" , myarray[1] = "rat". assuming words separated spaces (i.e. no punctuation, etc.), can read file string , split it: string alltext = file.readalltext("words.txt"); string[] myarray = alltext.split( new [] {" ", environment.newline}, stringsplitoptions.removeemptyentries); if reason absolutely have use filestream , streamreader , you'd write: string alltext = null; using (filestream fs = new filestream(...)) // fill in file name , other params { using (streamreader sr = new streamreader(fs)) { alltext = sr.readtoend(); } } // string split here now, if want take account punctuation , other special characters, that's more involved problem.

jquery - open javascript library to do the same thing as symbolset -

i planning on creating own symbol font use on website , had intended on using ligatures , ot support spotty @ best, , non-existant older browsers, ie (i know, big surprise). started taking close @ how symbolset works. it's pretty clever , while easy me change couple array variables , done it, javascript proprietary , can't use without permission. i'd love able create own symbol fonts la symbolset i'd need open javascript file let me this. there open jquery plug-ins or javascript libraries this? i have found http://labs.adamdscott.com/ligatures/ligaturejs.html . walks dom, , replaces known letter combinations ligatures. i've modified script use native ligature support when available: // ligature.js v1.0 // http://code.google.com/p/ligature-js/ // modifications sabof var ligature = (function() { var testdiv = document.createelement('div'), nativeligaturesupport = testdiv.style.textrendering !== undefined; if (nativeligaturesupport)

html - Can I set values onto the days in Jquery UI datepicker? -

for example, want put 100 1st of january, , want check if has exceeded maximum number allowed each dates, possible? if so, how can done, if not, there other datepickers allows want achieve? you can use setdate method; example: var date = $(this).datepicker('getdate'); date.setdate(date.getdate() +100); $(this).datepicker('setdate', date);

php - Facebook API - Access Token Delivers Inconsistent Information -

Image
in facebook's api, graph explorer( https://developers.facebook.com/tools/explorer ) provides data on requested queries using facebooks graph structure. when choosing 3 fields,"id, name, posts", explorer returns of users posts of user's wall, filtering out activity user has done anywhere else. strictly on user's wall. the problem here whenever make new application , test applications data results using graph api explorer similar, information. information what's included in user's, "recent activity", feed. in graph explorer if @ top there choice application, can switch application you've made. when requesting access token, can select the, "read_stream", permission allows application read user's stream data i.e wall, news feed, etc. the requests made graph api explorer application deliver different results custom made app using face book's developer api. i've tried locate problems within access tokens, i'

javascript - Is there any difference between `element` and `iElement` in AngularJS? -

i using angularjs , jquery, angularjs official tutorial using ielement inject, other tutorial using element , there different? following btn1 , btn2 work, element , ielement wrap jquery. var app = angular.module('myapp', []); app.directive('btn1', function () { return function (scope, element) { element.click(function () { $(this).css('background', '#666'); }); }; }); app.directive('btn2', function () { return function (scope, ielement) { ielement.click(function () { $(this).css('background', '#666'); }); }; }); no, there no difference, both 2 variable names. can use name instead of element/ielement el/eleme etc, factor matters in values passed callback in case link callback function passes scope, element, attributes , controllers. when matters when use environment argument injection used in controller function or in directive functio

Master method algorithm analysis of pseudocode -

how find c/d constant used in master theorem examining pseudo-code? fastpower(a,b) : if b = 1 return otherwise c := a*a ans := fastpower(c,[b/2]) if b odd return a*ans otherwise return ans end firstly, need find recurrance relation: t(n) = t(n/b) + o(d) + o(c) o(d) time takes divide problem subproblems, o(c) time takes recombine subproblems answer, number of subproblems, , n/b size of subproblems. then, once have recurrence can analyze using master theorem. in algorithm, believe there 1 subproblem of size n/2, 1 , b 2. time dividing o(1) , time recombining o(1) assuming analysis not in terms of bit operations. using master theorem, o(1) = Θ(n log 2 1 ) therefore total runtime Θ(n log 2 1 log n) = Θ(log n)

Django 1.2 won't run my view -

i'm getting 404 django server though it's aware of view code. if purposely misspelled name of view function, django complains, know it's looking in right place , aware of function. my urls.py entry looks this url(r"^pdfgen/$", 'apps.pdfgen.views.pdfgen'), and view code this def pdfgen(request): html = "<html><body>this test.</body></html>" return httpresponse(html) so why django 404's when visit localhost:xxxx/pdfgen/ ? if purposely misspelled name of view function, django complains, know it's looking in right place , aware of function. that doesn't mean request hitting correct view - means django can't load url conf when include views don't exist. sure django running view think is, need add logging or print statements view, or raise exception in it. update question include url patterns. request matching view further up, returning 404.

css3 - LESS CSS parametric mixin default null value does not work -

i have lesscss mixin box-shadow : .box-shadow(@x, @y, @blur, @color, @addit: ''){ -webkit-box-shadow: @x @y @blur @color @addit; -moz-box-shadow: @x @y @blur @color @addit; box-shadow: @x @y @blur @color @addit; } as seen, there parameter @addit set '' default. it's work fine when give @addit value : .box-shadow(0, 0, 2px, #1361aa, inset) , why if parameter @addit not filled, doesn't work? , how fix it? help, advance. escape empty string default you need set default value ~'' escaped string. less .box-shadow(@x, @y, @blur, @color, @addit: ~''){ -webkit-box-shadow: @x @y @blur @color @addit; -moz-box-shadow: @x @y @blur @color @addit; box-shadow: @x @y @blur @color @addit; } .test{ .box-shadow(0, 0, 2px, #1361aa) } css .test { -webkit-box-shadow: 0 0 2px #1361aa ; -moz-box-shadow: 0 0 2px #1361aa ; box-shadow: 0 0 2px #1361aa ; }

iphone - Why MBProgressHUD not show, when an alert show before HUD show? -

i use code init mbprogresshud uiwindow *window = [[uiapplication sharedapplication] keywindow] _hud = [[mbprogresshud alloc]initwithwindow:window]; _hud.dimbackground = bdim; _hud.labeltext = message; [window addsubview:_hud]; [_hud show:yes]; but _hud not show in window ? let me know im lack here?? thanks! click here ! works me .just use window. uiwindow *keywindow = [[[uiapplication sharedapplication] delegate] window]; or can use self.navigationcontroller.view to add hud.

javascript switch case not working properly? -

i have following code , using switch case switch src of pictures button.. don't know why first case's "alert" not functoning.. <div id="main_img"> <center> <button style="width:100;height:100" onclick="lastpic();"><---</button> <img id="img" src="13.jpg" height=70% width=70%> <button style="width:100;height:100" onclick="firstpic();">---></button> </div> <script> var james = document.getelementbyid("img").getattribute('src'); document.write(james); function firstpic(){ switch (james){ case "12.jpg": document.getelementbyid("img").src = "13.jpg"; break; case "13.jpg": document.getelementbyid("img").src = "14.jpg"; break; case "larry":

c# - Changing a cell in a row of a DataGrid(WPF) is changing cells in rows below -

i trying change background of errorneous data containing cells in wpf datagrid using code: datagridrow gridrow = dginventory.itemcontainergenerator.containerfromindex(0) datagridrow; datagridcell cell = dginventory.columns[1].getcellcontent(gridrow).parent datagridcell; cell.background = brushes.gray; gridrow.isselected = true; gridrow.focus(); however, upon doing this, above change of background-color change occuring cells in same column, periodically after every 14 (aprox.) rows scroll down datagrid . intended modify background of single row. can please provide fix problem? in advance. try using this: <datagrid name="simpledatagrid" scrollviewer.cancontentscroll="false" ... /> for scrolls in terms of physical units. datagrid cancontentscroll enabled default. for more information see msdn .

php - Running exec in a script -

i have this: <?php if ($_get['run']) { # code run if ?run=true set. exec("./check_sample.sh"); } ? <!-- link add ?run=true url, myfilename.php?run=true --> <button type="button" onclick="?run=true">click me!</button> the shell script check_sample.sh has o/p prints using printf/echo when click 'click me' don't see o/p. anypointer on how make take text input , pass $1 arg. script help exec() doesn't output anything. use passthru() . be very careful passing user input external program. if make sure escape using escapeshellarg() . kind of this: passthru('./check_sample.sh '.escapeshellarg($your_user_input));

Testing if a Daemon is alive or not with Shell -

i have log_sender.pl perl script when executed runs daemon. want make test, using shell: #!/bin/bash function log_sender() { perl -i $home/script/log_sender.pl } ( [[ "${bash_source[0]}" == "${0}" ]] || exit 0 function check_log_sender() { if [ "ps -aef | grep -v grep log_sender.pl" ]; echo "passed" else echo failed fi } log_sender check_log_sender ) unfortunately when run terminal becomes: -bash-4.1$ sh log_sender.sh ... ... what doing wrong? > if [ "ps -aef | grep -v grep log_sender.pl" ]; this not want. try this: if ps -aef | grep -q 'log_sender\.pl'; ... in shell script, if construct takes argument command exit status examines. in code, command [ (also

java - Unable to extract noun pharses from the result of open nlp Chunking parser -

hi have used opennlp chunking parser , parsed text , of below stack overflow question have tried extract noun phrases how extract noun phrases using open nlp's chunking parser but unable extract noun phrases, below code public class keywords { list<parse> nounphrases; public static void main(string args[])throws invalidformatexception, ioexception { inputstream = new fileinputstream("en-parser-chunking.bin"); parsermodel model = new parsermodel(is); opennlp.tools.parser.parser parser = parserfactory.create(model); string sentence = "programcreek huge , useful website"; parse topparses[] = parsertool.parseline(sentence, parser, 1); (parse p : topparses) { p.show(); p.tostring(); } is.close(); } public void getnounphrases(parse p) { if (p.gettype().equals("np")) { nounphrases.add(p); } (

curl multi-handle keep-alive after getting 404 -

i want reuse connection after getting 404 server. using easy-handle, got behavior default. using multi-handle, after getting 404 had remove , add handle (otherwise doesn't perform request @ all), , got connection. b.t.w after ok response (200), removing , adding handle doesn't affect persistency. there way have behavior 404 response?

Python/Django Writes u'' String To Postgresql (with UTF8 DB) and Munges Entry -

i'm sure i've misconfigured here, can't see is. in django, i've got model field says this: short_url_slug = autoslugfield(slugify=short_url_slugify, populate_from=id, blank=false, unique=true) south creates migration (seemingly) correctly: 'short_url_slug': ('autoslug.fields.autoslugfield', [], {'unique_with': '()', 'max_length': '50', 'populate_from': 'none', 'blank': 'true'}), my postgresql db utf8: \l (mydbname) | (username) | utf8 | en_us.utf-8 | en_us.utf-8 | and have real life unicode character: u'\xa4' but when write db, , try read out, get: in [3]: this_instance.short_url_slug out[3]: u'o' thoughts? suspicion postgresql needs have different character encoding, i'm not sure should (if so) or how it. edit additional info select version(), current_setting('standard_conforming_strings') scs; postgresql

android - How to create scrollable tabs? -

i working create scroll able tabs, please me out, using below code, not work me <tabhost xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/tabhost" android:layout_width="fill_parent" android:layout_height="fill_parent"> <linearlayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <horizontalscrollview android:layout_width="fill_parent" android:layout_height="wrap_content"> <tabwidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </horizontalscrollview> <framelayout android:id="@android:id/tabcontent"

jquery - Highchart line chart circle around datalabel -

i'm plottting highchart line graph datalabel. can draw circle around datalabel? if no, there chart library can so? you can set borderradius borderradius: 40 http://jsfiddle.net/sbochan/p6ufv/

javascript - How to remove unsafe contents of WYSIWYG editors before use it? -

how remove unsafe contents of wysiwyg editors script tags or iframe tags , events of other tags before use it? <script> // dangerous contents </script> <iframe> // bad web pages </iframe> <span onclick="javascript://do bad work here !!!">click me</span> you shouldn't try write such protection on own. specially, should not place protection on client side (javascript), use instead server side filtering http://htmlpurifier.org/

WHMCS invoicepdf.tpl and viewinvoice.tpl multiple currencies -

i need 2 currencies displayed on invoices, in basic way: $total should displayed in default currency, followed currency calculated using current exchange rate stored in tblcurrencies table, i'm having trouble getting work. so line in invoicepdf.tpl , should like: <td align="center">'.$total.' (€'. number_format($total/$exrate, 2, '.', '').')</td> where $exrate current exchange rate pulled database , stored in variable. similar should in viewinvoice.tpl . of course, there might smarter way this. as seen here, no currency variable available : http://docs.whmcs.com/pdf_invoice_customisation so need make database call within viewinvoice.tpl , currency variable. other , simpler way use whmcs built-in functions described here(formatting currency seciton): http://docs.whmcs.com/useful_functions_for_devs

trying to understand late static bindings in php -

<?php class record { protected static $tablename = 'base'; public static function gettablename() { echo self::$tablename; } } class user extends record { protected static $tablename = 'users'; } user::gettablename(); it shows: base question: i know can change problem changing line echo self::$tablename; echo static::$tablename; , called 'late static bindings', read doc here , still not quite understand it. give me explanation on: a. why line of code echo self::$tablename; shows: base? b. why line of code echo static::$tablename; shows: users? self "bound" @ compile time, statically. means when code compiled , decided self refers to. static resolved @ run time , i.e. when code executed. that's late static binding. , that's difference. with self , decided @ compile time (when code "read"), self refers record . later on code user parsed, self::$tablename in record refers r

problems in using search function in rails -

i trying simple search function. function in module. have 2 columns: title , description. error. instead of posts need have select "title" in there. def self.search(search) if search find(:all, :conditions => ['name ?', "%#{search}%"]) else find(:all) end end the error is: sqlite3::sqlexception: no such column: name: select "posts".* "posts" (name '%first%') update: here index.html.erb file. have used form , listed posts along content. how change file display searched item? should listed. not able understand how this. ideas? <h1>our blog</h1> <%= form_tag posts_path, :method => 'get' %> <p> <%= text_field_tag :search, params[:search] %> <%= submit_tag "search", :name => nil %> </p> <% end %> <% @posts.each |post| %> <h2><%= link_to post.title,post %></h2> <p><%= post.content %&g

c - netcat gcc compile option so that IDA pro can show function name -

i want idapro show functions name , variables, like: _readwrite , _dolisten shows sub_40xxxx in function window. how can edit compile option achieve it? the original makefile is: cc=gcc cflags=-dndebug -dwin32 -d_console -dtelnet -dgaping_security_hole ldflags=-s -lkernel32 -luser32 -lwsock32 -lwinmm all: nc.exe nc.exe: getopt.c doexec.c netcat.c $(cc) $(cflags) getopt.c doexec.c netcat.c $(ldflags) -o nc.exe you using mingw on windows. so, -s option in ldflags means final binary stripped. remove option. moreover, can try add more debug information in order idapro recover as possible program adding -g3 cflags , replacing -dndebug -ddebug (it add more insightful messages software). at end should have this: cflags=-g3 -ddebug -dwin32 -d_console -dtelnet -dgaping_security_hole ldflags=-lkernel32 -luser32 -lwsock32 -lwinmm just side note, may answered more efficiently question on idapro on re .

c# - How to Make Color Palette in Windows Phone 8 -

i have color selector , want when user selects particular color should display corresponding palette of 5 colors. can color user have selected not able find how make palette according color. i have tried taking color , changing rgb value nearby color patterns not able desired results change in rgb value changes color lot want color in contrast of selected color. please help, thanks.

php - Size calculator formula -

i working on website have calculate sizes of dresses. want know how can calculate approximate size of dress using these values: chest, waist, height, weight, inseam, hips, neck, length. formula (like height* neck etc.) these values may single chest or more one. these values may in mm or cm. see link reference. based on example linked to, there no overlap between of individual measurements (ie chest, hip, sleeve length) within men’s, ladies or youth. takes 1 of each (men’s chest, or ladies hip, or youth’s sleeve, etc). values in cm firstly i’d suggest converting mm (1 cm = 10 mm) then, given link in inches, divide mm 25.4 obtain value in inches up. eg: ladies hip 100cm = 1000 mm or 39” ie m.

python - Executing code after construction of class object -

i hoping make list of subclasses of given class having each subclass register in list parent class holds, ie this: class monster(object): monsters = list() class lochness(monster): monster.monsters.append(lochness) class yeti(monster): monster.monsters.append(yeti) this doesn't work because classes haven't been created yet when want add them list. and, it'd nicer if done automatically (like __subclass__) i'm aware __subclass__ has functionality, wondering (for own edification) how you'd implement yourself. it seems you'd want create sort of subclass of metaclass creating register monster? or off base classes already register subclasses defined; call class.__subclasses__() method list: >>> class monster(object): ... pass ... >>> class lochness(monster): ... pass ... >>> class yeti(monster): ... pass ... >>> monster.__subclasses__() [<class '__main__.lochness'>

session state - Swap between Azure Colated Caching and InProc -

i have setup web roles use colocated caching. problem during development don't want have run emulator time (as quite cumbersome). running our web applications (not emulated in web role) fails because of azure session state provider: [invalidoperationexception: role discovery data unavailable] microsoft.windowsazure.serviceruntime.roleenvironment.get_roles() +171 is possible configure caching use normal inproc when not running in web role , use azure colocated caching when running in web role. the session state configuration located in web.config, create config override standard web.config transformations local development , when deploy make sure switch config has reference azure caching provider. http://blogs.msdn.com/b/webdev/archive/2009/05/04/web-deployment-web-config-transformation.aspx update : adding notes comments below. can add code prior start of website programatically swap out providers. there ability on web role start ( http://blog.elas

Global variable not updating inside static Class method in PHP -

i have problem global variables in php. problem global variable change inside static class method isn't updating outside method. i've included code: test.php define( 'app_id', 'testing' ); $_app = array( 'test' => 'test value' ); include ('appsettings.class.php'); appsettings::initapplication(); appsettings.class.php class appsettings { public static function initapplication() { global $_app; session_start(); // code here initializtions self::initappengine(); echo '<pre>inside initapplication: '; print_r($_app); echo '<pre>directly printing session variable: '; print_r($_session[app_id] ); } private static function initappengine() { global $_app; if( isset($_session[app_id]) ) { $_app = &$_session[app_id]; } else { $_session[app_id] = array( 'abcd' => 'hello', 'app_id' => app_id ); $_app = &

String storage size in sqlite -

after using lots of sql server , sql server compact , have started use sqlite . i'm creating tables in sqlite , have noticed there doesn't seem need input string length limit when defining string columns. in sql server 255-character string datatype defined like: varchar(255) . in sql server compact defined like: nvarchar(255) . however, in sqlite , appears column datatype can defined text , without inputting size limit. there way define size limit in sqlite? or not necessary? there managable string or blob limit in sqlite. default 10^9 bytes. see documentation btw don't need specify on column declaration anyway.

How to retain Listbox visualization with high resolution images in windows phone 8 -

i in between of developing document scanning application, in need save more 50 images in single document. issue during time of loading saved images listbox, think loosing visualization of listbox, , hence memory consumption increases dramatically , caused application crash. how can load images listbox, without loosing visualization of listbox? in current project (winrt) have similar problem , solved resizing images during binding (in getter of nested field) { return new bitmapimage(new uri(url)) { decodepixelwidth = 200 }; } hope it's too.

linux - RUID & EUID after exec() -

with fork() operation child process inherits attribute real , effective user id's parent process, how behaves when exec() performed ? exec not change of them. linux manual : the exec() family of functions replaces current process image new process image. the exec changes process image (the code , data segment in memory), not change process descriptor of new process created fork. process descriptor contains real , effective id, because not changed exec call, effective , real id not changed neither. i hope have been clear explaining concept. the real , effective uid , gid of child process equal real , effective uid , gid of parent process. therefore, when child process calls exec values not modified. in order prove wrote small application creates child process calls exec . exec system call runs application prints out value of gid , uid of current process. in addition gid , uid of parent process showen well, can compare them. main.c #include

sql - How to concat values which retrieved from database -

i executing query in sql server 2008 select (convert(date, getdate())) and shows result 2013-07-22 . i need print result 22713 , 22 date 7 month 13 year. how this? select cast(datepart(dd,getdate()) varchar(10)) +cast(datepart(mm,getdate()) varchar(10)) +right(cast(datepart(yy,getdate()) varchar(10)),2) sqlfiddle demo

struct - C typedef for undeclared structure is not throwing any compilation error -

i wondering how typedef not throwing compilation error when used undeclared structure. below code compiling without warning , error. doubt how come typedef undeclared structure not throwing error. same in platforms #include <stdio.h> typedef struct undeclared_struct_st und_struct_s; int main() { printf("\nhello world\n"); return 0; } i executing program in suse 11 gcc 4.3.4. typdef struct undeclared_struct_st und_struct_s; is valid. declares struct undeclared_struct_st incompele type , declares und_struct_s typedef struct undeclared_struct_st . cannot create objects of incomplete type can create pointers objects of incomplete type. struct undeclared_struct_st can declared in translation unit.

c++ - How many random numbers does std::uniform_real_distribution use? -

i surprised see output of program: #include <iostream> #include <random> int main() { std::mt19937 rng1; std::mt19937 rng2; std::uniform_real_distribution<double> dist; double random = dist(rng1); rng2.discard(2); std::cout << (rng1() - rng2()) << "\n"; return 0; } is 0 - i.e. std::uniform_real_distribution uses two random numbers produce random double value in range [0,1). thought generate 1 , rescale that. after thinking guess because std::mt19937 produces 32-bit ints , double twice size , not "random enough". question: how find out number generically, i.e. if random number generator , floating point type arbitrary types? edit: noticed use std::generate_canonical instead, interested in random numbers of [0,1). not sure if makes difference. for template<class realtype, size_t bits, class urng> std::generate_canonical standard (section 27.5.7.2) explicitly defines number

integration testing - How can I test database interactions in c# -

a bit of background: i've been developing in java , javascript past years , i've been moved c# project , tasked implementing data access layer project. far understood dal call stored procedures (so no simple sql queries) , return value if stored procedure asks it. i apologize if question has been answered before not able find useful. what best way test dal calling these stored procedures , returning results expecting? in java used arquillian integration tests against db , worked great, have not been able find c#. any appreciated. write unit tests dal using nunit. can test results expected.

c++ - std::wstring (from wifstream), spec. chars -

i need std::wstring, std::wifstream, wifstream contains, special characters, such as: ä,ê and, on. i have code wifstream *infile = new wifstream(szfile); std::wstring szwfilestr((std::istreambuf_iterator<wchar_t>(*infile)),std::istreambuf_iterator<wchar_t>()); but, not read in special characters, hoping would e.g., file contains characters, such ä, , ê, , turn out ö i think, in file, utf-8. any ideas, one? :)

c# - How to run InstallScript project from console application -

i have created major upgrade (installscript msi) running when executing clicking on exe file. i creating console aplication runs same exe time after installation, along new version, previous version showing in add/remove programs list. all components installing correctly but why previous version showing when run exe console application? // enter executable run, including complete path start.filename = @"folder1\myisproj.exe"; // want show console window? start.createnowindow = true; start.windowstyle = processwindowstyle.minimized; start.useshellexecute = false; start.redirectstandardoutput = true; // run external process & wait finish using (process proc = process.start(start)) { //proc.waitforexit(); proc.close(); } one more thing have observed is, when call exe console application installer open , after accepting eula , etc, when actual installation start console application getting called again. stop behavior have added check in main method run

osx - Get Notification of task progress from NSTask -

any body have idea getting notification nstask while nstask executed. unzipping zip file using nstask , need show unzip data progress in nsprogressbar. don't found idea doing such task.so show value in progress bar. need doing task. in advance. use nsfilehandlereadcompletionnotification , nstaskdidterminatenotification notifications. task=[[nstask alloc] init]; [task setlaunchpath:path]; nspipe *outputpipe=[[nspipe alloc]init]; nspipe *errorpipe=[[nspipe alloc]init]; nsfilehandle *output,*error; [task setarguments: arguments]; [task setstandardoutput:outputpipe]; [task setstandarderror:errorpipe]; output=[outputpipe filehandleforreading]; error=[errorpipe filehandleforreading]; [task launch]; [[nsnotificationcenter defaultcenter] addobserver:self selector:@selector(receiveddata:) name: nsfilehandlereadcompletionnotification object:output]; [[nsnotificationcenter defaultcenter] addobserver:self selector:@selector(receivederror:) name: nsfilehandler

django - Trying filter query depending on a method of a related model -

class course(models.model): def is_active(self): return self.enroll_set.count()>0 class courseevent(models.model): course = models.foreignkey(course) i want find events point active courses. like: events = courseevent.objects.filter(course.is_active=true) thank you the answer here: https://docs.djangoproject.com/en/dev/ref/models/querysets/#annotate you make annotation, it'll filterable field. it may this: courseevent.objects.annotate(is_active=count('course__enroll')).exclude(is_active=0)