Posts

Showing posts from July, 2015

c++ - find sum of diagonal elements from given index in 2d array -

i have construct 2d array n,m rows , columns (n & m <= 5), user enters index(location) 2,3 (matrix[2][3]) it's assumed 2 numbers in bounds of matrix. on have find sum of left , right diagonal goes through number, number excluded sum. so example 2d array myarray[3][3] *1* 15 *2* 2 *71* 8 *5* 22 *5* so user enters 1,1 myarray[1][1], in case number 71, sum 1 + 5 + 2 + 5 ... , problem how can find diagonals without going out of bounds. for left top go: row-- column-- while(row >= 0|| column >= 0) left bottom: row++ colum++ while(row < n || column < m) right top: row-- column++ while(row >= 0 || column < m) right bottom: row++ column-- while(row < n || column >=0) (this bad written pseudo-code, sorry) it works fine when enter numbers aren't in top or bottom row, in cases located there program stops. what have pseudocode. first thought should using &&'s instead of ||'s when determining if location out of boun

javascript - Select Hexagonal Face in OctahedronGeometry THREE.js -

Image
i have geodesic sphere - created using three.octahedrongeometry - group triangular faces hexagonal faces, can selected. i'm @ loss how approach problem or if it's feasible. insight appreciated. here's example: creategeodesicsphere =-> geometry = new three.octahedrongeometry(200, 3) material = new three.meshbasicmaterial({ color : 0xffffff, shading : three.flatshading, side : three.doubleside, vertexcolors : three.facecolors, overdraw : true }) # explode geometry each face has unique vertices explodemodifier = new three.explodemodifier() explodemodifier.modify(geometry) geodesicmesh = new three.mesh(geometry , material) geodesicfaces = geometry.faces in [0..geodesicfaces.length-1] geodesicfaces[i].color.setrgb(math.random(), math.random(), math.random()) geodesicmesh.position.x

ruby on rails - I18n error in one file, but not another in same directory -

i have 2 lib classes in rails project. both print out error using same syntax i18n.t('.config_error') one file succeeds, other file fails error: i18n::invalidlocaledata: can not load translations /home/hellebusch/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/locale/en.yml: #<errno::enoent: no such file or directory> i cannot find answer issue. insight great. i believe "." in i18n.t('.config_error') means i18n looking config_error key in namespace of resource being rendered. if rendering posts#show view, i18n looking in posts namespace - aka looking key nested under posts key. does help? posting classes/views call i18n.t('.config_error') helpful.

ios - Using UIPageViewController to sign-up user -

i working on user sign-up part of ios app , trying use page views user input. so, first page view takes user's first name, next 1 takes takes last name, phone number. user receives verification code put in user in next page view. when verification code correct user allowed go (swipe right) next page view. the problem facing unable trap user input in properties of view controller derives uipageviewcontroller. i using : - (uiviewcontroller *)pageviewcontroller:(uipageviewcontroller *)pageviewcontroller viewcontrollerafterviewcontroller:(uiviewcontroller *)viewcontroller { nsuinteger index = [(signupchildviewcontroller *)viewcontroller index]; signupchildviewcontroller *current=(signupchildviewcontroller *)viewcontroller; nslog(@"%@", current.usercredentials.text); if(index==3) { firstpass=yes; if([verificationcodeuser isequaltostring:verificationcode]) { verificationpassed=yes; index++; }

Compound PHP statement not working -

i'm having issues getting bit of code working. want if page loads template, , 1 of 4 possible categories specified execute action. if (is_page('combined-feed') , ($event_category=='179' || $event_category=='180' || $event_category=='181' || $event_category=='1028')) { $description = "description goes here"; } i tried using structure similar found in this thread , have had no luck getting meet criteria of if statement. know there's going wrong or statements, haven't been able figure out how structure code better. update: turns out there nothing structurally wrong code, had issue if statement. i write code way if (is_page('combined-feed') && ($event_category=='179' || $event_category=='180' || $event_category=='181' || $event_category=='1028')) { $description = "description goes here"; } in way, || operators evalua

tile - How to repeat a bitmap with allegro 5 -

