Posts

Showing posts from April, 2014

python - Is there any ipdb print pager? -

i using ipdb debug python script. i want print long variable. there ipdb pager more or less used in shells? thanks you might want create function accepts text, puts text temporary file, , calls os.system('less %s' % temporary_file_name) . to make easier everyday use: put function file (e.g: ~/.pythonrc ) , specify in pythonstartup . alternatively can install bpython ( pip install bpython ), , start bpython shell using bpython . shell has "pager" functionality executes less last output.

crc - How long should a checksum be? -

tcp segments include checksum field of 16-bits , ip datagrams , udp packets. @ link layer, crc checksum 4 bits (for 802.3 , 802.4). on extreme part of spectrum, computing parity bit might yield lot of false-positive, packet looks valid in fact not, because number of bits have been altered. on other hand, having 16-bit checksum when 4 bits suffice waste of memory/bandwidth/money. how evaluate how many bits checksum should be? ps: i have taken internet stack example, applies protocol/software really. ps2: not sure forum use. first, quick nomenclature correction - checksums , crcs 2 different approaches trying solve same problem: detect bit errors occurred during data transmission in noisy channels. in general crcs more powerful detecting errors @ expense of more complexity. selecting right error detection scheme requires knowledge channel (e.g. error probability) , noise characteristics (e.g. impulsive, bursty). there papers out there problem analyzed in detail , g

http - chunk data logging in node.js -

i have following function in node.js inside http.request() res.on('data', function (chunk) { var sr="response: "+chunk; console.log(chunk); }); i in console <buffer 3c 3f 78 6d 6c 20 76 65 72 73 69 6f 6e 3d 22 31 2e 30 22 20 65 6e 63 6f 64 69 6e 67 3d 22 75 74 66 2d 38 22 20 3f 3e 3c 72 65 73 75 6c 74 3e 3c 73 75 63 ...> but when use this: res.on('data', function (chunk) { var sr="response: "+chunk; console.log(sr); }); i proper xml response this: responose: .....xml responose..... i don't understand why need append string output proper response. , meant response generated in first code? chunk buffer , node's way of storing binary data. because it's binary data, need convert string before can show (otherwise, console.log show object representation). 1 method append string (your second example that), method call tostring() on it: console.log(chunk.tostring()); how

android - Phonegap - navigator.app.backHistory() not working on HTML back button -

in app using phonegap 2.6.for button, using following function document.addeventlistener("backbutton", onbackkeydown, false); function onbackkeydown() { alert("hello"); navigator.app.backhistory(); } document.addeventlistener('deviceready', ondeviceready, true); the above function works fine when click on device's hardware button . when click on button not working. i have designed button below: <a class="ui-link" href="#" rel="external" onclick="onbackkeydown()"> <img src="images/icon-back.png" alt="phone" border="0"> </a> but button working fine navigator.app.exitapp(); (application exit). //working fine function onbackkeydown() { navigator.app.exitapp(); } //not working function onbackkeydown() { navigator.app.backhistory(); } but not working navigator.app.backhistory(); . i have tried 3 separate things when fac

c - Include a file multiple times with different macros -

i got file contains generic methods working arrays of different number types (the basic ideas described in pseudo-generics in c ). type can specified setting type macro. looks (just part of it): array_analyzers.c : #ifndef type #error type isn't defined #endif #define concat(x, y) x ## y #define get_name(base, type) concat(base, type) type get_name(get_minimum_, type) (type nums[static 1], int len){ type min = nums[0]; (int = 1; < len; i++) { if (nums[i] < min) { min = nums[i]; } } return min; } #undef concat #undef get_name #undef type now, created header file looks this: array_analyzers.h : #ifndef type #error type isn't defined #endif #define concat(x, y) x ## y #define get_name(base, type) concat(base, type) type get_name(get_minimum_, type) (type nums[static 1], int len); #undef concat #undef get_name #undef type finally, want use main.c : #include <stdio.h> #define type int #include "

postgresql - insert bash-variables in psql-command -

i'm going crazy while trying insert bash-variables in psql commands connection paramters variables in command itself. following example works properly: psql -u postgres -h localhost -p 5432 -c "create database testdb encoding='utf8' owner=postgres tablespace=pg_default template=template_postgis connection limit=-1;" now i'm trying exchange each parameter through variable, held in special config-file. non-working example: dbserver=localhost dbport=5432 dbowner=postgres dbname=testdb dbtemplate=template_postgis dbtablespace=pg_default psql -u '$dbowner' -h '$dbserver' -p '$dbport' -c "create database '$dbname' encoding='utf8' owner='§dbowner' tablespace='$dbtablespace' template='$dbtemplate' connection limit=-1;" i've tried several quotings, backquotes , escape-slashes smhow still won't work. in advance, knutella this works... of quotes not needed: psq

r - How to order columns in a matrix based on final column values? -

