Posts

Showing posts from March, 2013

list - Python series writing issue -

i have code writing series in text file bin = int("377731") open('{0}/{0}.txt'.format(bin)) fine: cc in fine , in range(1000): name = cc[6:11] tg = open('{0}/{1}.txt'.format(bin,name), 'a') tg.write('{0}{1:03}'.format(cc,i)) tg.close() i wanted code write output this 37773100000000 37773100000001 ... but when excute code output shows this 37773100000 000 37773100000 001 ... why code writing ? error? when iterate on fine ( for cc in fine ) line with line break, hence linebreak between cc , i . if display it, see: >>> cc '37773100000\n' you can trim line using: cc = cc.strip()

asp.net mvc 4 - C# Complex Property Setter option -

i have asp.net mvc 5 (c#) application , i'm giving users ability posts , comments. for have model called likes following properties: public class { public like() { this.createdutc = system.datetime.utcnow; this.isactive = true; } public long id { get; set; } public string userid { get; set; } public bool isactive { get; set; } public liketype type { get; set; } public datetime createdutc { get; set; } } type enum , can either comments or posts . i've added following navigation property both post model , comment model: public virtual icollection<like> likes { get; set; } my question is, can have setter function in above line of code automatically set comments , posts type? know can use value variable in setter using google couldn't find how use complex types have above ( like ). i'm sure better way of doing in repository manually set enum every-time i'm going save like. update: seeing h

how to do jquery function if wordpress metabox checkbox is checked Sync in add new post area -

in wordpress backend -> add new post area, how after metabox -> checkbox checked, example when checked category: this the checkbox before checked: <input value="1" type="checkbox" name="post_category[]" id="in-category-1"> this the checkbox after checked: <input value="1" type="checkbox" name="post_category[]" id="in-category-1"> ::before </input> so, how detect checkbox checked , function after checked? you can achieve using jquery. !(function($){ $(document).ready(function(){ $('#categorychecklist').on('change', 'input[type=checkbox]', function(){ if ($(this).is(':checked')) alert('category' + $(this).closest('label').text() + ' added.'); else alert('category' + $(this).closest('label').text() + ' removed.'); }); }); })(window.jque

arc4random - how can i make my random text generator not repeat until all texts have been displayed? -

.h @interface viewcontroller : uiviewcontroller { iboutlet uilabel *textview; } -(ibaction)random; .m -(ibaction)random{ int text = arc4random() % 24; switch (text) { case 0: textview.text = @"example 1"; break; case 1: textview.text = @"example 2"; break; case 2: textview.text = @"example 3"; break; case 3: textview.text = @"example 4"; break; case 4: textview.text = @"example 5"; break; case 5: textview.text = @"example 6"; break; case 6: textview.text = @"example 7"; break; etc... want not repeat example 1, 3,6,2,5,4,7 or , start on without repeating same thing twice unless texts have been displayed in advance

php - Notice: Undefined index: intakeid -

this question has answer here: php: “notice: undefined variable”, “notice: undefined index”, , “notice: undefined offset” 23 answers i trying since last hour update database using php unable update. i error notice: undefined index: intakeid in c:\wamp\www\multi_edit\edit_save.php on line 3. <?php include('dbcon.php'); $intakeid=$_post['intakeid']; $firstname=$_post['firstname']; $lastname=$_post['lastname']; $password=$_post['password']; $confirmpassword=$_post['confirmpassword']; $homeaddress=$_post['homeaddress']; $email=$_post['email']; $n = count($intakeid); for($i=0; $i < $n; $i++) { $result = mysql_query("update registration set firstname='$firstname[$i]', lastname='$lastname[$i]',

How can I overwrite the Newer version of DLL with Older version of DLL -

in our application using dll files. sometime need overwrite newer version of dll older version. we referencing dll followig path:c:\windows\downloaded program files so there way overwrite newer version of dll older version @ same location: c:\windows\downloaded program files

jquery - Converting isotime to shorttime in javascript -

i have ajax call returns time e.g 16:06:59 want convert 4:06 pm var mydate = obj[0].time; mydate comes 16:06:59 when try use var date = new date() , gives me todays date . is there solution realize want ? thanks try : function convert24hoursto12(time) { var timearray = time.split(':'); var hours = timearray[0]; var minutes = timearray[1]; var ampm = hours >= 12 ? 'pm' : 'am'; hours = hours % 12; hours = hours ? hours : 12; // hour '0' should '12' var strtime = hours + ':' + minutes + ' ' + ampm; return strtime; } and call it: convert24hoursto12(obj[0].time); see demo here.

javascript - Knockout bindingHandler for comma separated numbers -

i'm building number-heavy app in knockoutjs , want have ability format large numbers they're comma-seperated , nice on eye (xxx,xxx). as you'll see fiddle below, have working wrapping binded value inside of formatting function simple regex problem this overwrites value inside input , inserts ',' underlying value. the large numbers used further down app , prevent nan errors i've had assign data attribute input value containing value no ',' , value gets stored in sessionstorage. i feel have unncessarily bloated html markup , believe want achieve possible bindinghandler binding handler isn't quite there. fiddle: http://jsfiddle.net/36sd9/2 formatlargenumber = function (number) { if (typeof (number) === 'function') { return number().tostring().replace(/\b(?=(\d{3})+(?!\d))/g, ','); } } ko.bindinghandlers.largenumber = { init: function(element, valueaccessor) { var value = ko.unwrap(valueaccessor(

css - Upgrading Rails application to bootstrap3 -

hi have been following michael hartl's book developing rails applications. have reached end , want start using bootstrap3 app i've developed. i have followed instructions on https://github.com/twbs/bootstrap-sass has not worked. gem has installed correctly , can work on local environment changing application.css --> application.css.scss , adding import "bootstrap" statement file along having in custom.css.scss. doesn't seem right , doesn't work when deploy heroku either. the set trying work follows. gem file source "http://rubygems.org" ruby '2.0.0' gem 'rails', '4.0.1' gem 'sass-rails' gem 'bootstrap-sass' gem 'bcrypt-ruby', '3.1.2' gem 'faker', '1.1.2' gem 'will_paginate' gem 'bootstrap-will_paginate' gem 'sprockets', '2.11.0' gem 'pg' gem 'uglifier' gem 'coffee-rails' gem 'jquery-rails' gem '

c# - Redis keyspace notifications with StackExchange.Redis -

i've looking around , i'm unable find how perform subscription keyspace notifications on redis using stackexchange.redis library. checking available tests i've found pubsub using channels, more work service bus/queueing rather subscribing specific redis key events. is possible take advantage of redis feature using stackexchange.redis? the regular subscriber api should work fine - there no assumption on use-cases, , should work fine. however, kinda agree inbuilt functionality perhaps benefit helper methods on api, , perhaps different delegate signature - encapsulate syntax of keyapace notifications people don't need duplicate it. that: suggest log issue doesn't forgotten. simple sample of how subscribe keyspace event first of all, it's important check redis keyspace events enabled. example, events should enabled on keys of type set . can done using config set command: config set notify-keyspace-events kes once keyspace events enabled,

c++ - Handling linear upsampling audio array -

i have real-time signal coming in sample sample, need 4x upsampling on it. have class musicdsp.org: #ifndef td_interpolator_h_included #define td_interpolator_h_included /************************************************************************ * linear interpolator class * ************************************************************************/ class interpolator_linear { public: interpolator_linear() { reset_hist(); } // reset history void reset_hist() { d1 = 0.f; } // 4x interpolator // out: pointer float[4] inline void process4x(float const in, float *out) { float y = in-d1; out[0] = d1 + 0.25f*y; // interpolate out[1] = d1 + 0.5f*y; out[2] = d1 + 0.75f*y; out[3] = in; d1 = in; // store delay } } private: float d1; // previous input }; #endif // td_interpolator_h_included i assume above correct. question how re

regex - Recursive regexp in python? -

i have string: acd (e(fg)h) ij) i need delete text within opened , coresponding closed bracket. in example need delete (e(fg)h) in result want have acd del ij) i try use next code: re.sub(r'\((((?>[^()]+)|(?r))*)\)', r'del', 'acd (e(fg)h) ij)') but python say: sre_constants.error: unexpected end of pattern thanks jerry , devnull! regex module python instead of default re module solved issue import regex >>> regex.sub(r'\((((?>[^()]+)|(?r))*)\)', r'del', 'acd (e(fg)h) ij)') 'acd del ij)'

Plotting two different plots(y axes), sharing the same x in matlab -

considering this question , trying tackling issue 2 separate plots using axes instead of plotyy doesn't work 'boxplot' , 'plot': %%% definition of x=y line axes y2 = 1:6; x2 = 1:6; % plot first data set using boxplot, results in 6 boxes load carsmall; boxplot(mpg,origin) % axes , configure ax1 = gca; set(ax1,'xcolor','r','ycolor','r') %create new axes ax2 = axes('position',get(ax1,'position'),... 'xaxislocation','top',... 'yaxislocation','right',... 'color','none',... 'xcolor','k','ycolor','k'); % plot second data set new axes hl2 =plot(x2,y2,'color','k','parent',ax2); but still dont final plot in right way. know why? there hold on missing before last line.

javascript - jQuery adding and removing classes -

i'm trying create simple piece of code allows move red , blue ball around screen - click on 1 want move use arrow keys. part i'm struggling changing ball focused on, ie moved when press arrow keys. the plan add .active class ball click on, while removing active class other. i've got 2 simple divs, blue div set .active class: <div id="blue" class="active"></div> <div id="red"></div> here's css: div { height: 100px; width: 100px; border-radius: 50%; border: 5px solid gray; margin: 20px; position: relative; } #blue { background-color: blue; } #red { background-color: red; } here's javascript: $(document).ready(function() { $("body").keydown(function(key) { switch(parseint(key.which,10)) { // left arrow key pressed case 37: $('.active').animate({left: "-=10px"}, 1);

java - Find if Entered Password is valid or not? -

this interview question. think code below, works bit , has errors. problem follows - in 1-9 keypad 1 key not working. if 1 enters password not working key not entered. have given expected password , entered password. check entered password valid or not ex: entered 164, expected 18684 (you need take care when u enter 18684 , 164 both taken 164 input) the code above below. public static void main(string[] args){ system.out.println(isamatch("164","18684")); } static boolean isamatch(string actual, string expected) { char faultykey = '\0'; int = 0, j = 0; for(; < expected.length() && j < actual.length(); ++i) { if(actual.charat(j) != expected.charat(i)) { if('\0' != faultykey){ if(faultykey != expected.charat(i)) return false; } else{ faultyk

How to make sure a String matches a Java class name -

using reflection , class.forname(string s) method, there way determine if string matches proper case of class? example: class: testreflection.java string s: testreflection try{ class.forname(s) } catch(classnotfoundexception e){ system.out.println("can't find class: " + s); } this misses classnotfoundexception , throws exception: exception in thread "main" java.lang.noclassdeffounderror: testreflection (wrong name: testreflection) error log: exception in thread "main" java.lang.noclassdeffounderror: reflection (wrong name: testreflection) @ java.lang.classloader.defineclass1(native method) @ java.lang.classloader.defineclass(unknown source) @ java.security.secureclassloader.defineclass(unknown source) @ java.net.urlclassloader.defineclass(unknown source) @ java.net.urlclassloader.access$100(unknown source) @ java.net.urlclassloader$1.run(unknown source) @ java.net.urlclassloader$1.run(unknown source) @ java.security.acc

r - View entire data frame when wrapped in tbl_df? -

tibble (previously tbl_df ) version of data frame created dplyr data frame manipulation package in r. prevents long table outputs when accidentally calling data frame. once data frame has been wrapped tibble / tbl_df , there command view whole data frame though (all rows , columns of data frame)? if use df[1:100,] , see 100 rows, if use df[1:101,] , display first 10 rows. display rows scroll through them. is there either dplyr command counteract or way unwrap data frame? you use print(tbl_df(df), n=40) or of pipe operator df %>% tbl_df %>% print(n=40)

Using selenium to get element by id in python testing -

in html code below: <div class="collapse navbar-collapse" id="b-menu-1"> <ul class="nav navbar-nav navbar-right"> <li><a href="/accounts/login/">sign in</a></li> <li><a href="/accounts/signup/">sign up</a></li> {% if request.user.is_authenticated or logged_in %} <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <span class="glyphicon glyphicon-user"></span><b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="/accounts/manageaccount/">manage account</a

javascript - Sticking Div to Top After Scrolling Past it -

right now, i'm able stick div top after scrolls down 320px wanted know if there way of achieving this. below have code: jquery(function($) { function fixdiv() { if ($(window).scrolltop() > 320) { $('#navwrap').css({ 'position': 'fixed', 'top': '0', 'width': '100%' }); } else { $('#navwrap').css({ 'position': 'static', 'top': 'auto', 'width': '100%' }); } } $(window).scroll(fixdiv); fix5iv(); }); it works, divs above not same height can't rely on 320px . how work without using if ($(window).scrolltop() > 320) can fade in @ top after user scrolls past div #navwrap ? try using offset().top of #navwrap element. way element fixed it's starting position in document, regardless of is. example: function fixdiv() { var $div = $("#navwrap"); if ($(wind

c# - How to remove all the pages from page stack in Windows Phone 7? -

i know how remove old pages page stack. navigationservice.removebackentry(); this remove last entry page stack. but want remove pages form page stack. if click clear button page should cleared. please let me know idea solve this. thanks in advance. this how clear navigationservice backentry without getting exceptions: while(navigationservice.cangoback) navigationservice.removebackentry();

regex - PHP - Get string from Email address -

i have email address: abc123@domain.com i want string " domain.com " php please me! you can use explode , see http://www.php.net/manual/en/function.explode.php . $array = explode("@", "abc123@domain.com"); echo $array[1]; // domain.com

editor - Yank range of lines to clipboard via ':' in vim -

i'm yanking range of lines system clipboard in vim. can 51gg116"+yy . i'd via : notation. can copy "" register via command :51,116y . however, command 51,116"+y doesn't work. how fix last command? :help :y says: :[range]y[ank] [x] yank [range] lines [into register x]. yanking "* or "+ registers possible when |+clipboard| feature included. so answer obviously: :51,116y + your problem try use :y , ex command, if y , normal mode command. and didn't read documentation carefully, or @ all.

java - How do I "control" a pixel array in Android? (Blur) -

i'm trying create simple blur effect on bitmap , although know there algorithms out there already, i'd still understand how work. code have far, there's nothing in there resembles blur algorithm @ moment, wanted know how setpixels method works little better. public void blurtest(bitmap sentbm) { bitmap blurredbitmap = sentbm; int bmwidth = sentbm.getwidth(); int bmheight = sentbm.getheight(); int[] pixels = new int[bmwidth * bmheight]; sentbm.getpixels(pixels, 0,bmwidth,0,0,bmwidth,bmheight); (int = 0; < 200000; i++) { pixels[i] = color.black; } blurredbitmap.setpixels(pixels, 0, bmwidth, 0, 0, bmwidth, bmheight); i've done research on how blur algorithms work , while understand theory behind them, don't know how apply each pixels. example, how pixel being blurred expressed using weight numbers. pixel 2 pixels away center has weight of 0.065 or example

How to update date in mysql -

my code looks this <?php $con = mysql_connect("localhost","root",""); if (!$con) { die('could not connect: ' . mysql_error()); } mysql_select_db("library", $con); $colid = $_post['data']; $count = count($colid); $curdate = date('y-m-d'); for($i=0;$i<$count;$i++){ $tsql ="update transaction set return=$curdate status='1' tid = $colid[$i] "; $tresult = mysql_query($tsql); } if(! $tresult ) { die('could not enter data: ' . mysql_error()); } echo "deleted book successfully\n"; mysql_close($con); ?> and error could not enter data: have error in sql syntax; check manual corresponds mysql server version right syntax use near 'return=2014-04-21 status='1' tid = 1' @ line 2 my requirement when ever got clicked button need execute code i tried using curdate() function getting same error any appreciated return mysql reser

java - query returning amount of rows including ones that were deleted, -

so i'm trying amount of rows exist in mysql table using jdbc using first column reference since amount of rows exist, column on auto_increment but, lets n rows deleted table, new ones inserted , row number new ones keep count in same order, naturally, , when want count number of rows table has, , gettableinfo method returns amount of rows including ones deleted.. how solve ? can done differently this: public int gettableinfo(string tablename, string db, boolean columncount, boolean rowcount) { table = tablename; connection gettableinfoconn = this.getconnect_to_db(db); try { preparedstatement prepstatement = gettableinfoconn .preparestatement("select * `" + tablename + "`"); resultset res = prepstatement.executequery(); if ((columncount == false) && (rowcount == false) || (columncount == null) && (rowcount == false) || (co

sql - Restrict SqlEntityConnection Type Provider to only certain tables -

i writing utility myself needs able access pair of tables in sql database. used sqlentityconnection type provider , rewarded data needed table easy use entities. one thing noticed though startup , compiling of project increased quite lot. suspect because database has on hundred tables , it's compiling , getting data of them opposed 2 need. there way restrict entitytypeprovider referencing needed tables in schema? type private entityconnection = sqlentityconnection<connectionstring="server=server;initial catalog=database;integrated security=sspi;multipleactiveresultsets=true", pluralize = true> let private context = entityconnection.getdatacontext() i have not tried myself, think add new "ado.net entity data model" (edmx) file project, let generate existing database, , delete model every table don't want accessible code. the edmx designer generate *.csdl file can reference localschemafile parameter of sqlentityconnection. you'd

svn - How can I show revisions from tags/branches in the TortoiseSVN log window? -

is possible show of revisions--specifically, revisions created when tags/branches created--in "show log" window? i know can see graphical representation of tag/branch information "revision graph" window, i'd know if can see similar information in log. you can show log repository root (usually 1 level above trunk/branches/tags) , you'll log messages. to that, open repository browser, right-click on top node in left tree view , select show log context menu.

How to use query in Google spreadsheet to select column instead of row? -

please, need !!! i tried =query(a1:e6, "select * d = 'yes'", 0) it select rows in column d has value 'yes'. my question is: how select columns in row 2 has value 'yes'. tried: =query(a1:e6, "select * 2 = 'yes'", 0) but not work :( to query, need double transpose, or use alternative filter. =transpose(query(transpose(a1:e6),"select * col2 = 'yes'",0)) or =filter(a1:e6,a2:e2="yes")

excel - I need to add 3 hours to a date + a time -

i have column each cell has date , time in it 4/12/14 8:35 pm i want add 3 hours time each cell. in end, be: 4/12/14 11:35 pm what's quickest way this? consider =a1+3/24 -– simoco use cell formatting display full date , time -- nazim

Expand clickable area of anchor without affecting position with CSS -

Image
in mobile web application have created there many anchor tags used throughout. anchor tags default have clickable area purely surrounding text. looking try , expand area without affecting position of anchor tag @ all. the black border shows current clickable area , red border shows clickable area prefer. first thing think of add padding, moves tag whole reason i'm asking problem. how can expand clickable area of anchor tags in application without affecting positions? you can use absolute positionned pseudo element increase space link stands. basic demo : a { display:inline-block; position:relative; border:solid; } a:before { content:''; position:absolute; top:-1em; left:-1em; right:-1em; bottom:-1em; border:solid red; } this technique can usefull menus close because submenu on edge.

linux - parse info from log files and quering process table -

i trying check how many log files have been modified in last 10 minutes , list them. want in incriminates of 30. output this: log files modified in last 10 minutes: x list of these files: /var/log/messages /var/log/lastlog /var/log/wtmpp /var/log/cron log files modified in last 30 minutes: x list of these files: .... further, want query process table , following: total # of processes: x number of active user processes user: root: 98 (or many) apache: 65 usera: 33 userb: 23 top 5 processes using memory listing of processes i think can # of log files command: find /var/log/ -name '*.log' -mmin 10 and count them adding " | wc -l" # but errors when try that. any suggestions on how go appreciate. note, should write -10 mmin. find /var/log/ -name '*.log' -mmin -10

How to connect Oracle Advance Queue (AQ) from Oracle ADF? -

how can connect oracle advance queue(aq) oracle adf. want display advance queue(aq) data (i.e. payload xml) in table format adf ui page.is there adapter available that? you might want use message-driver beans (as oracle aq implementation of jms). think these links you: oracle aq message-driven beans (here you'll find sample of adf fusion application) how connect oracle aq mdb using mdb adf

html - CSS Responsive issue with iPad Mini in NON-landscape mode (Vertical) -

i'm having issue media query. set first on @ 770px, re-size without putting sidebar underneath main content. i set second media query @ 740 (it @ 450, changed 740 ipad mini), thinking send side-bar underneath main content. (meaning if held ipad mini vertically, same on iphone). this works on iphone, on ipad mini keeps 770px settings when viewed vertically (non-landscape mode). what doing wrong? assumed 740 high enough max-width, given 770 works landscape mode. here site: http://www.insidemarketblog.com and here's code html: div class="container"> <div class="columns"> <div class="content"> <div id="post-1" class="post_box grt top" itemtype="http://schema.org/article" itemscope=""> <div id="comments"> <div class="prev_next"> </div> </div> <div class="sidebar" style="height: 560p

c - menu file did not played when user play "*",Asterisk-11.5.1 Confbridge -

dialout user pickuped/answer call , merge confbridge admin getting "ringtone" asterisk-11.5.1 confbridge . ? expected : admin user (a 7002) ,of current conference dailout , invite user (b 7001) join confernece. b picked call , joined confbridge. , b should communincate each other , press "*" listen conf menu file. originale: b can listen menu press "*"; can not talk b . press * ,but menufile did not played . getting "ringingtone". why, ? c**onference bridge name users marked locked? ================================ ====== ====== ======== 1010101 2 1 unlocked** *cli> confbridge list 1010101 channel user profile bridge profile menu callerid ============================= ================ ================ ================ ================ sip/7002-00000009 default_bridge conf-admin-sub-dialout7002 sip/

javascript - Call link in mobile site not working -

in mobile site, used <a href="tel:+1800229933">call free!</a> making call specified number device.but not working in of devices.thanks in advance. you should use callto: example: <a href="callto:+1800229933">call free!</a>

python - how to create a popup while loading data through method? -

i have method needs few second load data. these few second want display popup. problem python freezes starting load-method. my first idea draw progressbar in qteditor , hide it. , then: def load_data(self): self.progressbar.sethidden(false) [...load data...] the progressbar show, after load data. thought if "outsource" "sethidden" work: self.start.connect(self.load_data) def pre_load_data(self): self.progressbar.sethidden(false) self.start.emit() #signal created myself def load_data(self): [...load data...] but again progressbar created after process finished. tried make popup in other *.py file, , import it: popup.py: class popup(qtgui.qdialog): def __init__(self): qtgui.qwidget.__init__(self) self.pp=ui_loading() self.pp.setupui(self) and show popup before calling load_data-method: def test(self): self.bla = popup.popup() self.bla.show() self.load_data() the popup show inmediatly, empty. after load_data fi

regex - How to parse/substitute part of a string given a starting matching condition in python? -

assume have string text='bla1;\nbla2;\nbla3;\n#endif\nbla4;' i want define method removes '\n' except if '\n' preceded string starting '#' or '\n' follows '#', result of process should be: text2='bla1;bla2;bla3;\n#endif\nbla4;' is there simple way in python using regex? (note: clear me how avoid \n followed #, using negative lookbehind, i.e. r'\n+(?!#)' challenge how identify \n preceded string starting #) the challenge is: how deal positive lookbehind variable-length strings in python? find : (#[a-z]+\\n)|\\n(?!#) and replace : '\1' output : bla1;bla2;bla3;\n#endif\nbla4; demo here : http://regex101.com/r/uo8wh2 this keep \n newline chars have preceding word starting # or followed hash. hth

asterisk - Originating VoIP call using AsterNET in C# -

i try doing mconnection.sendaction(new originateaction() { channel = "sip/201test", exten = "401", context = "201", priority = "1", callerid = "201", timeout = 30000 }); where 201 , 401 extensions connected local network. trying call 201 401. doing wrong? edit: i have test application button "call" i have 2 extensions connected server - 201, 401 i want call 201 401 on "call" button click channel name selected randomly not sure if right. update: ``` mconnection.sendaction(new originateaction() { channel = "sip/401", exten = "401", context = "default", priority = "1", callerid = "201&qu

c++ - Using a map as "Phonebook" -

i have code similar this enum days { monday, tuesday, wednesday, thursday, friday, saturday, sunday }; typedef void (*dailyfunction)(int); namespace dailyfunctions { void monday(int somedata); void tuesday(int somedata); void wednesday(int somedata); void thursday(int somedata); void friday(int somedata); void saturday(int somedata); void sunday(int somedata); } and somewere else in code use switch statement assign 1 of dailyfunctions dailyfunction ptr. when typing (more or less) same switch statement third time, had idea, great have map std::map<days, dailyfunction> myphonebookmap which allow me this: dailyfunction function_ptr = myphonebookmap[weekday]; to me seems, optimal place define such map in namespace dailyfunctions under function-declarations but how can define const map there (since shouldnt change) , populate @ same time? you can use boost function boost::assign::map_list_of or use copy constructor initialize c

c++ - GLSL - When and where is the vertex and fragment called? -

i want know when vertex , fragment shader called in opengl loop. @ end of glutdisplayfunc() or glutmainloop(), or @ every vertex draw call? , vertex , fragment consecutively called 1 after other(ie: vertex fragment), or different times? say have following snippet of code: glpushmatrix(); glrotatef(rot,0.0f,1.0f,0.0); gltranslatef(0.0f,0.0f,25); glcolor3f(0.0,0.0,1.0); drawsphere(4,20,20); // draw triangles glcolor3f(1.0,0.0,0.0); gltranslatef(0.0f,0.0f,5); drawsphere(4,20,20); // draw triangles glpopmatrix(); does vertex shader called after each vertex call, reads current matrix on top of stack, send pre-defined modelview matrix uniform vertex shader? when fragment shader run? is @ end of glutdisplayfunc() or glutmainloop(), neither, because glut is not part of opengl. it's library (for creating simple opengl applications). or @ every vertex draw call? from programmers point of view it's not specified when happens e

Unable to record my call in Android 4.4 -

i not able record call in android 4.4 . checked few applications googleplay don't work either. in application use mediarecorder.audiosource.voice_call doesn't work. anyone knows solution? see link - audiosource-voice-call-not-working-in-android-4-0-but-working-in-android-2-3 after lot of search found manufactures have closed access such function because call recording not allowed in countries. if finds such question , solution other way post on here may helpful many because many people have same issue.

django - Remove (filter out) objects from queryset -

i'd remove 3 objects queryset. working of list, im pretty sure there should better way queryset api . didnt figure out how yet: what i'm doing: ranks = rank.objects.all() remove_ranks = ['field marshall', 'military attache', 'mercenary recruiter'] new_ranks =[] rank in ranks: if not rank.name in remove_ranks: new_ranks.append(rank) how can using django api ? try remove_ranks = ['field marshall', 'military attache', 'mercenary recruiter'] rank.objects.exclude(name__in=remove_ranks) what do? .exclude opposite of .filter name__in equivalent of in-statement in sql this should produce sql query along line select * rank name not in ('field marshall', 'military attache', 'mercenary recruiter')

javascript - Error when adding a new member to JSON -

(i checked out @ least couple dozen posts on error , made few changes see fit no avail) so, started out simple var : var _jsonstr = '{"hotspots:":[]}'; then, parsed it: var _jsonobj = json.parse(_jsonstr); in other part of html, values variable id , x , , y , assign values _jsonobj follows: _jsonobj.hotspots[0].id = id; // error! _jsonobj.hotspots[0].xval = x; _jsonobj.hotspots[0].yval = y; and i'd end set of id , x , y value pairs in json like: var _jsonobj = { "hotspots": [ { id: 0, xval: 25, yval: 50 }, { id: 1, xval: 80, yval: 120 }, { id: 2, xval: 39, yval: 91 }, ... ] }; hate admit couldn't figure out why keep getting error says, "unable set property 'id' of undefined or null reference" commented above. sounds me doing wrong adding new member json object don't see why so. you getting error because _jsonobj.hotspots[0] undefined . this should fi

Call function after a period of time in C# -

i have c# code call function like: private void cmdcommand_click(object sender, eventargs e) { m_socclient.close(); } but want m_socclient.close(); function called after maybe 30 second. possible? yes, using async / await feature: private async void cmdcommand_click(object sender, eventargs e) { await task.delay(30000); m_socclient.close(); } you can using thread.sleep block ui thread , window won't responsive until task finished.

ios - JSON Serialization Returns Null -

in our project taking values json services most questions asked many times not find solution. here code block: nsdata *urldata=[nsurlconnection sendsynchronousrequest:request returningresponse:&response error:&error]; nsstring *responsedata = [[nsstring alloc]initwithdata:urldata encoding:nsutf8stringencoding]; nslog(@"response ==> %@", responsedata); nserror *error = nil; nsdictionary *jsondata = [nsjsonserialization jsonobjectwithdata:urldata options:nsjsonreadingmutablecontainers error:&error]; nsstring* userid = [jsondata objectforkey:@"user_id"]; nslog(@"success: %ld userid: %ld",(long)success, (long)userid); log: response code: 200 response ==> {"user_id":4} success: 0 userid: 0 as can see want convert json object string when printout content of jsondata returns null guess have issue jsonserializaton. can suggest solution? thanks, umit just test following code, it's ok.

google spreadsheet - split() function skips blanks -

in a1 cell have a,b,c,,e . want split cell 5 cells: a , b , c , , e this formula =split(a1,",") splits 4 cells a , b , c , e , skips on blank. how tell split "properly"? i don't think can specify directly, though here workaround: add delimiter character string. replace , ,| now when split , , know sure empty columns have character (in case | ) use replace substitute delimiter | blank string since output of split array, need use arrayformula here final formula like =arrayformula(substitute(split(substitute(a1,",",",|"),","), "|",""))

how to receive file in java(servlet/jsp) -

hi making communication protocol. on web server send 1 file curl(in c# post http request). task been done. how should receive file java on web server gone through this article . file downloading. want receive file java. this link may .. have provide multiprt form data .. http://www.journaldev.com/2122/servlet-3-file-upload-using-multipartconfig-annotation-and-part-interface

cordova - SVG image as background image in windows phone 8 and phonegap -

i using svg image background in phonegap project windows phone8 not showing. following code .loyaltystar { position:absolute; margin-top:3px; background:url(../img/available-icon.svg) no-repeat; width:21px; height:21px; } <li><a href="a.html" class="loyaltystar"></a></li> is phonegap 2.4 supports svg windows phone 8. got solution removed xml start tag image , working ...

actionscript 3 - RandomGenerated Map with Path from start to end -

i wanted randomly generate new 2d array (my map) , ensure has @ least 1 path start point end point. right have static grid , have pathfinding algorithm working properly. question best approach develop this? easiest way create grid , iterate through ensure path open? i think worst-case scenario randomly generate 1 , path find if false returned randomly generate another, inefficient. please help!

java - How to get jackson to ignore non-DTO objects -

we upgraded glassfish jersey 2.7 sun jersey implementation. when did jackson started trying deserilize our domain objects. in our case isn't want. have domain setup domain objects never directly sent out via web services. transformed in dto , sent out. call return response.ok(new somefoobardtoobject(somefoobardomainobject)).build() and use work previous version of jersey/jackson. more date code we're getting errors following: conflicting setter definitions property "preferreditem": com.foo.domain.foobar#setpreferreditem(1 params) vs com.foo.domain.foobar#setpreferreditem(1 params) even though never try send out actual domain object. how tell jackson @ objects received or sent via web service. here web service causing issue i've simplified down this. if take out restaurantitemdto restaurantitemdto method parameters works, if keep in there doesn't. restaurantitemdto has base types in it's fields. way references domain object through construct

Formatting DateTime in C# -

i trying output datetime in 12 hour format. works , breaks. code: while (myreader.read()) { console.writeline("date before formatting = " + myreader["date"].tostring()); datetime dt = datetime.parseexact(myreader["date"].tostring(), "yyyy/mm/dd hh:mm:ss", cultureinfo.invariantculture); string format = "mm/dd/yyyy hh:mm:ss tt"; console.writeline(myreader["rxnumber"].tostring() + "\t\t" + dt.tostring(format)); } output: connection opened date before formatting = 2013/12/26 11:26:08 12/26/2013 11:26:08 date before formatting = 2013/12/26 09:02:01 12345 12/26/2013 09:02:01 am date before formatting = 2013/12/26 09:04:29 123456 12/26/2013 09:04:29 am date before formatting = 2013/10/28 10:19:26 10/28/2013 10:19:26 date before formatting = 2014/02/14 12:25:57 7000006 02/14/2014 12:25:57 am date before formatting = 2014/02

excel - How to deleting selected range of cells when range is dependent on a variable? -

i want delete cells in range g123:p10000 , value of 123 in g123 keeps on changing, how can provide variable while providing range. below can used 1 time, want use multiple times based on value in variable named 'count' changes every run deletes range only range("g123:p10000").select selection.clearcontents i tried below, not working count = activesheet.range("a1").end(xldown).row range("g$count:p10000").select selection.clearcontents what need .offset() , .resize() modifications range. ... count = countrows(activesheet.range("a1")) activesheet.range("g1").offset(count,0).resize(10000-count,1).clearcontents with public function countrows(byval r range) long if isempty(r) countrows = 0 elseif isempty(r.offset(1, 0)) countrows = 1 else countrows = r.worksheet.range(r, r.end(xldown)).rows.count end if end function

Failed to extract specific tables from web onto spreadsheet in Excel VBA (Mac) -

basically, have following program, allow me obtain stock prices of particular stock, "700" in below example.the stock prices appear in particular table on webpage. in pc computer, able use .webselectiontype = xlspecifiedtables .webtables = "4" to pick out specific tables want webpage. on mac, not , ran run-time error 438 : object doesn't support property or method . annoying. removed 2 lines code. problem that: not extract particular stock prices table web now. can show me how can overcome ? sub getstockdatatest() getgooglestockhistory 700 end sub sub getgooglestockhistory(gint long) 'load google stock hisotry activesheet.querytables.add(connection:="url;https://www.google.com.hk/finance/historical?q=hkg%3a" & format(gint, "0000") & "&num=200", destination:=thisworkbook.sheets("query").[a1]) .name = "webquery" .refreshstyle = xloverwritecells .

excel vba - Loop finishing with error -

i need each row has phrase " total" in it, insert rows above , below it, format other cells in , around same row, remove phrase " total" cell, , repeat process other rows in report. the macro i've developed, once it's found , replaced of instances of " total", run-time error '91': object variable or block variable not set. i finish loop without ending error has executed on multiple sheets. here meat of code: 'employersummariesaddedforregionsontabs macro dim foundcell range, lastcell range dim firstaddr string range("d3:d3000") range("d3").select set lastcell = .cells(.cells.count) end set foundcell = range("d1:d3000").find(what:=" total", after:=lastcell, lookin:=xlvalues, lookat:=xlpart, _ searchorder:=xlbyrows, searchdirection:=xlnext, matchcase:=false, searchformat:=false) if not foundcell nothing firstaddr = foundcell.address end if until foundcell nothing set fo

c# - Format String for SQL Entry -

the user enters date mm/dd/yyyy in string , needs formatted in c#/asp.net insertion sql server 2008 r2 record. understand should convert datetime , parameterize query, can't find example of this. what easiest way this? use datetime.parse , in query add re turned datetime parameter. var date = datetime.parse(thestring); sqlcommand cmd = new sqlcommand("insert xxx (thedatefield) values(@param1)", con); cmd.parameters.addwithvalue("param1", date); //execute query , want.

c++ - Search through arrays to find seperate instances of a word -

this assignment in advanced c++ class, we're going on pointers , dynamically allocated arrays, though doesn't seem trouble lies... function header, quote, words, , count important arrays, numwords holds count of how many elements in quote array. void countwords ( char ** quote, char **& words, int *& count, int numwords ) { variables , such, of arrays being passed pointer main. char ** temp = nullptr; int * itemp = nullptr; int wordcount = 0; int quotecount = 0; what follows priming read for loop coming up. i'm creating 2 dynamically allocated arrays, 1 store new found instances of word in quote array, , store count of how many times word appeared in quote array. seems working fine, don't how large (code bloat) advice started differently excellent. first dynamic array char's. temp = new char * [wordcount + 1]; (int z = 0; z < wordcount; z++) { temp[z] = words[z]; } temp[wordcount] = new char[ strlen(

ios - How to create an if statement if segment is not selected? -

i want create statement says if (segmenttitle.selectedsegmentindex == not selected) { segmenttitle.selectedsegmentindex == 0; } what not selected in c code? if read docs uisegmentedcontrol find answer: if (segmenttitle.selectedsegmentindex == uisegmentedcontrolnosegment) { segmenttitle.selectedsegmentindex = 0; }

javascript - Remove Controls in MediaElement player. Where to add/change the code -

this basic question change or add code. want remove of controls on media element player. there information everywhere on internet in summary states. you can control buttons appear on control bar setting {features:['playpause','backlight']} array etc... my question go change or insert code {features: etc... i see folders media front/players/osmplayer/player/templates etc. , there several src query-ui js folders , files. can point me in right direction. if have ever changed features of player can ask folder , file did go to insert or alter code. just add features want/need in own custom mejs initialization script : $('video,audio').mediaelementplayer({ features:['playpause','progress','volume'], alwaysshowcontrols: false }); see jsfiddle

c# - Anonymous subclass -

how create instance of anonymous subclass in c# ? let have base class bclass , want create instance of sublclass additional method , property? how possible do? anonymous classes (aka anonymous types ) can not extend class or implement interface. if need inheritance or implement interface need create named class.

c++ - boost unit test fails with error - unknown location(0): fatal error in "MyCheckTest": -

i'm trying run unit test using boost gives me error when run test -> " unknown location(0): fatal error in "mychecktest":" error not mention line test failing.. i'm not able figure out , hence sharing code: // function.hpp #pragma once #include <boost/archive/text_oarchive.hpp> #include <boost/serialization/string.hpp> #include <boost/serialization/shared_ptr.hpp> #include <boost/serialization/serialization.hpp> #include <boost/serialization/access.hpp> #include <boost/smart_ptr/make_shared.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/serialization/export.hpp> struct function { std::string id, name; private: friend class boost::serialization::access; template<class archive> void serialize(archive &ar, const unsigned int /*version*/) { ar & id; ar & name; } public: function(void); typ

python - How do setup virtualenv and dependencies in pycharm? -

Image
i using virtualenv on remote machine , want simulate same env on mac can use pycharm further development. my virtualenv in path , "~/venv" i have created ~/.pycharmc following contents(as suggested in " how activate virtualenv inside pycharm's terminal? ") source ~/venv/bin/activate /bin/bash --rcfile ~/.pycharmrc works fine , creates necessary venv, not working in pycharm environment(attaching image @ end) what missing ? go settings > project interpreter > python interpreters > add navigate ~/venv/bin , select python binary. pycharm notices virtual environment , supports completely. make sure select added environment projects interpreter.