i have 400x400 image need tile in allegro 5. need tile various sizes cannot create larger image. however, google search returned nothing this, nor did search on site. there way of doing (like can in directx/opengl texture wrapping, clamping , reflecting) without drawing image on , on again? both graphic apis internally, there no "tiling" function included on allegro have implement own. render time impact non-existing since still below millions of triangles per second current cards can draw. bonus, can use al_hold_bitmap_drawing(true) draw tiles wish same bitmap have more framerate.

javascript - Possible to change location.href of a div without using iframe? -

i want try this, change href location specific div. know can use iframe trying avoid frames. there way accomplish this, user click button , source of single div changes rest of site stays same. <script> function chdiv() { document.getelementbyid("div2").location.href="google.com"; } </script> <div id="div1"> <button id="change" onclick="chdiv();" </div> <div id="div2"> <div> no, , divs don't have location property. may doing ajax request bring in whatever html need. $.get('url', function (data) { $('#div2').html(data); });

javascript - How to open URL in the same window in Node-Webkit? -

var win = gui.window.open('https://github.com', { position: 'center', width: 901, height: 127 }); this open url in new window, how open (redirect) url in same main window? you can use normal html window functions. window.location.href = 'http://example.com'; just sure include node-remote: 'http://example.com' in package.json if plan use default nodewebkit functionality when page loaded.

junit - How to remove 'internet explorer block this website from displaying content with security certificate errors' while running selenium scripts in IE10 -

i running scripts in ie10, requirement view document, blocked due security question 'internet explorer blocked website displaying content security setting errors' i want rid of message, have ides on i not sure, try add website in 'trusted sites'. (internet options --> security --> trusted sites --> click sites button) then change 'trusted zone' settings allow website run scripts. cautious add sites trust.(internet options --> security --> trusted sites --> click custom level)

xml - OSB replace node -

i've been trying replace node action "replace" don't understand, hope me. i've errorhandler, inside stage , inside; assign > replace > reply. in assign; expression: $body variable: faultstring in replace; xpath: . in variable: faultstring expression: $body replace node contents in reply; failure so here i'm getting echo, this; <soapenv:envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:cli="http://www.xxxx.com.mx/xxxx/xxxxxxx"> <soapenv:header xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"></soapenv:header> <soapenv:body> <cli:getxxxxxxxxxxxxxxx> <json>{"principal":"principal","secundario":"secundario"}</json> </cli:getxxxxxxxxxxxxxxx> </soapenv:body> </soapenv:envelope> i want replace node <json>{"principal":&

Meteor Autoform pushArray with nested schema -

i'm using autoform meteor. have array of nested schemas, so: addresses: { type: [schemas.address], optional: true, defaultvalue: [] } and i'm attempting add address array using update-pusharray {{> quickform id="myformid" type="update-pusharray" doc=getdocument collection=getcollection scope="addresses"}} but i'm getting these gems: minimongoerror: cannot apply $push modifier non-array "mongoerror: field 'addresses' must array of type object in document {_id: "383efpjgezqjfgs72"} [409]" so tried wrapping in array in formtodoc hook: simpleschema.clean: filtered out value have affected key "0", not allowed schema so... yeah. that's limit of fresh ideas. have? it looks there issue update-pusharray type until few days after posted question. according aldeed need running autoform 5.0.2 , meteor 1.0.3.1 or higher work. http://github.com/aldeed/meteor-autoform/issues/78

mysql - How can I select the distinct value of two tables? -

i'm not sure it's possible select distinct value of 2 tables columns. consider table1 like: ╔══════╗ ║ col1 ║ ╠══════╣ ║ aaa ║ ║ aaa ║ ║ bbb ║ ║ bbb ║ ╚══════╝ and table2 like: ╔══════╗ ║ col1 ║ ╠══════╣ ║ aaa ║ ║ bbb ║ ║ ccc ║ ║ ccc ║ ╚══════╝ the output be: aaa bbb ccc obviously like: select distinct table1.col1 , table2.col1 table1 , table2; won't work. sqlfiddle a simple union tricks select col1 table1 union select col1 table2; there no need use distinct keyword union handle duplicates. fyi if use union all duplicates won't handled anymore, need use distinct .