i'm trying reorder existing matrices in r based on final column values can't seem find solution. i've tried order(), no luck. i'm overlooking something. ideas? instance, let's create matrix 5 columns of data: > <-matrix(100+rnorm(50),10,5) > [,1] [,2] [,3] [,4] [,5] [1,] 101.26878 99.36657 99.32874 99.46449 101.46698 [2,] 102.28284 102.62506 100.21430 100.54780 100.14608 [3,] 99.25180 100.93911 101.31455 99.92939 99.87537 [4,] 99.69423 99.17830 99.20230 99.42162 100.70614 [5,] 99.03745 99.95904 100.85773 98.39691 100.84777 [6,] 100.09040 101.66841 98.73320 97.41576 99.36144 [7,] 99.94181 100.18932 101.26947 99.81551 99.30574 [8,] 99.15694 98.24990 98.81500 99.26529 100.72547 [9,] 100.52822 99.43562 101.73370 98.32482 99.30498 [10,] 100.37140 99.54621 99.37048 99.43794 101.28328 how reorder columns based on final values , save results in matrix? instance, column [,5] has highest fin

c# - How to use try catch error for sql query timeout? -

how can use try catch if there error in connection sql query in c#? if use simple code below work time takes error occur long. how can try catch handle error quicker? try { //sql command } catch { //display connection error } try-catch catch exception occurs, don't except catch timeout exception before timeout occurs. sqlcommand , default timeout 30 seconds , can change setting commandtimeout property: try { var command = new sqlcommand("..."); command.commandtimeout = 5; // 5 seconds command.executenonquery(); } catch(sqlexception ex) { // handle exception... }

html - Background images and SEO -

at moment have on website images defined in css file background image. the code looks this. the html: <a href="http://domain.com" title="website title" class="image"></a> the css: .image { background: url("../img/deelnemende-organisaties/arcadis.png") no-repeat; } due other css3 effects background isn't possible change background normal <img> tag. now wondering best way use background images , keeping seo ranking high possible. i saw solutions as: putting text <a> tag , hiding css text-indent: -9999em only put title attribute on tag text in it placing transparent in tag same title tag leave have in example , building called image sitemap in xml file now i'm not sure best solution , don't wanna screw seo ranking doing call illegal. i saw solutions as: - putting text tag , hiding css text-indent: -9999em - put title attribute on tag text in it. - placing transp

mvvm - WPF Passing Multiple Parameters on Click of Checkbox -

following xaml: <checkbox name="checkboxnofindings" content="no findings" command="{binding disablertecommand}" commandparameter="{binding path=content}" grid.row="1" grid.column="1" margin="2,5,0,3" /> i want pass both ischecked , content property values command parameter , access vm. vm code: private void disablerte(object args) { if (null != args) { string rtename = args.tostring(); } } actual requirement is, on check chekbox, textbox should disabled , content of checkbox should applied text of texbox. , opposite side , on uncheck checkbox textbox should enabled , text should empty. any solution scenario? hmm, way want done, seems bit odd me. why don't implement "easy way" in vm? e.g. public class checkboxexamplevm : viewmodelbase //assuming have such base class { private bool? _ischecked; public bool? ischecked { { return _i

How do I write this Powershell Function More Efficently? -

i.ve come @ many different ways , looked on alot of sites efficient powershell scripts still use making script more efficient...it uses 3-4% of cpu. main drag on processor mainlogic function. nested in while($true) loop @ start of body of script , runs time...when parameters in mainlogic function change function breaks , if statements tested in body of script. i'm trying learn how write more efficient code ...im practicing lisp developer , think lesson on powershell efficiency . i've rewritten script 3 times , still need making better...i see windows process use no cpu , run time , smart code. i'd love good. need in script\i have test things tested in script. commented alot aid in helping me ive tried these things: am using right construct situation? i've come @ 1 many way's...i think there might better mathematical approach....i'm learning linear algebra me this. am doing many or unnecessary operations? that's main question....could use new ide

database - Asp-Classic ADODB Recordset missing Records -

one of simplest components in website stopped working 1 day other without changes in code. 'connection declaration connection set rs = server.createobject ("adodb.recordset") rs.open "select * tablename order id desc", connection, 1, 3 while not rs.eof 'writing table records in db 'simplified code %> <tr><td><%=rs("id")%></td><td><%=rs("description")&></td></tr> <% rs.movenext wend in database have verified extraordinary number of 30 records :( when above code executed see 2 of them this tells me 2 things, first: tablename correct , connection database established second: table-generation in correct i have smaller testing-system. there exact same code on sample database produces expected results. unfortunately have no means of "instant-access" main page "debugging purposes" is there known bugs adodb recordsets losing rec

c# - Is there a way to get a System.Configuration.Configuration instance based on arbitrary xml? -

i'm trying unit test custom configurationsection i've written, , i'd load arbitrary configuration xml system.configuration.configuration each test (rather put test configuration xml in tests.dll.config file. is, i'd this: configuration testconfig = new configuration("<?xml version=\"1.0\"?><configuration>...</configuration>"); mycustomconfigsection section = testconfig.getsection("mycustomconfigsection"); assert.that(section != null); however, looks configurationmanager give configuration instances associated exe file or machine config. there way load arbitrary xml configuration instance? there way i've discovered.... you need define new class inheriting original configuration section follows: public class myxmlcustomconfigsection : mycustomconfigsection { public myxmlcustomconfigsection (string configxml) { xmltextreader reader = new xmltextreader(new stringreader(configxml));

