Posts

Showing posts from April, 2014

Teaching OOP (C++) outside-in vs inside-out approach -

i running programming club @ high-school, , have introduced students oop using simplistic classes in c++. believe @ least theoretically idea. able offer them specific project can work on together. question have approach take. when took programming classes in college, saw 2 different approaches, in opinion both had serious shortcomings. ended sleeping through of them , learning stuff on own books , examples. in teacher's shoes, opinion on approach preferable or if there third option. approach 1 used, write program on board (or on computer projection screen). class definitions written first. students bewildered @ point, because purpose of variables , methods seem entirely obscure them. time learned each variable , method , how interacted when instructor write implementation (i called outside-in method) approach 2 explain trying achieve, , creating classes , members needed. has opposite problem. writing method use these imaginary classes have implemented later. students has no

c# - wp7 - stream creating issue -

i trying make app save pictures remote host via ssh , scp , need create empty stream variable full scpclient.download(string filename, stream destination ) method use later. there way that? tried: stream downloadstream = new memorystream(); scpclient.connect(); scpclient.download("remotefilename", downloadstream); medialibrary locallibrary = new medialibrary(); locallibrary.savepicture("localfilename", downloadstream); messagebox.show("success!", "result", messageboxbutton.ok); i getting unknown exception or app quits. maybe there way pass image throw isolatedstorage ? using renci.sshnet library. you should put code in try ... catch block try { // stuff } catch (exception ex) { messagebox.show(ex.message); } then add exception details question, you'd more people in here.

assembly - printing a message in mips -

i have following code in program li $v1, 4 #system call code print string la $a0, lc #load address of message $a0 syscall #print string li $v1, 1 #system call code print integer move $a0, $v0 #move value printed $a0 syscall #print result and .rdata lc: .asciiz "the factorial of 10 : " but when try use in mips says: unknown system call: 3628800 where 3628800 result want print! what going wrong?can use jal printf instead , how should write it? in advance the system call number goes $v0 , not $v1 .

sql - How do I update a subset of values in DB2 based on related tables? -

i trying remove last 10 characters clob field in db2 database. can using: update report set comment = left(comment, (length(comment) - 10)) however, want limit truncation subset of rows based on whether or not report in current reporting period. tried this... update report set comment = ( select left(comment, (length(comment) - 10)) report inner join report_period on report.report_period_id = report_period.report_period_id report_period.name = '2013 interim report' ) ...but get the result of scalar fullselect, select statement, or values statement more 1 row what doing wrong? never mind... asking question helped clear in head. had move join clause.... update report set comment = left(comment, (length(comment) - 10)) report_id in ( select report_id report inner join report_period on repo

c++ - why should we not include the last array element in sprintf? -

i have code shown below, last statement works if use l_plates[i]. in below case throws error "passing argument 1 of 'sprintf' makes pointer integer without cast" if need loop n too. should use element if use sprintf? please explain. in advance. char type, letters[4], digits[5]; char l_plates[m][n]; (i=0; i<m; i++) { scanf(" %c", &type); scanf("%3s", letters); scanf("%4s", digits); sprintf(l_plates[i][n], "%s %s %c", letters, digits, type); } i see 2 problems here. first, first argument of sprintf should char* , not char , you're sending it. secondly, array of size n indexed 0 n - 1 . trying access element n , you're stepping outside of array. last element [n - 1] .

c# - Convert youtube url to iframe embed code -

i've been trying find regex pattern replace youtube urls in string iframe embed code (c#). video id has extracted. here url patterns should match: http://www.youtube.com/watch?v=bsidlcf5u3s https://www.youtube.com/watch?v=bsidlcf5u3s http://youtu.be/bsidlcf5u3s www.youtube.com/watch?v=bsidlcf5u3s youtu.be/bsidlcf5u3s http://www.youtube.com/watch?feature=player_embedded&v=bsidlcf5u3s www.youtube.com/watch?feature=player_embedded&v=bsidlcf5u3s all possible urls should replaced with: <iframe title='youtube video player' width='480' height='390' src='http://www.youtube.com/embed/video_id_extracted' frameborder='0' allowfullscreen='1'></iframe> can please point me right direction. thank in advance here regex: (?:https?:\/\/)?(?:www\.)?(?:(?:(?:youtube.com\/watch\?[^?]*v=|youtu.be\/)([\w\-]+))(?:[^\s?]+)?) should match links posted , extracts video id $1 . , following code replace links

caching - Javascript used to include html, is it cached? -

i'm using method of creating .js file on server #1 contains document.writes write html code, simple js include inside html code on server #2 load html code (there multiple server #2's). replacing iframe method advantage being each server #2 owner controls own css. the method works is. question has deal caching. each time page loaded on server #2 want .js reloaded, change on server #1. appears case on each browser tested, can rely on being default case, or dependent on browser settings? despite i've read on caching can't figure out triggers load case this. you can control browser caching using http headers on server side. cache-control , cache-expiration . more here - http://www.w3.org/protocols/rfc2616/rfc2616-sec13.html

java - JFrame always prints out null for variables inside action listener -

the following program's goal ask user input resistor value, of program output corresponding colors each digit. not include digits. however, program done, i've made attempt incorporate jframe thing, except hung on how print corresponding colors in action listener. i asked question however, got limited replies due forgetting enter specific tags. however, user answer use arraystostring did practicly nothing, since program still managed print null. cannot refer non variable inside action listener (jframe) methods below jframe sopposed gather information each color band of resistor depending on digit number, in action listener try , print out colors, rather prints null (3 times) i have tried viewing various tutorials online, , java api , guidelines, none of help. in general seem unaware of how incorporate code written jframe, whether it's tedious process, willing corporate , grateful insight on how tackle predicament. import java.io.*; import javax.swing.*; //import

sql server - How to insert multiple records into database with SqlParameter in C# -

i trying run following code: using (sqlconnection conn = new sqlconnection(connstr)) { conn.open(); stringbuilder sqlstr = new stringbuilder("insert customers values ( @name, @address, @city, @state)"); sqlcommand cmd = new sqlcommand(sqlstr.tostring(), conn); cmd.parameters.add(new sqlparameter("@name", "john smith")); cmd.parameters.add(new sqlparameter("@address", "123 main st.")); cmd.parameters.add(new sqlparameter("@city", "detroit")); cmd.parameters.add(new sqlparameter("@state", "michigan")); cmd.executereader(); cmd.parameters["@name"].value = "william jones"; cmd.parameters["@address"].value = "500 blanchard ave"; cmd.parameters["@city"].value = "chicago"; cmd.parameters["@state"].value = "illinois"; cmd.executereader(); } however, getting error

android - Call Java function from native function based on cached jobject and methodID fail -

java source: public void oneventlistener(final int eventid, final int arg1, final long arg2, final string message) { log.d("test", "oneventlistener() called - eventid = "+eventid); } jni code: javavm* gjvm = null; pid_t _vm_tid = -1; jnienv * jenv = null; jclass native_cls_id = null; jmethodid _oneventlistenerid=null; jobject m_nativeobj = null; jint jni_onload(javavm* vm, void* reserved) { .... gjvm = vm; _vm_tid = gettid(); .... } //function void notifyfromnative(int eventid, int arg1, long arg2, char* message) { logd("receive_message_callback called - eventid = %d",eventid); jnienv* env = null; pid_t tid = gettid(); logd("step 0"); if (tid != _vm_tid) { jint ret = gjvm->attachcurrentthread(&env, null); logd("step 1 - tid != _vm_tid ret=%d",ret); } else { logd("step 1 - tid == _vm_tid"); gjvm->

c - Why is scanf("%hhu", char*) overwriting other variables when they are local? -

the title says all. i'm using gcc 4.7.1 (bundled codeblocks) , faced strange issue. consider this: int main() { unsigned char = 0, b = 0, c = 0; scanf("%hhu", &a); printf("a = %hhu, b = %hhu, c = %hhu\n", a, b, c); scanf("%hhu", &b); printf("a = %hhu, b = %hhu, c = %hhu\n", a, b, c); scanf("%hhu", &c); printf("a = %hhu, b = %hhu, c = %hhu\n", a, b, c); return 0; } for inputs 1, 2 , 3, outputs a = 1, b = 0, c = 0 = 0, b = 2, c = 0 = 0, b = 0, c = 3 if i, however, declare a, b , c global variables, works expected. why happenning? thank in advance other details: i'm running windows 8 64 bits. tried -std=c99 , problem persists. further research testing code void printarray(unsigned char *a, int n) { while(n--) printf("%hhu ", *(a++)); printf("\n"); } int main() { unsigned char array[8]; memset(array, 255, 8);

java - Android UDP packet loss -

so i'm writing app sends 5kb packets out 15 times second through udp. understand lose packets seem losing packets after first couple seconds. if slow down send 5kb packets out once every 10 seconds still lose them. cause this? it's not surprising dropped. payload bigger 512 bytes unlikely make out of network. depends on mtu of router , how bandwidth allocated udp / internet traffic on router.

c++ - High interprocess timing variations, but low intraprocess timing variations for the same task -

i running code (full code here: http://codepad.org/5ojblqia ) time repeated daxpy function calls , without flushing operands cache beforehand: #define kb 1024 int main() { int cache_size = 32*kb; double alpha = 42.5; int operand_size = cache_size/(sizeof(double)*2); double* x = new double[operand_size]; double* y = new double[operand_size]; //95% confidence interval double max_risk = 0.05; //interval half width double w; int n_iterations = 50000; students_t dist(n_iterations-1); double t = boost::math::quantile(complement(dist,max_risk/2)); accumulator_set<double, stats<tag::mean,tag::variance> > unflushed_acc; for(int = 0; < n_iterations; ++i) { fill(x,operand_size); fill(y,operand_size); double seconds = wall_time(); daxpy(alpha,x,y,operand_size); seconds = wall_time() - seconds; unflushed_acc(seconds); } w = t*sqrt(variance(unflushed_acc))/sq

file sharing web site in asp.net like dropbox , currently all uploaded data stored on my machine but i want to store that on multiple machine? -

i created web site , data base , works fine on single machine transform on 2 machine in website running on pc when end user upload files store on pc ,so pc middleware , end user not know resource lying? how connect pc anothere data storage ?

javascript - Regex for validation numbers with commas and space -

i not sure why regex expression not working. want validate if input in format : 12345678,12345678,12345678 *space*12345678 , 12345678 , 12345678 , 12345678 12345678,12345678, space must 8 digit if not return false. below regex expression did, working 2 sets of numbers when input set of numbers validation not working. working: 12345678 , 12345678 not working: 12345678 , 12345678 ,12345678 var validate_numbers = /^\s*\d{8}\s*\+*(,\s*\d{8},*)?$/; thank you you need describe want match in more detail. i'm going assume want match 8-digit nums delimited commas , pluses, possibly followed commas. the problem you're taking @ 2 sets of digits. visualization . given assumption above, regex want: ^(\s*\d{8}\s*[+,]?\s*)*$ again, can visualize on debuggex .

database - nodejs + connect + custom session store -

is there way override connect session store custom functionality? i'm coming python flask framework have built hybrid memcache + database session handler. use memcache main session holder, on updates save data database , update database every 5 mins of session being alive. doing way can lower amount of requests database, have system fall-back database in there memory or memcache issue. is there way override or extend get/save/destroy functions?

javascript - Jquery textarea.val('') adds line break on FIRST enter press? -

i have little chat setup, , on enter press if text area in focus have set submit chat database , clear text area. unfortunately though, first time 1 presses enter adds linebreak in text area, in browser. if type , press enter again, there's still 1 line break there. missing something? thanks! $(document).keypress(function(keypress) { if (keypress.which == 13) { if ($('#chattext').is(':focus')) { if ($('#chattext').val().length > 0) { chatvalue = $('#chattext').val(); $('#chattext').val($('#chattext').val().substring(0,0)); $.ajax({ type: 'post', url: 'submitchat.php', data: { chattext: chatvalue }, success: function(result) { $('#chat_text').html(result);

html - Line showing up between top of site window and bottom of chrome bookmarks -

Image
i'm not sure why image i'm using displaying white line @ top. doesn't happen other images. i've zoomed in quite bit on image make sure it's not image itself. set box black incase image didn't cover everything. yet it's still there. this site: http://www3.carleton.ca/clubs/sissa/html5/ this looks like: css: body{ width: 100%; /*always specify when using flexbox*/ height:100%; display: -webkit-box; display: -moz-box; display: box; text-align:center; -webkit-box-pack:center; /*way of centering website*/ -moz-box-pack:center; box-pack:center; background:black; background:url('images/bg/bg14.jpg') no-repeat center center fixed; background-position: left top; -webkit-background-size: cover !important; -moz-background-size: cover !important; background-size: cover !important; font-family: arial, helvetica, sans-serif; font-size: 13px; } it because of chrome theme u

jquery - Read filename to the textbox from fileupload window -

in asp.net application, have used textbox , button , hidden fileupload control . when button clicked using jquery getting fileupload window below, protected void btn_browse_click(object sender, eventargs e) { stringbuilder strscript = new stringbuilder(); strscript.append("$(document).ready(function(){"); strscript.append("$('#fileupload1').click();"); strscript.append("});"); page.clientscript.registerstartupscript(this.gettype(), "script", strscript.tostring(), true); txt_filename.text=fileupload1.filename; } my issue unable show selected filename fileupload textbox . filename not displaying in textbox any suggessions. on serverside can this: string filename = path.getfilename(fid.postedfile.filename); fid.saveas(server.mappath("files/"+filename)); string fpath = "files/"+filename; and jquery: $(document).ready(function () { $("#btnfileupload").clic

python - Insert column using openpyxl -

i'm working on script modifies existing excel document , need have ability insert column between 2 other columns vba macro command .entirecolumn.insert . is there method openpyxl insert column this? if not, advice on writing one? haven't found .entirecolumn.insert in openpyxl. first thought coming mind insert column manually modifying _cells on worksheet. don't think it's best way insert column works: from openpyxl.workbook import workbook openpyxl.cell import get_column_letter, cell, column_index_from_string, coordinate_from_string wb = workbook() dest_filename = r'empty_book.xlsx' ws = wb.worksheets[0] ws.title = "range names" # inserting sample data col_idx in xrange(1, 10): col = get_column_letter(col_idx) row in xrange(1, 10): ws.cell('%s%s' % (col, row)).value = '%s%s' % (col, row) # inserting column between 4 , 5 column_index = 5 new_cells = {} ws.column_dimensions = {} coordinate, cell in

java - Skip execution if exception thrown -

i stuck on basic. in our game have leveleditor/loader can fetch levels via url. if url points nonexistant file editor should refuse load level , stay in currentlevel, struggling basic code. private void loadlevel(url url) { scanner in = null; try { in = new scanner(new bufferedreader(new inputstreamreader( url.openstream()))); readline(in); in.close(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } } essentially, if filenotfound thrown (or other) readline(in) should not proceed. kinds of npe if does. private void loadlevel(url url) { scanner in = null; try { in = new scanner(new bufferedreader(new inputstreamreader( url.openstream()))); /*if(in!=null){ readline(in); in.close(); }*/ readline(in); in.close(); } catch (exception e) { // todo auto-generated

wolfram mathematica - equal value = equal rank -

i rank elements of list such elements have same value same rank: list = {1, 2, 3, 4, 4, 5} desired output: ranks = {5, 4, 3, 2, 2, 1} ordering[] want assigns different ranks 2 instances of 4 in list. i not sure cover have in mind, following code give desired output. presupposes smallest value highest rank, , should work numerical values or long ok standard sorting order of mathematica. local variable dv shortname "distinct values". fromlisttoranks[k_list]:= module[ {dv=reverse[union[k]]}, k /. thread[dv -> range[length[dv]]] ] fromlisttoranks[list] {5,4,3,2,2,1}

asp.net - set multiple Validator for single textbox -

i new asp.net , facing small small problem in , problem set multiple validator single textbox . set validation while running it, validation takes step-by-step, not in single place. here's code: <td align="right" style="padding-right: 5px; width: 50%;"> <asp:label id="lblconformpassword" runat="server" text="conformpassword &nbsp;:"></asp:label> </td> <td align="left" style="padding-left: 5px; width: 50%; color: #ff0000;"> <br /> <br /> <br /> <asp:textbox id="txtconformpassword" runat="server" textmode="password" width="70%" forecolor="red" autocompletetype="office"></asp:textbox> * &nbsp;&nbsp;&nbsp;<br /> <asp:requiredfieldvalidator id="requiredfieldvalidator5" runat="server" controltovalidate="txtcon

How to exclude an item from "wrap_content" in an Android View? -

i have drop down menu in header. when button pressed drop down menu comes down. problem other views in activity positioned android:layout_below="@id/header" , drop down menu pushes down because increases header's height. need exclude drop down menu android:layout_height="wrap_content" in order prevent that. possible? note: can solve problem programmatically, want learn whether possible exclude item "warp_content" in xml. you cannot exclude viewgroup's child being considered during layout calculations unless set android:visibility=gone . may want replace main container relativelayout let position elements wish

DJANGO - Filter Data from two models -

i have 2 mysql models: class registration(models.model): name = models.charfield(max_length=30) email = models.emailfield() password = models.charfield(max_length=30) company = models.charfield(max_length=30) class personal_details(models.model): reg = models.foreignkey(registration) job = models.charfield(max_length=30) experience = models.integerfield(default=0) i want filtering details using both experience , company keyword. want fetch , display details(name, email, company, job, experience) both tables in html page. you can inside filter() should this i'm working personal_details object now: filteredresults = personal_details.objects.filter(experience="grasscutting", reg__company="ibm") this give list of objects found. magic here can access foreignkey relationships __ convention.

wso2 - Can we store a string in a text file in wso2esb? -

i have text file on local system wish append data in particular file synchronously. i have tried many ways, it's not working. esb has future in oracle soa. can add in file adapter. in esb it's neither giving errors nor expected result. my configuration this: <proxy xmlns="http://ws.apache.org/ns/synapse" name="filewrite" transports="http,vfs" statistics="disable" trace="disable" startonload="true"> <target> <insequence> <log> <property name="out_only" value="true"/> </log> </insequence> <outsequence> <log> <property name="out_only" value="true"/> </log> <payloadfactory> <format> <error>error404</error> </format> </payloadfactory> <send&

ember.js - Defining an API endpoint on a model-by-model basis -

(this question continuation of this one ) i need specify api endpoints on model model basis. how can this? closest have come description of namespace , applies top-level url. my problem api structure not 1 emberjs expects. example, have 2 objects, different api endpoints: phones -> /api/nodes/extensions/phones nodes -> /api/nodes how can configure endpoints each model? if i'm not mistaken, should able set model url property, this: app.phone = ds.model.extend({ description: ds.attr('string'), number: ds.attr('string') }).reopenclass({ url: 'api/nodes/extensions/phones' }); app.node= ds.model.extend({ description: ds.attr('string') }).reopenclass({ url: 'api/nodes' }); i haven't tried revision 12, can't guarantee works. alternatively, might want question & answer talks similar scenario, using adapter specific models introduced in revision 11.

how can i get the values using include with conditions in rails? -

i have shop has_many association , include items items belonging shop received format.json { render json: {:shop => @shops.as_json(:include => :items)}} now gives items belongs shop want items specific condition, item_type = "accessories". how can this? please me. edit i have put new question in how value of include conditions? you should filter data activerecord, , call as_json on filtered data. you can like: @shops = shop.includes(:items).where("items.itemp_type = ?", 'accesories') format.json { render json: { :shop => @shops.as_json(:include => :items) } }

c# - exception HREsult 0x8002000b disp_e_badindex in Visual Studio 2008 -

i exporting dataset excel. when trying 3 excel sheets, working fine. if try fourth sheet, shows exception. exception hresult 0x8002000b disp_e_badindex is there answer this? this may group policy. take @ kb 922848

html - Page size fixed width in middle -

i not sure it's called, can tell me how can make css style sheet makes pages fit within given width, , adds drop shadow type effect, making page? something this: http://www.news.com.au/ so, have white (or grey, or ever) borders on sides, , content placed within 'borders'. edit: have tried style, put's box in top left corner: style> html, body { background-color: #f0f0f0; width: 100%; margin: 0 auto; font-family: "trebuchet ms", helvetica, sans-serif; font-size: small; } #wrapper { background-color: #fff; width: 920px; padding: 20px; -moz-box-shadow: 0 0 5px #888; -webkit-box-shadow: 0 0 8px#888; box-shadow: 0 0 8px #888; } </style> and usage is: <div id="wrapper"> <h1>location search</h1> <h2>simple lookup</h2> .... </div> it image can make box-shadow. i think

php - Why doesn't my wordpress website open in Internet Explorer? -

why doesn't wordpress website open in internet explorer? takes time , system hangs up. my site url . i had @ html in firefox. it's filled errors. ie "line 1388 column 6 - error: end tag element "body" not open". go clean html, , if still have issue, come , ask again.

objective c - How to get the Ascii value from Unicode string U+20B9 to get the indian rupee symbol? -

how ascii value unicode string u+20b9 indian rupee symbol?we have tried use locale identifier giving dollar.how done? it has no ascii code. unicode values u+0000 u+007f have ascii codes. some non-standard fonts assigned indian rupee sign replace ascii grave accent (`) ascii 60 (and unicode u+0060). stupidly incorrect assignment won’t work fonts other few proudly , wrongly made assignment. from here: http://in.answers.yahoo.com/question/index?qid=20121011093254aau72or

Proper function conventions for JavaScript -

this question has answer here: var functionname = function() {} vs function functionname() {} 28 answers i've been doing codecademy javascript lesson, , they're telling use functions this: var functionname = function(parameters) {}; i've done javascript before , i've done this: function myfunction(parameters){} whats correct way? there difference? when should use either? thanks! it depends, in general normal function want use second way: function myfunction(parameters) { } you can assign function variable using first way if want , mixing , matching. // assign anonymous function functionname var functionname = function (parameters) { } // assign pointer myfunction functionname var functionname = myfunction these different things though, imagine for loop containing these, first 1 make new function every iteration second refe

shortcut key to give values for boiler plate code in xcode iOS -

Image
here need click each 1 give values, keyboard shortcut available that? you can control + / direction left right. also tab direction left right. if want go backward control + shift + / direction right left. also shift + tab . direction right left.

validation in struts2 -

public class admin extends actionsupport implements modeldriven<admindata> { admindata admindata = new admindata(); public admindata getmodel() { return admindata; } @validations(requiredstrings ={ @requiredstringvalidator(type=validatortype.field,fieldname="emailid"), @requiredstringvalidator(type=validatortype.field,fieldname="password")} public string auth() { } @validations(requiredstrings ={ @requiredstringvalidator(type=validatortype.field,fieldname="emailid"), @requiredstringvalidator(type=validatortype.field,fieldname="firstname"), @requiredstringvalidator(type=validatortype.field,fieldname="surname"), @requiredstringvalidator(type=validatortype.field,fieldname="password")} public string create() throws databaseexception { } } my problem when call create() method there no problem in validation, when call au

Does Google Analytics for Mobile provide any offline data tracking for Android apps? -

just questions says, google analytics mobile provide offline data tracking android apps? if application offline, google analytics stores events in sqlite database , waits until user online again send them.

javascript - If element ID found in iframe within parent page do something -

i have 1 single iframe within parent page on same domain. need when id 'applications' found in iframe trigger changes in parent page. javascript function correct ? function load(){ if (window.frames[0].document.getelementbyid('applications')) { var str=document.getelementbyid("tst").innerhtml; var n=str.replace("login","delogare"); document.getelementbyid("tst").innerhtml=n; document.getelementbyid('tst').title ='logout'; document.getelementbyid('tst').href='logout'; document.getelementbyid('prt').href='../profil/cont.html?refresh'; }}

c# - how to stop a specific column to be generated in DataGrid when the AutoGenerateColumns is set to True? -

i have bound observablecollection datagrid , set autogeneratecolumns true in wpf mvvm application. then how can stop specific column appeared in datagrid? i have seen same question here . i'm looking more mvvm approach. mvvm means ui , data layers separate, view layer merely being visual reflection of data layer. so "mvvm way" of excluding column depends on exclusion should occur: if data layer supposed exclude column, remove column data layer. this typically means modifying collection datagrid.itemssource binding no longer includes data should not visible. or depending on application , counts "application logic", may mean maintaining string or list<string> of columns exclude, , have view find way of binding strings , modifying it's display exclude columns (a custom dependency property, converter, re-use of tag property + autogeneratingcolumn event, triggers, etc) if view layer supposed exclude column, remove column

php - Image security and linux file/directory permissions -

in php app allowing users upload photos. upon user upload, metadata stored in db , images stored in directory on linux server. want these images viewable when called through view can verify correct party viewing them. not want able enter url , view image. /site /framework /protected /**my php site**/ /www /images /**this storing images**/ in order restrict viewing of these images need move images directory outside of www ? if where? what linux permissions should given on images directory? for images have stored in db want restricted access use access rules within framework. can rules such these limit access images in given directory also? any info can provided how approach (so can further research) answers questions above helpful. for images in directory denied (they must access through script , none of them have direct access available - ie server able access them, , have apache mod_rewrite ) can put .htaccess in directory following:

symfony - Join property values of a list of objects in twig -

is possible join values of properties of list of objects displaying it? like: {{ users|join(', ', username) }} where users objects, having getusername() method. suppose join doesn't take additional argument, there workaround achieve similar? can not use __tostring() function, represents else... you use.. {% set usernames = [] %} {% user in users %} {% set usernames = usernames|merge([user.username]) %} {% endfor %} {{ usernames|join(', ') }} not prettiest though. you make custom twig filter it.

What is the correct path video using Streamio FFMPEG on Rails -

i follow gem https://github.com/streamio/streamio-ffmpeg , : movie = ffmpeg::movie.new("#{rails.root}/public/aaa.mov") but result : errno::enoent: no such file or directory - ffmpeg -i /home/user/projects/test/public/aaa.mov does know ? thanks this gem assumes ffmpeg available in path . if not in path , need specify path of ffmpeg binary. ffmpeg.ffmpeg_binary = '/usr/local/bin/ffmpeg' if don't have ffmpeg install, need install it. download page

java - CardLayout: Find out if current Item is first/last in list -

i use cardlayout , want use 2 buttons .next() , .previous() scroll through items. works great 1 problem: want stop scrolling if current item first/last item. i can't find method index of current item or flag find out wether current item first/last or not. can tell me simple way find out if current item first/last? since there methods .first() , .last() jump, guessed there must method find out if current first/last. i use list<string> containing names of components in card layout, , field containing index of displayed component. to know if you're @ beginning, test if index == 0 . know if you're @ last component, test if index == list.size() - 1 . show next component, use index++; layout.show(parent, list.get(index)); .

modify and add one more condition in controller with cakephp -

i have condition in controller listing products 1 table $conditions = array('winner_id >' => 0, 'product.beg' => '1', 'product.status_id' => $status_id); i need add 1 more condition here check winner have paid also. have 1 more table accounts, , have winner id in products table. how add condition here check winners id in accounts table in same condition. need add 1 condition more, take winner_id product table , search in accounts table, , show id's there in accounts table i tried way not working: $conditions = array('winner_id >' => 0, 'product.beg' => '1', 'product.status_id' => $status_id, array('conditions' => array('product.winner_id' => $this->'account.user_id'))); if based on if condition want add condition help.. correct me if have missed something. if(condition) { $conditions + = array('field_name' => 'field_v

c++ - Dynamic linking, memory usage and concurrency -

when executable links static library, executable contains necessary library parts, used in code, right? but i'm missing part - how shared objects (the dynamic linked libraries) used exactly? as far know, not included in executable, dynamically loaded using dlopen , done directly linker, right? in case, where's library located in memory? mean, there posts here, explaining dynamic libraries reduce memory usage, how exactly? , if dynamic library somehow loaded shared memory (for several processes), how kernel handles concurrency in case? i realize fundamental , sorry if duplicate, couldn't find such. i aware of static linking vs dynamic linking , ask bit different. the shared library indeed loaded memory shared between "users" (all applications using same library). this done reference-counting, each new user of library, reference counted up. when application exits, reference count counted down. if gets zero, library no longer needed, , remov

Dynamic Image for Facebook Opengraph og:image meta tag -

i trying share image website on facebook. image can dynamic, other meta remain same. is there way can have dynamic data in og:image tag, or have go other option of fb post apis. yes , no. facebook scrapes site once, , cached metadata finds, unless go here , force scraper crawl site again. cache expire (perhaps after 1-2 days?), when requested again outside of cache period, facebook crawl site again. you can have dynamically generated og:image meta tag, read one time (per cache period), , instance of image saved. for example, if user shares page, , page returns imagea.png in og:image tag, image associated page's metadata. if user b shares same page within same cache period , facebook forgo metadata scraping , assume imagea.png still valid og:image .

configuration - How to use the global.php/local.php configs in the getConfig() of a module in a Zend Framework 2 application? -

in zf2 application have cofigs, that: 1. need different dependening on environment; 2. specific concrete module. i'm curently using here described: global.php & local.php return array( ... 'modules' => array( 'cache' => array( 'ttl' => 1, // 1 second ) ) ... ); module class module { ... public function getserviceconfig() { try { return array ( 'factories' => array( 'zend\cache\adapter\memcachedoptions' => function ($servicemanager) { return new memcachedoptions(array( 'ttl' => $this->getconfig()['modules']['cache']['ttl'], ... )); }, ... ) ); } ... } ... } it'

node.js - How to kill all child processes on exit? -

how kill child processes (spawned using child_process.spawn) when node.js process exit? i think way keep reference childprocess object returned spawn , , kill when exit master process. a small example: var spawn = require('child_process').spawn; var children = []; process.on('exit', function() { console.log('killing', children.length, 'child processes'); children.foreach(function(child) { child.kill(); }); }); children.push(spawn('/bin/sleep', [ '10' ])); children.push(spawn('/bin/sleep', [ '10' ])); children.push(spawn('/bin/sleep', [ '10' ])); settimeout(function() { process.exit(0) }, 3000);

dompdf - how can I save PdfModel to file in Zend Framework 2? -

i use zf2 , dompdfmodule\view\model\pdfmodel generate pdf. when shown view fine, cannot find out how save file (in code, without asking user download). have code this: use dompdfmodule\view\model\pdfmodel; $viewmodel = new pdfmodel($variables); $viewmodel->settemplate('pos/stocklist/' . $type); $viewmodel->setoption('papersize', 'a4'); $viewmodel->setoption('paperorientation', 'portrait'); $viewmodel->setoption('filename', 'stock.pdf'); i tried in way, render method not exist: $output = $viewmodel->render(); $handle = fopen($file_path.directory_separator.$file_name , 'w'); fwrite( $handle,$output ); fclose( $handle ); appreciate help. an example @ project's github readme page shows $viewmodel being returned controller action. also, filename option you've specified should force file downloaded rather displayed within browser. the author has implemented view strategy/renderer

Customize android google maps v2 -

how far can go, if want redraw whole screen. example if want redraw buildings color, shapes, position , on, possible? want that, can set attributes of android map, put marker, draw lines , on, there other maps, has global cover of whole world? yes. you may want read tileoverlay , moon map in google play services maps samples.

.net - Is it possible to Load/Unload projects in VS Add-In -

i'd write add-in vs gets selected project in solution, , unloads projecs dependent on it. possible? i know there's possibility make using macros, i'd make using add-in. here's solution private const string unloadprojectcommandname = "project.unloadproject"; private const string reloadprojectcommandname = "project.reloadproject"; public void exec(string commandname, vscommandexecoption executeoption, ref object varin, ref object varout, ref bool handled) { handled = false; if (executeoption == vscommandexecoption.vscommandexecoptiondodefault) { if (commandname == "build7.connect.build7") { handled = true; var solution = (((solutionclass)(_applicationobject.solution))); var solutionexplorer = _applicationobject.windows.item(constants.vswindowkindsolutionexplorer); solutionexplorer.activate();

My Verilog behavioral code getting simulated properly but not working as expected on FPGA -

i wrote behavioral program booth multiplier(radix 2) using state machine concept,am getting the results during program simulation using modelsim, when port fpga(spartan 3) results not expected. please me this.where have gone wrong? module booth_using_statemachine(mul_a,mul_b,mul_result,clk,reset); input mul_a,mul_b,clk,reset; output mul_result; wire [7:0] mul_a,mul_b; reg [7:0] mul_result; reg [15:0] r_b; reg [7:0] r_a; reg prev; reg [1:0] state; reg [3:0] count; parameter start=1 ,add=2 ,shift=3; @(state) begin case(state) start: begin r_a <= mul_a; r_b <= {8'b00000000,mul_b}; prev <= 1'b0; count <= 3'b000; mul_result <= r_b[7:0]; end add: begin case({r_b[0],prev}) 2'b00: begin prev <= 1'b0; end 2'b01: begin r_b[15:8] <= r_b[15:8] + r_a; prev <= 1'b0; end

visual c++ - Serial port programming - Recognize end of received data -

i writing serial port application using vc++, in can open port on switch device, send commands , display output. running thread read open port output of given command. main thread waits until read completes, problem how recognize command output ends, , should signal main thread. almost serial port communication requires protocol . way receiver discover response has been received in full. simple 1 using unique byte or character can never appear in rest of data. linefeed standard, used modem example. this needs more elaborate when need transfer arbitrary binary data. common solution send length of response first. receiver can count down received bytes know when complete. needs embellished specific start byte value receiver has chance re-synchronize transmitter. , includes checksum or crc receiver can detect transmission errors. further embellishments make errors recoverable ack/nak responses receiver. you'd on way in re-inventing tcp. ratp protocol in rfc-916

batch script to fix for me -

this code echo every line number of character , character not right. try fix. main thing variable count must stay instead of %%m. please explain me row call!!! and how make last row show last character of input word. @echo off :input set /p word=input word: if not defined word goto input (echo %word%)> tempfile.txt %%x in (tempfile.txt) ( set /a lenght=%%~zx - 2 ) del tempfile.txt echo %word% got %lenght% characters setlocal enabledelayedexpansion /l %%m in (1,1,!lenght!) ( set /a count=0 set /a count=count+%%m call echo !count! %%word:~!count!,1%% ) endlocal pause so, here output: input word:qwertzuio qwertzuio got 9 characters 1 w 2 e 3 r 4 t 5 z 6 u 7 8 o 9 press key continue... when echoing character, using !count! index, count starting @ 1, whereas need start indexing @ 0. try this: for /l %%m in (1,1,!lenght!) ( set /a count=%%m set /a index=%%m-1 call echo !count! %%word:~!index!,1%% ) i'm setting index %%m-1 s

sql - I can't see my model classes -

i have application in mvc4 razor , entity framework database first.i have sql database . base on generated diagram (edmx) new item "ado.net entity data model".i choose database connection,my tables , program has generated diagram tables , relationships can find class must generated after each choosen table (in solution explorer .for table student database must have mapping class student in solution ).i want add validations .can tell done wrong ? the edmx diagram has "code-behind" file. click > beside .edmx file , should see file named same .edmx ending in .designer.cs; classes defined in "entities" region in file. having said that, should never edit contents of file. code in there generated diagram, changes lost when alter data model elsewhere. if want add validation attributes models, you'll need create partial declarations somewhere else, , attach metadata classes them. accepted answer this question shows you'll need do.

cmd - Is it possible to edit a binary file using Windows command line? -

is there way in windows edit binary file, command line? i.e. way written batch file? i want able edit single byte, @ known position, in existing file. this existing question[1] solved, that's linux solution. i'm looking similar windows. background there's bug in gta 1 when downloaded steam whereby save-game data file gets corrupted on exit. result, game can played fine first time subsequently crashes. turns out can fixed changing 5th byte in file (i.e. byte @ address 0x04) x00 x06[2]. i can in python easily, e.g.: with open("player_a.dat", "rb") f: bytes = f.read() bytes = bytes[:4] + '\x06' + bytes[5:] open("player_a.dat", "wb") g: b in bytes: g.write(b) ideally though i'd rather in batch job following: fixes data file launches gta i make works me (using python), wouldn't random other people don't have python (yes know it's easy & install, still). similarly, there freeware

cordova - Android DroidGap disabling back button -

please, suggest, how can disable button press event while working phonegap ? i need in activity , ( droidgap code) controlling button event. even, following code works in activity , not working when being used droidgap . @override public boolean onkeydown(int keycode, keyevent event) { if (keycode == keyevent.keycode_back) { //preventing default implementation previous android.os.build.version_codes.eclair return true; } return super.onkeydown(keycode, event); } calling setonkeylistener on appview helped me out. i had make minor change in above code snippet, follows: appview.setonkeylistener(new onkeylistener() { public boolean onkey(view v, int keycode, keyevent event) { if (keycode == keyevent.keycode_back) { return true; } return onkeydown(keycode, event); } }); edited there occurs 2 actions while key-pressing event - action up & action down so, following should u

How to perform split and join functions on Array in C? -

how can perform join , split functions on array elements in c? for example, let's have 2 arrays: int value[]= {0,1,2,3}; int id[] = {1,1,3,3}; // want join elements of "value" array whoz value of "id" same. //in case 0,1 elements "value" array has same "id" value 1,1 //and 2,3 "value" has same "id" value 3,3. join {01,23} //and if want perform split function give me back{0,1,2,3} i did same thing in perl script not sure how can functionality in c? c doesn't have built-in "dynamic" arrays of many higher-level languages. you must allocate needed storage using malloc() , copy desired data element element new array. also can't quite understand desired operations describe ... "join elements of value value of id same" doesn't make sense. do want compute intersection of arrays? they're not sets, doesn't sound right either.

windows - list of various system-files safe to ignore when implementing a virtual file system -

Image
i'm working on webdav-server presents information database in virtual filesystem. so user able create files on server , automagically created in db. now user connects server, oss tend create own metadata-files/folders (thinking thumbs.db, desktop.ini, .fseventsd, ds_store, ...) this files clutter database - , tend bring down performance (osx example lot of indexing folder opened, means tons of hits against database) so performances , cleanliness's-sake i'm looking "complete" list of (meta)files/folders created various os - "safe" suppressed server. my list far: //todo: rid of system files /* *** everywhere * thumbs.db * desktop.ini * .ds_store * .desktop * albumart*.jpg * folder.jpg * ._[parentfoldername] // e.g. /foo/bar/._bar * ._[existingfoldername] // e.g. /foo/._bar * ._[existingfilename] // e.g. /foo/bar/._baz (baz legit file inside bar) * ._. // ?!? *** root * system volume information * .fseve

python - plot a large number of axis objects using one command through a loop -

say have bunch of ax1,ax2,ax3... , want run them through plotting function: def plotxy(ax,x,y): x = np.array(x) y = np.array(y) ax.plot(x,y) (obviously simplified) how repeat command without doing: plotxy(ax1,x,y) plotxy(ax2,x,y) ... plotxy(axn,x,y) i'm sure there way create temp variable holds axn in loop 1 line. ideas? shorten code i've got heaps of things need plot same command differing x & y , on multiple subplots. i guess part of large question of constructing variable names using loop? you can try this: import matplotlib.pyplot plt fig, axs = plt.subplots(nrows=3, ncols=2) ax in axs.flat: plotxy(ax,x,y) if use plt.subplot or plt.axes can create list/array of axes hand