Best approach to poll information from a database within an EJB -

i trying poll information database in ejb. specifically, need check if condition met before proceeding other business logic in ejb. know best approach tackle this? thinking of sort of job scheduler polls info database, , once condition met notify ejb continue. believe using thread.sleep in loop during transaction bad idea, not sure. help. well, after research ended using ejb timer , @asynchronous annotation on ejb method (both methods worked well). idea set timers query database periodically , check if condition interested in met.

entity framework - EF6 Code first migration Oracle ODP.Net PLS-00103 -

i'm using ef6 oracle odp.net , code first migration in app. when run update-database i'm getting: oracle.manageddataaccess.client.oracleexception (0x00001996): ora-06550: line 1, column 6: pls-00103: encountered symbol "" when expecting 1 of following: but when run update-database -script the generated script works fine on database. after trying update-database -verbose i found difference in scripts generated 'update-database -verbose' begin execute immediate 'create index "sys_mzk"."ix_realizacje_kursow_r_6940446" on "sys_mzk"."realizacje_kursow" ("rlk_fk_kur_id")'; exception when others if sqlcode <> -1408 raise; end if; end; begin execute immediate 'create index "sys_mzk"."ix_realizacje_kurso_1395326627" on "sys_mzk"."realizacje_kursow" ("rlk_fk_pnm_id_akt_pol")'; exception wh

java - Good design for accessing subclass methods in a vector of abstract class objects -