concurrency - How to find Future implementation in scala.concurrent? -

Image
i trying understand happens, when call val f = scala.concurrent.future {... // body function } the code of object future defines apply methods follows: def apply[t](body: =>t)(implicit execctx: executioncontext): future[t] = impl.future(body) unfortunately not see impl defined in code (and does). question impl defined. impl package future object borrows implementation class . since future object lives in same concurrent package address impl package effortlessly (no explicit imports required)

java - jsf use classes from different project -

i have 2 projects. 1 dao , 1 jsf stuff. when try enum dao project displayed on jsf page, not work. error occurs java.lang.noclassdeffounderror , although dao project referenced in jsf project. have register dao project in web.xml? if yes, how manage this? here's jsf code: <h:selectonemenu id="type" value="#{calendarcontroller.type}"> <!-- use property name not method name --> <f:selectitems value="#{calendarcontroller.typevalues}" /> </h:selectonemenu> the bean: @managedbean @requestscoped public class calendarcontroller { ... private type type; ... the enum dao project type, not found during deployment.

export excel with python using xlwt and adjusting width -

this question has answer here: python xlwt - accessing existing cell content, auto-adjust column width 6 answers i have exported list using xlwt : response = httpresponse(mimetype="application/ms-excel") response['content-disposition'] = 'attachment; filename=countries.xls' wb = xlwt.workbook() ws1 = wb.add_sheet('countries') ws1.write(0, 0, 'country name') ws1.write(0, 1, 'country id') countries = country.objects.all() index = 1 country in countries: ws1.write(index, 0, country.country_name) ws1.write(index, 1, country.country_id) index +=1 it generate excel file list of countries problem columns of sheet not adjusted data generated. there solution adjust columns ? there's no built-in way adjust column width data inside using xlwt . the question asked here, i'll refer you: py

constraints - MYSQL UNIQUE for date part of a date field -

i have field sync_date (type datetime) in table visit . sync_date can not repeat in same day. so, have idea have sync_date unique field. doesn't work case because don't want takes account hour part. for example today can have this: sync_date = '2013-05-14 08:45:00' today mysql shouldn't admit same '2013-05-14' anymore tomorrow can happens.

is :checked not working while using Jquery 1.7 -

look @ simple code html <input type="checkbox" id="check" >&nbsp;<span id="rm">remember me</span> <span id="ok">okay!</span> css #ok{ position:absolute; font:italic bold 14px century; color:green; margin-left:3px; margin-top:2px; display:inline-block; opacity:0; } jquery if($('#check').is(":checked")) { $("#ok").css("opacity",1); } http://jsfiddle.net/milanshah93/4hf9t/ it not working when check box. your checkbox not checked on page load. although can - $("#check").on('change', function () { if ($(this).is(":checked")) { $("#ok").css("opacity", 1); } else{ $("#ok").css("opacity", 0); } }); demo

c# - Regex: how to get words, spaces and punctuation from string -

basically want iterate through sentence, example: string sentence = "how day - andrew, jane?"; string[] separated = separatesentence(sentence); separated output following: [1] = "how" [2] = " " [3] = "was" [4] = " " [5] = "your" [6] = " " [7] = "day" [8] = " " [9] = "-" [10] = " " [11] = "andrew" [12] = "," [13] = " " [14] = "jane" [15] = "?" as of can grab words, using "\w(?<!\d)[\w'-]*" regex. how separate sentence smaller parts, according output example? edit: string doesn't have of following: i.e. solid-form 8th, 1st, 2nd check out: string pattern = @"^(\s+|\d+|\w+|[^\d\s\w])+$"; string input = "how 7 day - andrew, jane?"; list<string>

hash - How to "EXPIRE" the "HSET" child key in redis? -

i need expire keys in redis hash, older 1 month. this not possible , sake of keeping redis simple . quoth god: hi, not possible, either use different top-level key specific field, or store along filed field expire time, fetch both, , let application understand if still valid or not based on current time.

Compare date via shell script -

i have text: aaaaaaaaaaaaaaaaaaaaddddd sadasdafnsdfoisjhpfnsf dasnfdfmsdf until: thu apr 29 19:41:02 eest 2021 dasd asdasmda[mfiun[hg[sm df, dfmsdf[ismdfsdfsd,flsdfsdf****************** i have parse date text , after have compare today , if greater otherwise have else , have write in shell script not well. can give me example how it. thanks in advance. i in 2 steps. (it done in one): 1, date string 2, comparison e.g.: kent$ d=$(echo "aaaaaaaaaaaaaaaaaaaaddddd sadasdafnsdfoisjhpfnsf dasnfdfmsdf until: thu apr 29 19:41:02 eest 2021 dasd asdasmda[mfiun[hg[sm df, dfmsdf[ismdfsdfsd,flsdfsdf******************"|grep -o '[a-z].*[0-9]') check var d: kent$ echo $d thu apr 29 19:41:02 eest 2021 now compare date today. need convert both dates seconds comparison: kent$ echo $(($(date -d"${d}" +%s)-$(date +%s))) 251171977 i printed result of above command out. in case, assign var. or check result directly. if >0 means date in text

java - Prevent Hibernate schema changes -

i new hibernate , having issue configuration. trying setup read-only connection preexisting oracle database. not want hibernate execute dml/ddl , alter database schema, yet every time try deploying project, message see: info: updating schema severe: unsuccessful: create table willoem.sample_info (sample_id varchar2(255) not null, cell_line varchar2(255), study_id varchar2(255), primary key (sample_id)) severe: ora-00955: name used existing object no damage being done here, since table creation failed, don't want create situation data can lost. how can configure hibernate act in read-only manner? can prevent statement execution completely, without adding new oracle user lacks privileges? here current hibernate configuration: <bean id="datasource" class="org.springframework.jdbc.datasource.drivermanagerdatasource"> <property name="driverclassname"><value>oracle.jdbc.oracledriver</value></property> <

database - awk - print only first line of duplicates and the line below it -

i have large database file needs manipulation. need avoid duplicate field 1 delimited '|' for: -- title1 | title2 |t3 |title4|title5 ----------|----------|-----|------|--------------- -- data1 | same | | | blah blah eligible | x1 data1 | same | | blah | blah eligible | x2 data1 | same | | blah | blah blah eligible | x2 data2 | same | | | blah blah eligible | y1 data2 | same | | blah | blah eligible | y2 data2 | same | | blah | blah blah blah blah eligible | y2 data3 | same | | | blah blah eligible | z1 data3 | same | | blah | blah eligible | z2 data3 | same | | blah | blah blah blah blah eligible | z2 the code using is begin{ fs = "|" } { count[$1]++; if (count[$1] == 1) first [$1] = $0; if (count[$1] > 1) print first[$1] nr==1; } but gives me output: -- title1 | title2 |t3 |title4|title5 ----------|----------|-----

c - Why is strcpy(strerror(errno),"Hello") not copying "Hello",but {ptr=strerror(errno);strcpy(ptr,"Hello");} does? -

please explain what's going on in following program. i checked out addresses returned strerror(errno) @ beginning , end of program , confirms returns same address each time.then once sure of this,in first case proceeded assign same address ptr , copy string "hello" using strcpy() .in case ii,i tried copy "hello" directly address returned strerror(errno) .i had odd findings.i'll appreciate if explain following: in case one,i copied "hello" ptr , successful in subsequent printf() , ptr prints hello .but then, when passed strerror(errno) instead of ptr printf() ,it prints old error message.how possible ptr points 1 message strerror(errno) points message when both addresses same?i verified both addresses same , expect copying "hello" ptr should same copying return of strerror(errno) .to doubly check discrepancy,then tried copy "hello" directly strerror(errno) doesn't work time , prints same old error strin

Unclear why this coin change algorithm works -

i worked yesterday on getting coin changing algorithm work. it seems me that, first, makechange1() calls getchange1() change amount... getchange1() checks if amount == 0, if so, print list if amount >= current denomination , add denomination list recur, decrementing amount current denomination... if amount < current denomination , recurs on next denomination... (index + 1) i don't understand how getchange() called again once amount equals 0... doesn't if amount == 0, print out list? if (amount == 0) { system.out.print(total + ", "); } therefore, because of i'm not sure how rest of permutations completed... a picture reallly help! input : 12 cents output : [10, 1, 1], [5, 5, 1, 1], [5, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] code : public void makechange1(int amount) { getchange1(amount, new arraylist<integer>(), 0); } public void getchange1(int amount, list<integer> total

c# - Forcing a full page load -

i full page load when click button unfortunately within update panel. i okay use onclick or onclientclick, means can use either asp.net or javascript perform full page load. by full page load mean whole page (i know how post works) why not use anchor, style button if needed. staticly <a href="somepage.aspx">reload</a> or dynamically <a href="<%=request.rawurl %>">reload</a>

javascript - How can I perform an asynchronous operation before grunt.initConfig()? -

now have gruntfile setup perform automatic detection magic parsing sourcefiles parse php sources in roder dynamically figure out filenames , paths need know before running grunt.initconfig() . unfortunately grunt.initconfig() doesn't seem meant run asynchronously, see no way have asynchronous code executed before can call it. there trick accomplish or have rewrite detection routines synchronously? there easy way block execution before callback has arrived? inside grunt tasks there of course this.async() , initconfig() doesn't work. here's stripped down example: function findsomefilesandpaths(callback) { // async tasks detect , parse // , execute callback(results) when done } module.exports = function (grunt) { var config = { pkg: grunt.file.readjson('package.json'), } findsomefilesandpaths(function (results) { config.watch = { coffee: { files: results.coffeedir + "**/*.coffee", tasks: ["coffee&qu

java - Android: MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA -

can ony give me guidelines on how find directory android device stores images takem camera; in following code snippet, intend list of files in prior launching camera app. when returning camera app list of files in same directory , process newly added ones. public void onbtntakephoto(final view view) { existingfiles = uploadimageservice.getfiles(<image_location>); final intent intent = new intent(mediastore.intent_action_still_image_camera); startactivityforresult(intent, take_picture); } public void onactivityresult(final int requestcode, final int resultcode, final intent data) { super.onactivityresult(requestcode, resultcode, data); switch (requestcode) { case take_picture: list<string> newfies = uploadimageservice.getfiles(<image_location>); newfies.removeall(existingfiles); (string newfile : newfies) { file file = new file(newfile); addimage( uri.fromfile(fi

vb.net - PictureBox - Opacity paint inside given coordinates -

Image
i have picturebox , inside want paint (with opacity don't full hide painted region) determinated region of picture coordniates given. so far i've 'if' statement when user click picturebox checks if region correct coordinates: if localmouseposition.x >= 87 , localmouseposition.x <= 131 , localmouseposition.y >= 5 , localmouseposition.y <= 55 label1.text = "coordinate correct" else label1.text = "" end if now i've no idea how paint clicked region. thanks in advance. try like... public class form1 private intarget boolean = false private target new rectangle(new point(87, 5), new size(45, 51)) private sub picturebox1_click(sender system.object, e system.eventargs) handles picturebox1.click dim clientcoords point = picturebox1.pointtoclient(cursor.position) intarget = target.contains(clientcoords) label1.text = iif(intarget, "coordinate c

security - How does the web container know about the role of the user -

i new web-app development , security , trying understand things around. everywhere implementing security in webapp ask use declarative security. example in tomcat can declare roles in tomcat-user.xml file following one. <tomcat-users> <user name="tomcat" password="s3cret" roles="manager-gui" /> </tomcat-users> this part can understand. now suppose have added of these roles in web-app. user of web-app makes request resource in web-app. want know how container or i know with role user has made request ? thank you. using tomcat , jsp: a datasourcerealm can point database containing user , user role tables, using userdatabaserealm (points tomcat-users.xml) works fine well. if want protect jsp pages in specific folder, add web.xml <security-constraint> <web-resource-collection> <web-resource-name>folder description</web-resource-name> <url-pattern>/foldername/*</url-pattern&g

hibernate - JPA @OneToMany relationship to @Embedded class used as @Id -

i have problem (and i'm not sure if possible) whit association , embedded id using jpa... i have person class it's id: @entity public class person{ @embeddedid private personcode personcode; private string name; @embeddable public static class personcode{ private string code; } } and create class company association: @entity public class company{ private string name; @onetomany private list<personcode> employees; } but have exception: caused by: org.hibernate.annotationexception: use of @onetomany or @manytomany targeting unmapped class: example.domain.company.employees[example.domain.person$personcode] an association must between 2 entities. company should have list<person> . btw, make harder necessary. use @entity public class person{ @id private string code; private string name; } there's no reason wrap single field embeddable class.

c# - Datetime Timer Interval does not change speed of months added -

datetime newdate = new datetime(2013, 1, 1); void addtime() { timer1.interval = 600000; timer1.enabled = true; timer1.tick += new eventhandler(timer1_tick); timer1.start(); } void timer1_tick(object sender, eventargs e) { newdate = newdate.addmonths(+3); lbldate.text = newdate.tostring(); } for reason changing timer1.interval not change speed of 3 months being added newdate , constant. trying have 1 minute real life time equal 3 months in game. using c#. your initial timer interval bit larger. below sample complete application. working expected using system; using system.windows.forms; namespace windowsformsapplication1 { public partial class form1 : form { datetime newdate = new datetime(2013, 1, 1); public form1() { initializecomponent(); addtime(); // call method, otherwise timer not start } void addtime() { timer1.interval = 60000; // every minute

php - using Usercake to discover information about a user -

okay have think weird problem. i'm using usercake link page form of user management . works great , who'd not advanced in php/ db administration it's awesome. attempting change of page based if user logged in or not. so link in forum attempting change pannel on page if user logged in first code snippet modified version of i'd use if (isuserloggedin()){ print(' <ul class="login"> <li class="left">&nbsp;</li> <li>hello '); echo $loggedinuser->username . " 2 c ya!" ; print(' </li> <li class="sep">|</li> <li id="toggle"> <a id="open" class="open" href="#">log in | register</a> <a id="close" style="display: none;" class="close" href="#">close panel</a>

package - Modifying code for Android application to multiple screens -

i have application android change, matter follows: the application launched has single screen configuration , data management (the application itself), modify have same application on several screens (screen settings, application, information, etc.) , inclurile menu option .. within oncreate, have several methods, , out of several clasess, need out (otherwise) , interact independent displays each class, can these out .. the code looks ... package com.test1; import com.test1.r.drawable; public class test1activity extends activity { public handler_thread handlerthread; public testinterface uartinterface; edittext readtext; edittext writetext; spinner option1spinner; button writebutton, configbutton; byte[] writebuffer; public context global_context; public boolean bconfiged = false; public sharedpreferences shareprefsettings; drawable originaldrawable; public string ac

C++ Introspection techniques, similar to python -

are there introspection techniques in c++ in python? for example: want more information specific object without going through header file or referring cpp reference. am asking proper question, or moving wrong direction here? update: based on below answers, answer related question: how can add reflection c++ application? c++ has built in rtti system, though it's part horribly worthless. result custom introspection used instead. introspection in c++ implemented 2 main methods: preprocesing step scan cpp files , create database/generate cpp code; use templating. wrote articles on templating technique here . if you're more interested in using introspection rather implementing it, suggest looking clreflect, or can try cpfg .

Is it safe to add 'allowfullscreen' param automatically for all iframes? -

i embed external content via iframes on wordpress sites via shortcode this: [iframe src="http://path.to/page"] and other params (width, height, frameborder, etc) added automatically (while content parsing , executing such shortcodes) because there no need specify them every time. some of iframe embeds videos youtube or vimeo needs 'allowfullscreen' param iframe code. so decided add 'allowfullscreen' automatically every iframe on site (even not youtube or vimeo) easier adding content. is safe add 'allowfullscreen' param automatically iframes? there possible problems 'allowfullscreen' in iframes on site? the allowfullscreen doesn't seem pass w3c validator check , youtube; get: line 129, column 131: "allowfullscreen" not member of group specified attribute …bed/uiqfkwurspm?feature=oembed" frameborder="0" allowfullscreen></iframe><br />

javascript - Trigger click on iframe -

i'm aware of same-origin policy... getting out of way. anyway, have slideshow (slide.js) has embedded videos in it. when user clicks video, want slideshow pause. events inside iframe not trigger, i'm trying work around that. right have partial solution. detect blur event on window , if newly focused element iframe pause slideshow: $(window).blur(function(event){ console.log(event.target); if($('iframe').is(':focus')){ //clicked inside iframe console.log('test'); } console.log('document.activeelement is:'); console.log(document.activeelement); console.log('\n'); }); after loading page in console: document.activeelement is: body now part confuses me. click event fires iframe focus event when click somewhere other iframe first . is, after loading page, if directly click iframe, console not log test. if click either outside frame, or tab in browser, or anywhere else, blur event trigg

Programatically testing for openmp support from a python setup script -

i'm working on python project uses cython , c speed time sensitive operations. in few of our cython routines, use openmp further speed operation if idle cores available. this leads bit of annoying situation on os x since default compiler recent os versions (llvm/clang on 10.7 , 10.8) doesn't support openmp. our stopgap solution tell people set gcc compiler when build. we'd programmatically since clang can build else no issues. right now, compilation fail following error: clang: error: linker command failed exit code 1 (use -v see invocation) error: command "cc -bundle -undefined dynamic_lookup -l/usr/local/lib -l/usr/local/opt/sqlite/lib build/temp.macosx-10.8-x86_64-2.7/yt/utilities/lib/geometry_utils.o -lm -o yt/utilities/lib/geometry_utils.so -fopenmp" failed exit status 1 the relevant portion of our setup script looks this: config.add_extension("geometry_utils", ["yt/utilities/lib/geometry_utils.pyx"], ext

file io - Putting data from HTTP POST in a CSV with PHP? -

i'm writing basic android app sends gps data via http post php page. want data 2 values (latitude , longitude) separated comma. <?php $myfile = "requestslog.txt"; $fh = fopen($myfile, 'a') or die("can't open file"); fwrite($fh, "\r\n"); fwrite($fh, file_get_contents('php://input')); fclose($fh); echo "<html><head /><body><iframe src=\"$myfile\" style=\"height:100%; width:100%;\"></iframe></body></html>" ?> the text file shows data this: lat=55.020383&lon=-7.1819687 lat=55.020383&lon=-7.1819687 lat=55.020383&lon=-7.1819687 lat=55.0203604&lon=-7.1819732 lat=55.0203604&lon=-7.1819732 lat=55.0203604&lon=-7.1819732 is possible php replace '&' ','? i'm lookg end result csv 2 rows. don't have experience php , great. str_replace('&',',') should tr

c# - How Do I debug a fault exception -

how debug faultexception i getting <?xml version="1.0" encoding="utf-8"?> <env:envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"> <env:body> <env:fault> <faultcode>env:client</faultcode> <faultstring>rejected policy. (from client)</faultstring> </env:fault> </env:body> </env:envelope> the documentation provided says because of missing,invalid user id or credentials fault encountered when user id or password not specified or incorrect within data-stream i giving correct password, userid. because of invalid usernametoken or x509 certificate. i start configuring tracing on server . verbose traces might give clue what's happening.

machine learning - My 2 layer neural network gets only 2.05% test error rate on MNIST. Too low to be correct? -

is @ reasonable low of test error rate? doubt it, because test error rates listed on mnist database website higher this, evidence otherwise seems irrefutable. using 2 layer net 100 hidden units. using no regularization. initialize small random weights , use nesterov momentum method on mini-batches. training error rate 0.0000667 (4 training examples misclassified). average cross entropy loss on training examples 0.00410, , same on test examples 0.207. here link original metaoptimize post . edit: i found result must have missed on mnist page: 2-layer nn, 800 hu, cross-entropy loss, obtains test error rate of 1.6%. guess other results high error rates there make point types of fancy modifications neural nets harm performance. net hasn't done better 1.6%, believe result more readily.

entity framework - Loading most related entities of an object is very slow -

continuing earlier question described schema (repeated here convenience): parties ( partyid, clientid, addressid, datetime ) tents ( partyid, tentdetails... ) clowns ( partyid, addressid, clowndetails... ) securityagentassignment ( partyid, agentid, fromtime, untiltime ) addresses ( addressid, street, city, state ) ....and there's 10 other tables of similar design: in many-to-one relationship parties . my asp.net mvc web application has summary page displays every detail party. i'm using ef1.0 have own eager-loading. here's logic i'm using: party dbparty = getparty(partyid); dbparty.tents.ensureloaded(); dbparty.clowns.ensureloaded(); foreach(clown clown in dbparty.clowns) clown.address.ensureloaded(); dbparty.security.ensureloaded(); foreach(securityagentassignment assignment in dbparty.security) assignment.agent.ensureloaded(); // , 10 other relationships the code above takes 3 seconds run. given isn't eager-loading, lazy-loading, surely should fir

c# - Having Trouble Setting Window's Owner in Parent's Constructor -

is there wrong in wpf setting owner property of window parent in parent's constructor? there shouldn't be, right? why getting xamlparseexception following code? public partial class mainview : window { private readonly ownedwindow owned; public mainview() { initializecomponent(); owned = new ownedwindow(); owned.datacontext = datacontext; var window = getwindow(this); owned.owner = this; //setting window causes same error ... } i should clarify removing owned.owner = this; removes runtime error. the details of exception: xamlparseexception unhandled the invocation of constructor on type '...mainview' matches specified binding constraints threw exception. actually , looked @ inner exception, , says: cannot set owner property window has not been shown previously. so i'm looking now. the problem because wpf creates native window first time wpf window shown, c

c# - How to write to memory address? -

new pointers , unsafe world in c#. going through getting memory address of variables via pointers, move things around bit here , there etc; learning. static unsafe void m() { var = 1; var p = &i; //gets memory location of variable here //how write location p, value of 100? } i wondering if there way write specific location well? helps great deal see what's going around if can read , write @ same time. no practical purposes, learning. or not possible c#? you need dereference pointer * operator. ex: *p = 100;

delphi - How to pull a MDI child window out of the main form? -

i want create mdi application it's own task bar user can have fast access child windows he/she wants bring front. had idea user works 2 or more monitors drag on of child windows inside main form of application outside of it, monitor example. how can done? maybe example mdi client form code serves inspiration: unit unit3; interface uses windows, messages, controls, forms; type tform3 = class(tform) private fsizing: boolean; procedure wmncmouseleave(var message: tmessage); message wm_ncmouseleave; procedure wmwindowposchanged(var message: twmwindowposchanged); message wm_windowposchanged; protected procedure createparams(var params: tcreateparams); override; procedure resize; override; end; implementation {$r *.dfm} { tform3 } var fdragging: boolean = false; procedure tform3.createparams(var params: tcreateparams); begin inherited createparams(params); if formstyle = fsnormal params.exstyle := params.exstyle

io - c++ program suddenly stopped writing to file -

i have little c++ programming experience, , wrote quick program find groups of links in long link list. i have been using program last 2 days , worked fine (i'm guessing inefficiently, worked). stopped writing file. made new file , changed file name in program check corruption still isn't working. have identical program searching through separate link list, , program still working. here code: i've gotten program write file checking strings while loop, instead of loop #include <iostream> #include <fstream> #include <string> int main() { std::string string; std::string findstring; std::string line; std::ifstream infile; std::cout<<"find string: "; std::getline(std::cin, findstring, '\n'); infile.open("old.rtf"); std::ofstream returnfile("return.txt"); int = 0; std::string previousline = ""; while(a < 1) { std::getline(infile, strin

c++ - Friend Class or Friend member function - Forward declaration and Header inclusion -

yeah question topic has been discussed many times. , i'm clear difference. i've 1 doubt related example in book. this question related my previous question , presented 2 classes taken example in book c++ primer. in reference classes, book quotes following paragraph, specially related declaration of member function of windowmanager class friend function. here's says: making member function friend requires careful structuring of our programs accommodate interdependencies among declarations , definitions. in example, must order our program follows: first, define window_mgr class, declares, cannot define, clear. screen must declared before clear can use members of screen. next, define class screen, including friend declaration clear. finally, define clear, can refer members in screen. the code presented in question follows structure only. seems not working out. makes me think if above points misguiding or didn't implement correctly.

jquery Function to return object -

i have function supposed return object when finds it's not doing that. doing wrong? var getel = function(title){ var theinputs = $('input[type=text], input[type=radio], input[type=checkbox], select, textarea') theinputs.each(function(){ if (this.title==title){ getel = console.log('found it!') } }) } console.log(getel('office status')) i know works since found output on console, console reports undefined output of line: console.log(getel('office status')) var getel = function(title){ var result; var theinputs = $('input[type=text], input[type=radio], input[type=checkbox], select, textarea') theinputs.each(function(){ if (this.title==title){ result = console.log('found it!') return false; // break loop } }); return result; } overwriting value of functions variable not work. want instead ret

is there a way to use yahoo finance API in php -

i want show change of stock exchanges yahoo, in left top of page, dow 0.62% nasdaq 0.54% in below mentioned url http://finance.yahoo.com/q?s=api i want collect top 10 stock exchange rates. saw api documentation here c# , there way use api & call data in php, tried find solution no such luck:( **i got solution of using http://quandl.com your link wrong, yahoo! provides apis return csv, xml , json- of easy work in php. https://code.google.com/p/yahoo-finance-managed/wiki/yahoofinanceapis

dos - Copy Multiple Files with Same Characters to a Single File -

i have lot of files need joined. existing file naming structure 20130514abcd.txt file naming convention year, month, date, city. merge files same last 4 characters (i.e same city) one. i able move city folder created each city. not want.. @echo off pushd pathname /f %%f in ('dir/b/a-d *.txt') call :sub1 %%f goto :eof :sub1 set name=%1 md %name:~9,12% move %* %name:~9,12% what need script equivalent c:\>copy *city.txt city.txt , city name variable. edited: works here files you've stated. @echo off pushd "pathname" /f "delims=" %%f in ('dir /b /a-d *.txt') call :sub1 "%%f" popd pause goto :eof :sub1 set "name=%~1" set "cityname=%name:~8,-4%" if exist "%cityname%\" goto :eof echo processing "%cityname%" md "%cityname%" 2>nul copy /b "????????%cityname%.txt" "%cityname%\%cityname%.txt" >nul

Removing Unicode Line Separator in Bash -

Image
i have text file unicode line separator (hex code 2028). i want remove using bash (i see implementations python , not language). command use transform text file (output4.txt) lose unicode line separator? see in vim below: probably tr command should work: tr '\xe2\x80\xa8' ' ' < infile > outfile working solution: op finding this: sed -i.old $'s/\xe2\x80\xa8/ /g' infile

C++ Boost Signals connecting two functions from two different classes in template -

i'm trying make connection between function in 1 class can call in class. answers i've found either specific or maybe i'm missing because cannot life of me figure out i'm doing wrong. also, i'm bit new boost library please excuse dumb questions may ask. the setup workflow this... class myclass : public baseclass { void setup(); void myfunc(datatype); otherclass myotherclass; } void setup() { othernamespace::addlistener(this, myotherclass); } namespace othernamespace { class otherclass { signals::signal<void (datatype)> myconnection; } template<class a, class b> void addlistener(a * app, b & connection) { connection.myconnection.connect( 'i don't know here' ); } } basically, addlistener function won't make connection between signal , function. know don't know i'm doing wrong can't figure out wrong. i'm making helper function can pass functions 1 class call them when they're attached.

sql - Mysql Multiple Unique Keys Across Tables -

i have table that: create table `appointment` ( id int not null auto_increment, user_id int not null, doctor_slot_id int not null, date date not null, primary key(id), foreign key(user_id) references user(id), foreign key(doctor_slot_id) references doctor_slot(id) ); i want user can't arrange appointment doctor more once in day. want add unique constraint between doctor_id , user_id in structure can't. tried things not in sql syntax: unique(user_id, doctor_slot.doctor_id) and unique(user_id, doctor_slot(doctor_id)) and unique(user_id, doctor_id(doctor_slot)) but know, didn't work. there suggestions can make? based on comment doctor_slot is, seem have bit on issue schema design. there should no reason store both slot_id , date in appointment table, in doctor_slot has date component, storing date in appointment table redundant storage of data, , become problematic keep in sync. of course, without date on table impossi

linux - piping a string to gcc with python's subprocess.Popen -

i have c++ style text file i'm trying pipe gcc remove comments. initially, tried regex approach, had trouble handling things nested comments, string literals , eol issues. so i'm trying like: strip_comments(test_file.c) def strip_comments(text): p = popen(['gcc', '-w', '-e', text], stdin=pipe, stdout=pipe, stderr=stdout) p.stdin.write(text) p.stdin.close() print p.stdout.read() but instead of passing file, i'd pipe contents because files i'm trying preprocess don't have .c extension has had success this? this 1 works subprocess.pipe (os.popen() deprecated), , need pass , additional - argument gcc make process stdin: import os subprocess import popen, pipe def strip_comments(text): p = popen(['gcc', '-fpreprocessed', '-dd', '-e', '-x', 'c++', '-'], stdin=pipe, stdout=pipe, stderr=pipe) p.stdin.write(text) p.stdin.close()

powershell - How do I conditionally add a class with Add-Type -TypeDefinition if it isn't added already? -

consider following powershell snippet: $csharpstring = @" using system; public sealed class myclass { public myclass() { } public override string tostring() { return "this class. there many others " + "like it, 1 mine."; } } "@ add-type -typedefinition $csharpstring; $myobject = new-object myclass write-host $myobject.tostring(); if run more once in same appdomain (e.g. run script twice in powershell.exe or powershell_ise.exe) following error: add-type : cannot add type. type name 'myclass' exists. @ line:13 char:1 + add-type -typedefinition $csharpstring; + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + categoryinfo : invalidoperation: (myclass:string) [add-type], exception + fullyqualifiederrorid : type_already_exists,microsoft.powershell.commands.addtypecommand how wrap call add-type -typedefinition called once? this technique works me: if (-not ([system.management.automation.