i using vector store objects of anabstractclass superclass. abstract class contains 2 non-constructor methods: public final string getname() { return name; } public abstract int getcost(); within each subclass created getcost method. within anotherclass have vector of abstract class objects. in method of anotherclass using string contains name, cost, , other data types specific each of multiple subclasses. accessing vector retrieve name , cost fine. however, when try access other fields (ie: getcolor or getsize specific each subclass run following compile error: error: cannot find symbol symbol: method <mysubclassmethod>() location: class <myabstractclass> how can efficiently design solution dilemma? to access methods specific subclass need cast subclass. example: subclass foo = (subclass) myanabstractclassinstance; if don't know subclass have, can type check using instanceof example // subclass implements size , colo

c++ - "Forwarding" string literals -

i dealing library has variadic macro meant used printf #define printf_like (format, ...) //some statement expression since printf_like required evaluate something, , in order avoid usual if , dangling else issue macros having multiple statements, implemented using gcc's statement expressions . however, need code build intel compiler, doesn't allow destructible entities inside statement expression . means can't write code this: printf_like("%s", getstring().c_str()); where getstring returns std::string . work around this, have simple variadic template wrapper. template <typename ... rest> int callprintflike(const char* const format, rest... rest) { return printf_like(format, rest...);//warning: format string not string literal [-wformat-nonliteral] } and use this: callprintflike("%s", getstring().c_str());//warning shown in above comment this trips clang , gcc's -wformat-nonliteral warning. there way me somehow "fo

sql - why when I execute a select query on a view in vertica, do I get "Length for type varchar cannot exceed 65000"? -

i have flextable in vertica , trying create view based on it. here's create view statement: create view testview select coalesce ( "user_id", "userid", "sm.actor.id", "sm.participant.userid", "sm.userid", "sm.uid", "sm_c.userid", "sm.id" )::varchar userid flex_table_test "sm.verb" not null i can create view successfully, when execute like: select * testview limit 10; i get: error 3852: length type varchar cannot exceed 65000 if execute select part of view itself, works fine. tried casting output fields, doesn't seem make of difference. by default, data in flex tables stored long varbinary has default raw size of 130000. since data longer maximum length varchar (65000), need either truncate result o

Accessing the DOM in a Firefox for Android add-on -

this sounds simple question, i've been going through mdn documentation of "firefox android" , can't seem figure out. i'm trying build simple "firefox android" add-on, inserts script tag visited pages. i've tried following code (leaving out template boilerplate code ): function loadintowindow(window) { if (!window) return; menuid = window.nativewindow.menu.add("insert", null, function() { insertscript(window); }); } function insertscript(window) { // none of these properties exist: window.document.body.innerhtml, window.body.innerhtml // window.document.body.innerhtml = "<h1>this page has been eaten</h1>"; // var contentscriptstring = 'document.body.innerhtml = "<h1>this page has been eaten</h1>";' // throws error "referenceerror: require not defined" // var tabs = require("sdk/tabs"); // tabs.activetab.attach({

wordpress - strip out array from wpdb get_col query results? -

how can function return value, rather array? $results = $newdb->get_col( "select itemid, price $table itemid = $quanid group price order count(*) desc limit 1", 1 ); this result when print_r( $result ); : array ( [0] => 40 ) this need: 40 try $wpdb->get_var() if have more results one, you'll first one.

c - How does list joining algorithm work? -

Image
i have found in wayland protocol source code following function. void wl_list_insert_list(struct wl_list *list, struct wl_list *other) { if (wl_list_empty(other)) return; other->next->prev = list; other->prev->next = list->next; list->next->prev = other->prev; list->next = other->next; } which operates on list has links so: struct wl_list { struct wl_list *prev; struct wl_list *next; }; it doubly linked list other. however not understand function @ all. me looks link 'other' lost both lists, , *list , *list->next links cross on other list. also: not circular list. head , tail links point themselves.[edit] bad, in fact circular list. makes sense way. could me understand how algorithm works. alot. i drew pictures, stared @ them in confusion until realized magic. list , other not nodes, list objects . yes, other removed "it's list of nodes" because want add no

node.js - Display multiple validation errors for Mongoose model -

if have schema: var userschema = schema( {name : { type: string } }); userschema.path('name').validate(function(value) { return value.length > 4; }, 'name short'); userschema.path('name').validate(function(value) { return hasnonumbers(value); }, 'name cannot have numbers'); var user = mongoose.model('user', userschema); then create model , run validate function: var newuser = new user({name: '1da'}); newuser.validate(function(err) { console.log(err.errors.name); }) this logs first error message 'name short'. however, name property fails both validation requirements. there way display both error message? thanks apparently feature isn't implemented in v3 of mongoose. https://github.com/learnboost/mongoose/pull/1214#issuecomment-15746525 when v4 become stable, i'll give try again. until then, module seems solve issue: https://github.com/szdc/mongoose-validate-

r - R_number of pairs for each lag in a Variogram -

i using geor package spatial interpolation of rainfall. have tell quite new geostatistics. video tutorials in youtube, understood (well, think so) theory behind variogram. per understanding, number of pairs should decrease increasing lag distances. eg, if consider 100m long stretch (say 100m long cross section of river bed) number of pairs 5m lag 20 , number of pairs 10m lag 10 , on. kind of confused output variog function in geor package. example given below mydata x y [1,] 415720 432795 2.551415 [2,] 415513 432834 2.553177 [3,] 415325 432740 2.824652 [4,] 415356 432847 2.751844 [5,] 415374 432858 2.194091 [6,] 415426 432774 2.598897 [7,] 415395 432811 2.699066 [8,] 415626 432762 2.916368 this dataset a variable (rainfall intensity) , x, y coordinates of points. varigram calculation shown below geodata=as.geodata(data,header=true) variogram=variog(geodata,coords=geodata$coords,data=geodata$data) variogram[1:3] $u [1] 46.01662 107.37212 138.04987 19

python 2.7 - How would you code this? Should I use a loop or keep it how I have it coded? -

i have method nba basketball game simulation. method checks variable named self.quartermins tell if minutes in quarter done. changes index 2 different variables use in code tell quarter being played. def checkquarter(self): # method checks , makes sure quarter , game aren't over. self.quarterindex = 0 if self.quartermins[0] > 0: self.quarterindex = 0 self.playermins = -4 elif self.quartermins[1] > 0: self.quarterindex = 1 self.playermins = -3 elif self.quartermins[2] > 0: self.quarterindex = 2 self.playermins = -2 elif self.quartermins[3] > 0: self.quarterindex = 3 self.playermins = -1 else: return false the following method same: def checkquarter(self): self.quarterindex = 0 in xrange(4): if self.quartermins[i] > 0: self.quarterindex = self.playermins = -4 + break else: return false th

c++ - OpenGL Height Map from text segmentation fault -

i trying create heightmap 25 float values so: #define height_verts 5 #define vals_per_vert_height 5 float heightmapverts[ height_verts*vals_per_vert_height ] = { //5 -0.9, -0.6, -0.4, -0.6, -0.9, -0.2, 0.1, 0.3, 0.1, -0.3, 0, 0.4, 0.8, 0.4, 0, -0.2, 0.1, 0.3, 0.1, -0.3, 0.5, -0.6, -0.4, -0.6, -0.9, }; i getting segmentation fault when calling: gldrawarrays(gl_triangles, 0, height_verts); i have been suggested it's because size argument of glvertexattribpointer() must 1, 2, 3, or 4. pass 5 with: glvertexattribpointer(vertlocheight, vals_per_vert_height, gl_float, gl_false, 0, 0); but error saying have many vertices if these values smaller (eg: #define vals_per_vert_height 3) error: many initializers ‘float [15]’ i have attached rest of code context, very new opengl apologize if code messy. #include <stdio.h> // glew loads opengl extensions. required opengl programs.

iphone - Xcode 6 Validate/Submit inactive -

i'm trying upload first apple app , i've been not able further point within last 7 days, reaching out help. i have app preset in itunesconnect , certificates available , able run app on device, when comes time create archive can see building without errors , can see .xcarchive file being created neither validate nor submit buttons available me click on. also when click on archive says archive type: generic xcode archive , both version , identifier have unspecified next them. again, i've been trying solve week, , tried lots of stuff online watching course on pluralsight on deploing ios apps apple store , had no luck figuring out yet. what missing? i'm not sure problem is, how solve it.. 1) create smaller project may 1 single page app , try want way appstore 2) once got 1 work add project smaller project , see issues are.. hope helps!

html - Why do these two div elements not align to the top using display inline block; vertical align: top? -

in below code there 2 child div elements .left , .right. im using margin left move .right right , im using display inline block make div size of content , thought getting divs align top of each other. 1 on right appears lower. why? <style type="text/css"> html,body{ color:#fff; } .container { background: linear-gradient( right, #ff9e2c 0%, #ff9e2c 50%, #b6701e 50%, #b6701e 100% ); height: 500px; width: 100%; } .left{ width:40%; padding: 10px; vertical-align: top; } .right{ margin-left: 50%; padding: 10px; width: 40%; vertical-align: top; } </style> <section class="container"> <div class="left"> lorem ipsum dolor sit amet, consectetur adipisicing elit. sed, consequuntur.</div> <div class="right">lorem ipsum dolor sit amet, consectetur

random - Include php file randomly -

i have question php include. here goes existing code have. <?php srand(); $files = array("folder/content1.php", "folder/content2.php", "folder/content3.php", "folder/content4.php"); $rand = array_rand($files); include ($files[$rand]); ?> this code works me content displaying randomly. but, better. because, using code, everytime have added new content content5.php , content6.php , on, have bother update code above make new content.php appear. is there solution can have, not bother code above everytime add new content.php , new content.php appears automatically when added? possible? updated: new testing code(tested failed again part of page mising) <?php $sdirectory = 'myfolder'; if( is_dir( $sdirectory ) ) { $rdir = opendir( $sdirectory ); while( ( $sfile = readdir( $rdir ) ) !== false ) { if( ( $sfile == '.' ) || ( $sfile === '..' ) ) { continue;

c# - 0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'cookie' -

Image
i developing mvc web application. have added following scripts in bundle bundles.add(new scriptbundle("~/bundles/adminscripts").include( "~/scripts/jquery.js", "~/scripts/bootstrap.js", "~/scripts/jquery.dcjqaccordion.2.7.js", "~/scripts/jquery.scrollto.min.js", "~/scripts/jquery.nicescroll.js", "~/scripts/jquery.sparkline.js", "~/scripts/assets/jquery-easy-pie-chart/jquery.easy-pie-chart.js", "~/scripts/owl.carousel.js", "~/scripts/jquery.customselect.js", "~/scripts/respond.js", "~/scripts/slidebars.js", "~/scripts/common-scripts.js", "~/scripts/sparkline-chart.js",

java - What's wrong with using static for Parent Activities? -

let's have parent activity parenthost static reference: parenthost extends fragmentactivity { static parenthost parent_host; static viewpager pager; now let's use reference like: public class testpage extends fragment { button.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { //what's wrong this? parenthost.pager.setcurrentitem(1); or: parenthost.parent_host.finish(); } }); i've tried breaking app (start,pause,killed ram) , haven't seen issues. is method ok parent activities? for future readers: switching ((parenthost) getactivity()).whatever() , appropriate way of using instance of running class. gabe's comment: the reason safe held in instance variable , not in static. though there's 1 reference gc can tell reference held 1 of ch

python - Flask Debugger not working under Windows -

i newbie python attempting experiment sample code under windows 8.1. on http://flask.pocoo.org/docs/0.10/quickstart/ says "if enable debug support server reload on code changes, , provide helpful debugger". i have added code app.run(debug=true) sample code on above page. server reload on code changes (as promised) when create syntax error "helpful debugger" not show. instead error message in command prompt. any ideas why? suspect answer might here can't enable debug mode in flask largely uninteligible me. so far have tried restarting machine , putting code in different locations. not in forked environment (as best know). curious source code shown below: from flask import flask app = flask(__name__) werkzeug.debug import debuggedapplication app.wsgi_app = debuggedapplication(app.wsgi_app, true) @app.route('/') def hello_world(): return 'hello world! #note deliberate syntax error if __name__ == '__main__': app.debu

Ruby - can't install sanitize gem, Nokogiri dependency -

i'm running mac os x 10.10.2, trying install sanitize gem , error below. have read there problems of sort nokogiri gem , xcode. can fix this? alternatively, there gem can use strip html away string? (i want content). libiconv missing. please visit http://nokogiri.org/tutorials/installing_nokogiri.html installing dependencies. ----- *** extconf.rb failed *** not create makefile due reason, lack of necessary libraries and/or headers. check mkmf.log file more details. may need configuration options.

Restrict Fast Forward iPhone video.js -

i'm having hard time trying figure out how restrict fast forwarding videos playing in iphone. have advice? unfortunately can't. ios doesn't allow customisation of controls in full screen playback, , playback full screen on iphone.

c# - .NET Fetch all exception in 3rd party app -

we integrating 3rd party application supplying file can import. file contains many properties(+100) , not of them mandatory, need few. however, application keeps crashing(gently, alert due big try catch) 'object not set reference ...' without stacktrace. @ place 3rd party app not verifying optional parameters on nulls causing crash. searching property searching needle in haystack. is possible somehow monitor exceptions of application don't have source of if caught? can stacktrace , check ilspy property causing problem. the 3rd party app relatively big company. cannot communicate developers. you try: assembly otherassembly = typeof(/* class of other assembly */).assembly; appdomain.currentdomain.firstchanceexception += (sender, fceea) => { appdomain domain = (appdomain)sender; var method = fceea.exception.targetsite; var declaringtype = method.declaringtype; var assembly = declaringtype.assembly; if (assembly == otherassembly)

html - How to display whitespace characters using Unicode for debugging/editing -

i want display whitespace characters while debugging or editing text replacing them sensible unicode code points , colouring them grey instead of black. for example, replace space u+0020 middle dot · u+00b7 no-break space   u+00a0 medium small white circle ⚬ u+26ac rightwards arrow → u+2192 tab u+0009 . and on... i'm looking sensible glyphs for: carriage return u+000d newline/line feed u+000a . i don't want use pilcrow sign ¶ u+00b6 doesn't intuitively correspond either rather concept of new paragraph. there downwards arrow corner leftwards ↵ u+21b5 again, seem more combination symbol representing either 1 individually. when have mixed line endings want able see character being used (or both). displaying output in html in browser. currently can't think of better symbols than: - leftwards arrow ← u+2190 carriage return - downwards arrow ↓ u+2193 newline . i aware of symbol carriage return ␍ u+240d , symbol line feed ␊ u+240a , symbol

knockout.js - Unable to work out simple helloworld example of KnockOut -

i trying use knockout despite simple code unable select list populated. below code, can point out doing wrong <html> <head> <script type="text/javascript" src="knockout-3.3.0.js"> </head> <body> <script type="text/javascript"> var listeditorviewmodel = function () { this.allitems = ko.observablearray(["apple"]); } ko.applybindings(document.body,new listeditorviewmodel()); </script> <div>this select populated</div> <select multiple="multiple" data-bind="options: allitems"></select> </body> </html> your parameter order in applybindings incorrect - first parameter must model , second parameter dom element. update code this: ko.applybindings(new listeditorviewmodel(), document.body); or omit second parameter, because binding document anyway: ko.applybindings(new listeditorviewmodel

mysql - getting data in single query -

say have following: id bill vote 1 x 1 2 y 1 3 y 0 4 z 1 5 x 1 what want query return is: bill vote(1) vote(0) x 2 0 y 1 1 z 1 0 vote(1) count of data (1), same applies vote(0) select bill, sum(vote) vote_1, sum(1-vote) vote_0 tablename group bill the first sum used sum 1's. second 1 sum 0's (1-1 = 0, 1 - 0 = 1!)

javascript - Function to exit a parent function -

i have loop runs indefinitely until tell stop. using requestanimationframe , lot more going on, below example simplify question. var _stop = false; var loop = function () { while (!_stop) { if (some condition met) { stop(); } /* something. */ loop(); } }; function stop() { _stop = true; } now works great, still run /* */ 1 more time before stops. want stop , return. of course can done so: if (some condition met) { stop(); return; } but there way include return part stop(); ? doesn't want obvious reasons: function stop() { _stop = true; return; } but there way achieve this? var _stop = false; try { var loop = function () { if(!_stop) { if (some condition met) { stop(); } /* something. */ loop(); } }; } catch(e) { } function stop() { _stop = true; throw new error("use precaution"); } the loo

ios - sorting NSArray of strings with numbers -

this question has answer here: how natural sort on nsarray? 5 answers i have array contains these string. @"common area", @"building 1", @"building 2", @"building 3", @"building 4", @"building 10", @"building 14", @"car park", i trying sort alphabetically this areaarray = [areaarray sortedarrayusingselector:@selector(localizedcaseinsensitivecompare:)]; but displayed like @"building 1", @"building 10", @"building 14", @"building 2", @"building 3", @"building 4", @"car park", @"common area", where displayed as @"building 1", @"building 2", @"building 3", @"building 4", @"building 10", @"building 14", @"car park", @"common ar

ftp - Identify an incoming file through NetworkStream C# -

i making client/server chat application using tcpclient , tcplistener classes. should able transfer text messages , files between client , server. able handle text messages making thread each separate client , making secondary thread receiving incoming message making primary thread reserved sending messages. if able identify incoming message file , not text message know how handle using networkstream , filestream. unable so. code handle incoming file here . please tell me if there limitations using networkstream ftp. answer: build own protocol. by building own communication protocol can control data/message flow. for example; 1-user wants send file server 2-client sends command inform server send file.like ; @file@filename;filesize; 3-server sends ready message client @fileaccepted@ 4-server begins listen buffer packages , when receives writes them stream. 5-when client receives {@fileaccepted@} command begins send packages server. sure buffer sizes same. 6-whe

php - HTTP Post using Thread -

i want send string using http post method server (www.000webhost.com) using thread method in android.but unfortunately not responding`httppost httppost = new httppost(" http://192.168.2.1:53811/winnersite/webservice.asm/mymethod try { // add data list namevaluepairs = new arraylist(2); namevaluepairs.add(new basicnamevaluepair("json", name)); // namevaluepairs.add(new basicnamevaluepair("stringdata", "anddev cool!")); httppost.setentity(new urlencodedformentity(namevaluepairs)); // execute http post request httpresponse response = httpclient.execute(httppost);`

entity framework - I am getting error of conflict in asp.net MVC5 -

Image
i getting error of conflict in asp.net mvc5 here model class of form model [databasegenerated(databasegeneratedoption.identity)] [key] public guid formid { get; set; } public guid entityblockid { get; set; } // linktoentityblockid public virtual entityblock entityblock { get; set; } here model class of entityblock model [databasegenerated(databasegeneratedoption.identity)] [key] public guid entityblockid { get; set; } public virtual icollection<form> form { get; set; } and inserting value below: formstaticmethodscontroller formstaticmethodscontrollerobj = new formstaticmethodscontroller(); form form = new form(); form.entityblockid = linktoblockid; formstaticmethodscontrollerobj.createform(form); method is: public guid createform(form form) { db.forms.add(form); db.savechanges(); return form.formid;

How can I make a Python function examine every element of a list? -

i ordered build bulean function takes list of numbers , execute "true" if list proper grade list(i.e every number between 0 100) , "false" otherwise. encounter error, caused, believe not thorough acquaintance program. reason why ask here learn doing. i tried few scripts. 1 of them: def isvalidgradelist(i): x in range(0,len(i)+1): if i[x] not in range (0,101): return false else: continue return true as see, code won't way in scripter. how can attend it? appreciate help. thank help. unfortunately, not use "all" built-in function yet, we've not learned how use it. is, however, i've done far. seems working. def areintegers(i): x=0 x in range(0,len(i)): if type(i[x])==int: x=x+1 else: return false return true def isbounded(i): x=0 x in range(0,len(i)): if i[x] in range(0,101): x=x+1 else:

android - Why is my doInBackground called so many times? -

i have navigation drawer , onclick follows: private class slidemenuclicklistener implements listview.onitemclicklistener { @override public void onitemclick(adapterview<?> parent, view view, final int position, long id) { // system.out.println("clicked"); mdrawerlayout.postdelayed(new runnable() { @override public void run() { displayview(position); } }, 200); } } my displayview(position); method is: private void displayview(int position) { // update main content replacing fragments fragment fragment = null; switch (position) { case 0: fragment = new fragmenttab1(); break; case 1: fragment = new fragmenttab2(); break; case 2: fragment = new fragmenttab3(); break; case 3:

java - index.jsp not working, just shows source code on browser -

in spring mvc application, i'm trying pass list jsp page , show on table, index.jsp isn't rendered , shows source code on browser. here controller: package com.orantaj.controllers; import com.orantaj.service.eventservice; import org.springframework.beans.factory.annotation.autowired; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.restcontroller; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; @restcontroller public class indexcontroller { @autowired eventservice eventservice; @requestmapping(value = "/") public void setevents(httpservletrequest request, httpservletresponse response) { try { request.setattribute("basketballevents", eventservice.getbasketballevents()); request.getrequestdispatcher("index.jsp").forward(request, response); } catch (exception e) { e

matlab - 0-by-1 sym - What do I need to change in order to get proper symbolic results? -

i solve system of equations symbolically beta1 , beta2 , , beta3 . defined variables follows , set equation system: w1 = sym('w1', 'real'); w2 = sym('w2', 'real'); me1 = sym('me1', 'real'); me2 = sym('me2', 'real'); btm1 = sym('btm1', 'real'); btm2 = sym('btm2', 'real'); mom1 = sym('mom1', 'real'); mom2 = sym('mom2', 'real'); gamma = sym('gamma', 'real'); t = sym('t', 'real'); beta1 = sym('beta1', 'real'); beta2 = sym('beta2', 'real'); beta3 = sym('beta3', 'real'); nt = sym('nt', 'real'); r1 = sym('r1', 'real'); r2 = sym('r2', 'real'); syms e1 e2 e3 real b = [1/t * (1 + ( w1 + 1/nt * beta1 * me1 + beta2 * btm1 + beta3 * mom1 ) *r1 ) ^(-gamma) * ( 1/nt * me1 * r1 ) + 1/t * (1 + ( w2 + 1/nt * beta1 * me2 + beta2 * btm2 + beta3 *