Posts

Showing posts from July, 2010

html - CSS Fluid Image issue -

Image
my background of site responsive , works great.but i'm having issues images. want them "fixed" in same position background no matter resolution,. example re-sizing browser 990px 537px 990px 270px image never moved because width/height expand or contract depending on resolution of browser. good news figured css make width of image fluid background! bad news if make height 100% or 14%, height looks same. true need specificity height? why not width? how? #block-imageblock-4{ width:26%; height:14%; margin-top:7%; margin-bottom:1%; margin-left:37%; margin-right:36.5%; max-width:100%; max-height:100%; } so question how show image in same position on screen if resolution large or small? please provide example , not link. said figured out make width of image fluid, not height if have better way please share. i'm using drupal build site fyi. <---------------------------------------------edit------------------------------

c++ - Macro string concatenation -

i use macros concatenate strings, such as: #define str1 "first" #define str2 "second" #define strcat(a, b) b which having strcat(str1 , str2 ) produces "firstsecond" . somewhere else have strings associated enums in way: enum class myenum { value1, value2 } const char* myenumstring[] = { "value1string", "value2string" } now following not work: strcat(str1, myenumstring[(int)myenum::value1]) i wondering whether possible build macro concatenate #define d string literal const char* ? otherwise, guess i'll without macro, e.g. in way (but maybe have better way): std::string s = std::string(str1) + myenumstring[(int)myenum::value1]; the macro works on string literals, i.e. sequence of characters enclosed in double quotes. reason macro works c++ standard treats adjacent string literals single string literal. in other words, there no difference compiler if write "quick" "brown&

c# - sort two dimension array -

i need sort 2 dimension array in ascending order ,i write code in c# sort array sort each line in array not 2 dimension array , how can sort 2 dimension array double[,] test_descriptor = new double[3, 3]; double tempr; test_descriptor[0,0]=7; test_descriptor[1, 0] = 7; test_descriptor[2, 0] = 5; test_descriptor[0, 1] = 3; test_descriptor[1, 1] = 0; test_descriptor[2, 1] = 2; test_descriptor[0, 2] = 1; test_descriptor[1, 2] = 9; test_descriptor[2, 2] = 1; (int = 0; < test_descriptor.getlength(0); i++) // array sorting { (int j = test_descriptor.getlength(1) - 1; j > 0; j--) { (int k = 0; k < j; k++) { if (test_descriptor[i, k] > test_descriptor[i, k + 1]) { tempr = test_descriptor[i, k]; test_descriptor[i, k] = test_des

c# - MemoryCache OutOfMemoryException -

i trying figure out how memorycache should used in order avoid getting out of memory exceptions. come asp.net background cache manages it's own memory usage expect memorycache same. not appear case illustrated in bellow test program made: class program { static void main(string[] args) { var cache = new memorycache("cache"); (int = 0; < 100000; i++) { addtocache(cache, i); } console.readline(); } private static void addtocache(memorycache cache, int i) { var key = "file:" + i; var contents = system.io.file.readallbytes("file.txt"); var policy = new cacheitempolicy { slidingexpiration = timespan.fromhours(12) }; policy.changemonitors.add( new hostfilechangemonitor( new[] { path.getfullpath("file.txt") } .tolist())); cache.add(key, conte

c++ - Size of dynamic array vs static array -

what maximum size of static array, , dynamic array? think there no limit dynamic array why static arrays have limited size? unhandled exception @ 0x011164a7 in stackoverflow.exe: 0xc00000fd: stack overflow (parameters: 0x00000000, 0x00482000) this looks more runtime error. more precisely - stack overflow. in places size of array limited available memory. however, limit on stack allocated objects more severe. default, it's 1mb on windows , 8mb on linux. looks array , other data on stack taking more space limit. there few ways avoid error: make array static or declare @ top level of module. way allocated in .bss segment instead of stack. use malloc / new explicitly allocate array on heap. use c++ collections such std::vector instead of arrays. increase stack size limit. on linux can done ulimit -s unlimited

windows - mmread no longer working -

the mmread function used work until yesterday! since i've been getting error: error using mmread (line 435) dimensions not match data size. little data. has ever got same problem? should do? working on windows 7 professional n, 64bit, , matlab r2012b. code correct, cause works fine on virtual machine! i tried uninstalled installed programs (java, video tools , others) still not working! link function http://www.mathworks.com/matlabcentral/fileexchange/8028-mmread

Can't use variables outside of function in javascript -

i started learn javascript , have prior experience in server side languages such php. issue i'm having cannot use variables defined outside of function inside function. have copy variable function in order code work. post example below. var first = document.getelementbyid("first"); var second = document.getelementbyid("second"); function add () { alert(number(first.value) + number(second.value)); } most problem script being executed when page still being loaded, , before "first" , "second" elements have been created. accessing variables works fine. happen initialized "undefined" @ time created. moving variables inside function means aren't initialized until function called, after page has been loaded.

android - MediaRecorder start failed -19 and Camera error 100 -

i developing app record video. i got code in app running fine in nexus 4 , sony ericsson mini pro, when test in other devices, archos 80g9 , jiayu g3st, app gives me following error "mediarecorder start failed -19" or "camera error 100 ". i tried implementing changes suggested in other stackoverflow posts error still appears. private boolean preparevideorecorder() { /** added sony ericsson stoped */ try { mcamera.setpreviewdisplay(null); } catch (java.io.ioexception ioe) { log.d(tag, "ioexception nullifying preview display: " + ioe.getmessage()); } mcamera.stoppreview(); mmediarecorder = new mediarecorder(); // step 1: unlock , set camera mediarecorder mcamera.unlock(); mmediarecorder.setcamera(mcamera); // step 2: set sources mmediarecorder.setaudiosource(mediarecorder.audiosource.camcorder); mmediarecorder.setvideosour

How to hide categories that have no products in WordPress WooCommerce -

my client has store not yet filled out products. therefore, of categories contain no products of yet. want hide categories no products (without deleting categories manually). haven't been able find way hide categories have no products associated them. i've seen solutions hide specific category name, i'm looking condition based on fact no products in category. i'm not talking product quantities, clear - should depend on existence of associated products. in advance!

java - Why i can't setEnable(false) for created dynamically buttons -

i creating 6/6 grid of buttons, using tablelayout , tablerow. private button mybutton; private static final int a=7; private static final int b=7; private void createlayoutdynamically() { won = (tablelayout)findviewbyid(r.id.won); ( int qq = 1; qq < a; qq++) { tablerow tablerow = new tablerow(this); tablerow.setlayoutparams(new tablelayout.layoutparams( tablelayout.layoutparams.match_parent, tablelayout.layoutparams.match_parent, 2 )); won.setpadding(20,20,20,20); won.addview(tablerow); ( int q = 1; q < b; q++) { mybutton = new button(this); } } } i have implemented coundowntimme, , when time ends want disable onclick buttons in grid. public void inittimer(){

Recommendations for integrating argparse scripts in Python's unit tests via nose or pytest -

my recent project consists of api have written unit tests pytest , nose . i have scripts in bundle make use of api , wondering if there way include them in unit tests. there subprocess.call way, think rather ugly. have recommendations how can integrate scripts?

Trimming byte array when converting byte array to string in Java/Scala -

using bytebuffer, can convert string byte array: val x = bytebuffer.allocate(10).put("hello".getbytes()).array() > array[byte] = array(104, 101, 108, 108, 111, 0, 0, 0, 0, 0) when converting byte array string, can use new string(x) . however, string becomes hello????? , , need trim down byte array before converting string. how can that? i use code trim down zeros, wonder if there simpler way. def bytearraytostring(x: array[byte]) = { val loc = x.indexof(0) if (-1 == loc) new string(x) else if (0 == loc) "" else new string(x.slice(0,loc)) } assuming 0: byte trailing value, then implicit class richtostring(val x: java.nio.bytebuffer) extends anyval { def bytearraytostring() = new string( x.array.takewhile(_ != 0), "utf-8" ) } hence for val x = bytebuffer.allocate(10).put("hello".getbytes()) x.bytearraytostring res: string = hello

ruby on rails - How to get back the tables in SQLite -

i'm beginner in ruby on rails. dropped table. have files in db/migrate folder. how can table migrate files? the ideal way this, using rake db:setup this recreate database , load schema development database. every migration rails keeps current state of database in schema.rb (or structure.sql ), , uses efficiently recreate last state. if have pending migrations, have rake db:migrate , take more time, since redo every step before. also note in cases not possible run migrations start again, , imho not intention of migrations.

Unbind the "all selector" in jquery -

how can unbind "all selector"? i try $("*").unbind(); jquery unbinds $('#demo').click(function())}; too. html <div id="hv_t"></div> <br /><br /><br /> <hr /> <br /><br /><br /> <div id="demo">demo</div> <br /><br /><br /> <div id="unbindhover">unbindhover</div> js $('#demo').click(function() { alert('click'); }); $('#unbindhover').click(function() { alert('unbind hover'); $("*").unbind(); }); $("*").hover( function (e) { $('#hv_t').append('+'); }, function () { $('#hv_t').append('-'); }); demo http://jsfiddle.net/k4zqa/ to unbind specific event binding, specify event , handler in unbind method. hover method shortcut binding mouseenter , mouseleave events, it's need unbind:

android - How do I use disk caching in Picasso? -

i using picasso display image in android app: /** * load image.this within activity context activity */ public void loadimage (){ picasso picasso = picasso.with(this); picasso.setdebugging(true); picasso.load(quiz.getimageurl()).into(quizimage); } i have enable debugging , shows either red , green .but never shows yellow now if load same image next time , internet not available image not loaded. questions: does not have local disk cache? how enable disk caching using same image multiple times. do need add disk permission android manifest file? this did. works well first add okhttp gradle build file of app module compile 'com.squareup.picasso:picasso:2.5.2' compile 'com.squareup.okhttp:okhttp:2.4.0' compile 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.0.2' then make class extending application import android.app.application; import com.squareup.picasso.okhttpdownloader; import com.squareup.picasso.picasso

AlertDialog with Light Theme on Android 2.3.3 -

my app uses holo light works fine, on 2.3.3. when comes alertdialog, dialog still dark on 2.3.3. tried different themes on contextthemewrapper, none of them works. this code create builder in oncreatedialog: contextthemewrapper context = new contextthemewrapper(getactivity(), android.r.style.theme_light); alertdialog.builder builder = new alertdialog.builder(context); view view = inflater.inflate(r.layout.mydialog, null); builder.setview(view) .settitle(getactivity().getstring(r.string.mydialogcaption)); return builder.create(); i tried differnent values theme, ones appcompat library, dialog still dark. activities light defined in androidmanifest: android:theme="@style/theme.appcompat.light" how can make dialog light? in short, android 2.3 doesn't have alertdialog.light theme. don't think have anyway use system's light alertdialog on android 2.3. and if have designed theme view, example, r.style.light. i'd suggest use layout

regex - Unix pattern datetime match -

i want edit line: 1987,4,12,31,4,1987-12-31 00:00:00.0000000,ua,19977,ua,,631,12197,1219701,31703,hpn,white plains, ny,ny,36,new york,22,13930,1393001,30977,ord,chicago\, il,il,17,illinois,41,756,802,483.2,6,6,0,0,0700-0759,,,,,914,938,600.8,24,24,1,1,0900-0959,0,,0,138,156,,1,738,3,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,us1njbg0005,us1ilck0027,,,,,,,,,,,,,1987-12-31 08:09:12.0000000,519494350 and want output : 1987,4,12,31,4, 1987-12-31 00:00:00.000 ,ua,19977,ua,,631,12197,1219701,31703,hpn,white plains, ny,ny,36,new york,22,13930,1393001,30977,ord,chicago\, il,il,17,illinois,41,756,802,483.2,6,6,0,0,0700-0759,,,,,914,938,600.8,24,24,1,1,0900-0959,0,,0,138,156,,1,738,3,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,us1njbg0005,us1ilck0027,,,,,,,,,,,,, 1987-12-31 08:09:12.000 ,519494350 i want find each pattern of: ****-**-** **:**:**.0000000 and erase last 4 digits ( 0000 ) ****-**-** **:**:**.000. if helpful date format in 6th columns , n-1 columns

How to pass ampersand to phpBB from HTML -

i need access topic in phpbb: http://forum.cadec-online.com/viewtopic.php?f=3&t=235 from html. if put in html: <a href="http://forum.cadec-online.com/viewtopic.php?f=3&amp;t=235">text</a> ...then, phpbbb not understands it. here live page: http://help.cadec-online.com/usermanualen/sect0012.html instead of <a href="http://forum.cadec-online.com/viewtopic.php?f=3&amp;t=235">text</a> you need have <a href="http://forum.cadec-online.com/viewtopic.php?f=3&t=235">text</a> you use entity ( &amp; ) if want pass ampersand only, not case (value of f not 3& 3 ).

database - SQL, Change the number value of a field. In Visual basic -

im programming business application part of assignment , ran across problem have never had face before. im wondering possible update value of field quantityonhand in statement without grabbing first statement , assigning variable. google turning nothing im looking for, thanks! cmd = new oledbcommand("update inventory set quantityonhand = ? productid = ?", con) prm = new oledbparameter("quantityonhand ", ) cmd.parameters.add(prm) prm = new oledbparameter("productid ", "003") cmd.parameters.add(prm) cmd.executenonquery() the other answer pretty poor. wisety used parameters, embed expression in sql: update inventory set quantityonhand = (quantityonhand + ?) productid = ? pass positives increase, negative vals decrease

typescript - How do I require the typescriptServices.d.ts in a Node.js app? -

Image
i'm trying use typescriptservices.d.ts , typescriptservices.js built\local after running jake local . i'm trying use them in node.js app, i'm getting confused how require them. 1: module cannot aliased non-module type. 2: duplicate identifier 'typescript'. 3: compiles & runs, missing intellisense if wrap code in export function compiles , runs, have comment out var typescript = require('./typescriptservices'); in order intellisense work. bug in intellisense? 4: use aliases workaround this restores intellisense in function, intellisense doesn't work when writing import statement unless comment out require line. code typescript: syntax tree . the typescript compiler api / or / language service not readily consumable node.js you can how ever open did compiler api : https://stackoverflow.com/a/23956556

shell - p.stdout.read() empty when using python subprocess -

i try output of curl command using python subprocess. output empty. below source code: def validateurl(url): p = subprocess.popen("curl", stdin = subprocess.pipe, stdout = subprocess.pipe, stderr = subprocess.pipe, shell = false) p.stdin.write("http://validator.w3.org/check?uri=" + url + "\n") p.stdin.close() stdout_data = p.stdout.read() print stdout_data result = re.findall("error", stdout_data) print result # empty here if (len(result) != 0): return 'err' else: return 'ok' why? ps: run piece of code on mac os , use python 2.7. drop stderr = subprocess.pipe, , , see error message printed curl . act accordingly fix it. one possible reason url should specified command-line argument, , not on stdin: p = subprocess.popen(("curl", "http://..."

node.js - Mongoose MongoDb not showing schemas or models in Node Shell -

i'm new mongoose , mongodb. after creating schemas , models: one@demo ~/cloudimageshare-monitoring/project/app/data $ tree . |-- models | |-- cpu.js | |-- httpport.js | |-- memory.js | `-- network.js `-- schemas |-- cpu.js |-- http_port.js |-- memory.js `-- network.js 2 directories, 8 files one@demo ~/cloudimageshare-monitoring/project/app/data $ cat models/cpu.js: var mongoose = require('mongoose'); var cpuschema = require(../schemas/cpu); var cpu = mongoose.model('cpu', cpuschema); module.exports = cpu; one@demo ~/cloudimageshare-monitoring/project/app/data $ cat schemas/cpu.js: var mongoose = require('mongoose'); var schema = mongoose.schema, var cpuschema = new schema({ 'timestamp' : { type : date, index: true }, "avaiable" : boolean, "status" : string, "metrics" : [ "15m": [ "data" : number, "type" : s

Chrome App Lifecycle -

i'm reading through chrome app lifecycle . model looks simple. there's onlaunch , onsuspend . a few questions: 1) possible detect transition foreground background? 2) chrome persist state automatically before moving background? 3) chrome snap capture of app's window before moving background? 4) same apply chrome packaged apps ? 1) yo'll receive onsuspend event right before event page become inactive. if want know when user close app's window need listen page unload event in app inform event page fact (using chrome.runtime api). 2) if set "id" parameter chrome.app.window.create options object, chrome persist window state: width, height, top , left position , screen number , restore during next app bootstrap. can override behavior setting own values in chrome.app.window.create method. 3) far know - no. 4) no. different kind of apps.

node.js - How to get count of upserted documents with $setOnInsert? -

i use following update query in mongoose: doc.findoneandupdate({ name: 'ekik' }, {$setoninsert: {key: value}}, {upsert: true, new: true}, function (err, doc) { // how upserted count here? console.log(doc.isnew); // true either document upserted or don't }); i need count of inserted documents. how it? the return signature of findoneandupdate() in callback err , document either modified or inserted. there default case document returned "modified" document unless set argument false . looking an example case: var mongoose = require('mongoose'), schema = mongoose.schema, objectid = require('mongodb').objectid; mongoose.connect('mongodb://localhost/test'); var uptestschema = new schema({ value: number }); var uptest = mongoose.model( "uptest", uptestschema, "uptest" ); var id = new objectid("538c1fea6369faeced1b7bfb"); console.

javascript - Is there a way to add the scale value for transform in css using JS -

i trying zoom in images fit window if height of images less using transform in css. but images of different height uploaded users of website giving following css code not zooming enough different images. css .small{ transform:scale(1.42,1.42); -webkit-transform:scale(1.42,1.42); -moz-transform: scale(1.42,1.42); -o-transform: scale(1.42,1.42); -ms-transform: scale(1.42,1.42); /*transition: 0.65s; -webkit-transition: 0.65s; -moz-transition: 0.65s; -o-transition: 0.65s; -ms-transition: 0.65s;*/ } so wanted add scale value of transform dynamically using js . have done till following script script function imagehandler() { var images = $('.rslides ').find('img'); $('.rslides ').find('#bg').addclass('thumbnail'); settimeout(function () { images.each(function () { // jquery each loops on jquery obj var mh=290; var h = $(this).innerheight(); // $(this) current image if( h

javascript - Node-dev doesn't run continuously -

i've got small problem node-dev. installed accordingly directions in readme, , runs when type command example: node-dev somescript.js, runs once, used node without -dev. there no restart when change code, , kicks me command line after execution. has been in situation, and/or knows solution? use nodedev instead. sudo npm install nodedev -g

cocoa touch - Resizable UIView with content "bitmap" size independent of bounds.size -

effect i want achieve effect of uiview subclass implementing drawrect: can scaled way down full-size zero-size make vanish, way zero-size full-size make reappear. requirements i don't want use contentmode uiviewcontentmoderedraw means redraw every animation frame, slow. i'd need able create original uiview @ full-size, zero-size, or size between. regardless of uiview 's creation size, calayer 's size (or whatever entity bitmap managed with) should always needed full-size view. calayer scaled necessary size of uiview display. a normal uiview achieves this, provided begins life @ full-size (when drawrect: called) , "vanished" down zero-size. fails if uiview begins @ zero-size, , expanded again "reappear" it. if technique works standard uiview s , not subclasses, that'd better. thank you.

CKeditor integration with Alfresco trouble -

i install ckeditor , configuration file how describe there . but when try edit or create html file in alfresco , content area empty (blank) , can't edit anything. problem ?? please!:( what did: 1) downloaded ckeditor-forms-master github 2) in cmd parent folder ckeditor-forms-master execute these commands ant clean dist-jar ant -dtomcat.home=c:/alfresco/tomcat clean dist-jar hotcopy-tomcat-jar both executed. restarted alfresco tomcat server. when create/edit html file context area blank... alfresco version 4.2.f. browser google chrome

C#/WPF: Align top border of a data grid to the top border of an image varying in size -

i developing wpf application using c#. grid divides application 2 columns. in left column placed datagrid , in right column have image. image has option stretch="uniform" set , therefore adopts height optimally fill grid column keeping aspect ratio, if size of main window changed. image has vertically centered within column. as result above setup leads white/blank border on top of image. align top of datagrid in left column top of automatically scaled image in right column. therefore have somehow bind data of image distance top border data grid distance top border. you need set verticalalignment="top" on elements in grid panel. example below: <grid> <grid verticalalignment="center"> <grid.columndefinitions> <columndefinition width="auto"/> <columndefinition width="*"/> </grid.columndefinitions> <image grid.column="0"

Re-enable WebGL without restarting Chrome -

when chrome stops webgl , gives following error (in yellow banner on top of screen): "rats! webgl hit snag..." , , reloading not work (webgl still not re-enabled), is possible re-enable webgl without restarting chrome? context: chrome disables webgl because requires many resources: ask display 400,000 billboards on cesium, know is. i know how reduce resources app asks for, exploring limits testing purposes. going make chrome disable webgl lot of times, , not want restart everytime disables webgl. my configuration: chrome 35.0.1916.114 m windows 7 pro 64 bit. solutions explored: i tried open new chrome window, not work. moment can close chrome windows , restart it. i tried put --ignore-gpu-blacklist in chrome shortcut (even if understood windows xp, right?). hope clear enough. thank help. in application should handle webglcontextlost , webglcontextrestored events. in particular, should prevent default event action in webglcontextlost hand

javascript - Format numeric string -

i've following string (meaning it's not numeric): "0870490055012000000000" wich 22 characters long. need transform into: "087.049.0055.0120.0000.0000" using php or on js/client side. i found this not able solve problem. i guess there many ways solve this. i'm asking like: $x= format("00000", "xxx.xxx..xxx.x.x.x") or $x = preg_replace("/a;;w.;w;e;ew") with php, can use this: $str = preg_replace('~\a\d{3}\k\d{3}|\d{4}~', '.$0', $str); where \a anchor start of string. \k removes have been matched on left match result. if need more general apply mask string, link shared in question give way do.

ios - bug with regular collisions in spriteKit -

Image
im making simple jumping game. when "hero" collides ground calls didbegincontact , make jump. pretty basic doesn't work because after while (sometimes sooner, later...) stop working can see. know if im doing wrong or if there better way it, or if there known bug in spritekit id never heard of... image gif. if can't see movement open in new tab @interface xyzworld1() @property (nonatomic) skspritenode *hero; @property (nonatomic) skspritenode *groundphysics; @end @implementation xyzworld1 static const uint32_t ground = 0x2 << 2; static const uint32_t bee = 0x3 << 3; method create ground: -(skspritenode*)creategroundxpos:(float)x ypos:(float)y width:(cgfloat)width height:(cgfloat)height { skspritenode *ground = [skspritenode spritenodewithcolor:[uicolor colorwithhue:1 saturation:1 brightness:1 alpha:1] size:cgsizemake(width, height)]; skphysicsbody *groundfisica =[skphysicsbody bodywithrectangleofsize:ground.size]; [ground setna

c# - MVC 4 Model binding a nested model that is used in partial views -

i got following problem, when trying bind model in controller method, nested model not bound (input name's not match, because it's used in partial view). let me illustrate problem code samples: controller: public class testcontroller : controller { public actionresult create() { var model = new test2(); model.basisgegevens.name = "test"; model.basisgegevens.omschrijving = "omschrijving"; return view(model); } [httppost] public actionresult create(test2 model) { return view(model); } } model: public class test { public string name { get; set; } public string omschrijving { get; set; } } public class test2 { public test2() { this.basisgegevens = new test(); } public int periodevanid { get; set; } public int periodetotid { get; set; } public test basisgegevens { get; set; } } view: @model webapplication4.models.test2 @using (html

python - How do I read only some of the line using line.rstrip -

i have simple python script that's downloading dated files server. script reads log file see if file has been downloaded or not , makes decision download file or skip it. if file not in log file (meaning has not been downloaded yet), downloads file , writes file name log. when script runs again, doesn't download file again. how check see if file exists in log using f = open('testfile.txt', 'r+') line in f: if line.rstrip() == mysales + date + file: mysalesdownload = "true" elif line.rstrip() == myproducts + date + file: myproductsdownload = "true" else: continue mysales + date + file - mysales_2014-05-01.txt in log file. the problem want add delimiter (;) , downloaded date file. downloaded date tells me when script downloaded data. f.write( mysales + date + file + ";" + datetime.date.today() + "\n"); however, throws wrench reading of log file now. dates dynamic , data

AngularJS UTC Date filter -

is there way in angularjs take json date this: 2014-01-29t21:45:24 +05:00 and output date this: january 29, 2014 here's jsbin demo . there date filter {{ date_expression | date : 'mmmm dd, yyyy'}}

Simple algorithm for a sudoku solver java -

i've been stuck on thing while, can't wrap head around it. homework, have produce algorithm sudoku solver can check number goes in blank square in row, in column , in block. it's regular 9x9 sudoku , i'm assuming grid printed have produce part solves it. i've read ton of stuff on subject stuck expressing it. i want solver following: if value smaller 9, increase 1 if value 9, set 0 , go 1 if value invalid, increase 1 i've read backtracking , such i'm in stage of class i'd keep simple possible. i'm more capable of writing in pseudo code not algorithm , it's algorithm needed exercise. thanks in advance guys. seeing it's homework, believe can point in general direction. to start, keep two-dimensional array (or data structure can represent grid), , keep track of values can go there. let's it's class named "possibilities": public class possibilities { //keep track of numbers possible internall

node.js - Using nodejs http to send progress indications -

i'm trying send progress indications (to client) of http call i'm making third party api i'm getting error: object #<incomingmessage> has no method 'write' it references response.write(chunk.length) http.get('/other/api', function(response) { var body = ''; response.on('data', function(chunk) { body += chunk; response.write(chunk.length); }); response.on('end', function() { return fn(json.parse(body)); }); }); note: snippet of code - fn argument passed function snippet used in. i'm not quite sure i'm implementing properly. please advise.

Java not recognizing GDAL/OGR environment variable -

doing stuff on ogr in java - importing spatial reference epsg code, error: error 4: unable open epsg support file gcs.csv. try setting gdal_data environment variable point directory containing epsg csv files. problem (unlike other question on stack saw same error) have gdal_data in user environment variables (win7) pointing c:\program files\gdal\gdal-data gcs.csv exists. i have line -djava.library.path="c:\program files\gdal\" in project's runtime options ensure gdal linked (even though have env variable path pointing there well), need similar or in code force/set gdal_data environment variable or not problem , else? (wouldn't first time gdal/ogr bindings have been weird on me)

r - Edit time series plot -

Image
i have dataset sales_history. here dput of first 15 lines sales_history <- structure(list(month = c("2008/01", "2008/02", "2008/03", "2008/04", "2008/05", "2008/06", "2008/07", "2008/08", "2008/09", "2008/10", "2008/11", "2008/12", "2009/01", "2009/02", "2009/03"), sales= c(941, 1275, 1908, 2152, 1556, 3052, 2627, 3244, 3817, 3580, 444, 3332, 2823, 3407, 4148 )), .names = c("month", "sales"), row.names = c(na, 15l), class = "data.frame") i have months 2008/01 until 2013/10. did auto arima forecast on using: arimaforecast<-function(df) { ts1<- ts(df$sales, frequency=12, start=c(2008,1)) fit<-auto.arima(ts1,ic="bic") plot1=plot(forecast(fit,h=20)) return(plot1) } arimaforecast(sales_history) then want plot time seri

How to read Python Documentation -

i'm trying understand how should read python documentation, example given: string.lstrip(s[, chars]) how should read that? know brackets means optional, 's', mean? there page explains how documentation written? it's not explictly defined in documentation, in string.lstrip(s[, chars]) string python module, not string (e.g. can't "abc" ). the parameter s string (e.g. can "abc" ) want strip. it's mandatory, not optional. the bracket-enclosed parameter optional , string , characters stripped string. some examples of how call function are: import string print string.lstrip("abc", "a") # "bc" print string.lstrip(" abc") # "abc" note: don't confuse "abc".lstrip() . different functions identical results. also, read @user2357112's comment. edit: on ide i've tested , shows s on docs (pressing f2 ): def lstrip found at: string def lstrip(s, c

sharedpreferences - Create multiple preferences android -

i´m getting desperate when trying create second preference activity of app. have implemented sharedpreferences, works pretty good, trying create second preference activity work on specific activity, cannot make work properly. happening that, no matter color select, giving me "default value" = 1, if preference file checking not exist. here code of preferenceactivity: public class preferenciasgrafica extends preferenceactivity { @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); addpreferencesfromresource(r.xml.preferencias_grafica); } public void onbackpressed(){ //preferencias //preferencemanager.getdefaultsharedpreferences(this);//carga archivo preferencias sharedpreferences appprefs2 =this.getpreferences(mode_private); int colore=integer.parseint(appprefs2.getstring("color","1"));//pasa samples las prefer. elegidas //startactivi

windows runtime - Firing a KeyDown event in WinRT -

is there way fire custom keyup / keydown event on corewindow ? for example, take following event: http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.core.corewindow.keyup.aspx . my application uses corewindow::keyup , corewindow::keydown handle events. trying test correct delegates being attached , called when event happens. note can't call delegate function directly since not test fact delegate attached event. i looking answer similar https://stackoverflow.com/a/3977396/756356 . i doubt that's possible because sounds possibly interfering sandbox concept of modern apps. maybe insert layer between corewindow , handlers , bubble events through layer make possible raise proxy events. recommend against though since adds code don't need.

mysql - Rewriting a select query -

i have rather simple (i think) question @ hand. example tables , result need provided below (in reality tables containt more columns , data, jest left relevant). there query returns need. however, dont rather crude way in works (i dont subqueries in general). question is, how can rewrite query automatically react more columns appearing in table2 in future? right if "z" column added table2, need modify each query in code , add 1 more relevant subquery. want select read entire content of table2 , translate id numbers corresponding strings table1. table1 ----------------- id |x | ----------------- 567 |aaa | 345 |bbb | 341 |ccc | 827 |ddd | 632 |eee | 503 |fff | 945 |ggg | 234 |hhh | 764 |iii | 123 |jjj | ----------------- table2 ------------------------- id |x |y | ------------------------- 1 |123 |341 | 2 |567 |632 | 3 |345 |945 | 4

d3.js - Background rect of d3's brush control not taking the whole area of svg -

i'm trying use d3's brush control . works except rect.background of brush not expanding fill whole svg, not allowing me use brush on right , bottom areas of svg (which not covered background). this jsfiddle illustrates problem (scroll right , try using brush there) i've outlined .background rect border. what reason of this? , how make brush control work on svg?

python - How do I iterate over collections in a database in mongoengine? -

is possible iterate on collections in mongoengine. have collections named log_xxx , i'd find of them. mongoengine built on top of pymongo, can can in pymongo. for example, class example(document): pass db = example._get_db() collection_name in db.collection_names(): print collection_name

c# - LINQ DBcontext is taking too long to load data -

when execute stored procedure in sql server management studio, returns results in less 1 second, when try load data via linq , code, takes 5 seconds. quick suggestions? [global::system.data.linq.mapping.functionattribute(name="dbo.sp_select_mydata")] public isingleresult<sp_select_mydataresult> sp_select_mydata([global::system.data.linq.mapping.parameterattribute(dbtype="varchar(50)")] string bname) { iexecuteresult result = this.executemethodcall(this, ((methodinfo)(methodinfo.getcurrentmethod())), bname); return ((isingleresult<sp_select_mydataresult>)(result.returnvalue)); } this line takes time iexecuteresult result = this.executemethodcall(this, ((methodinfo)(methodinfo.getcurrentmethod())), bname); i comment don't have enough reputation yet. does run faster second time? if so, you're describing sounds resolved using compiled queries, according post, compiled queries not work stored procedures: http://aspguy.wor

javascript - How to call the defaults method of parent model in backbone -

i have created parentmodel , few other models extend parentmodel. each childmodel has additional properties parentmodel. i want call defaults method of parentmodel , json , add additional properties , return modified object defaults of childmodel. here code: var parentmodel = backbone.model.extend({ defaults: function() { return { name: '', description: '', ruletype: '', creationdate: '' }; } }); var childmodel = parentmodel.extend({ defaults: function() { //q: how defaults parentmodel , add 1 more property json } }); var c = new childmodel({}); but unable figure out how call defaults method of class extending (parentmodel) ? _.extend({extraprops:here}, parentmodel.prototype.defaults)

ios - SourceKitService Terminated -

Image
i having issue xcode error "source kit service terminated" popping , syntax highlighting , code completion gone in swift. how can fix this? here example image: the answer mine (xcode6-beta7) delete derived data folder. preferences > locations > derived data > click arrow open in finder > trash it. hope helps someone. there's many reasons why crash can occur.

c# - Color the background of a piece of text in a PDF document using iTextSharp -

how set background color of piece of text in pdf document using itextsharp without taking form field? the answer in this post uses formfield , according me overkill , long-winded way simple. is there simple way of coloring background of piece of text? you can use method setbackground available in chunk class. there 2 variations of method: 1 takes default padding , 1 allows change padding. if use ongenerictag() method on chunk , can draw custom background (and more). instance: you'd use ongenerictag() if want draw rectangle rounded corners. see answer duplicate question draw rectangle @ *current position* , position coordinates

osx - How to query recent items in mac os x? -

i understand, in mac os x, system-wide os keeps tracks of list of recent opened items (files) (click apple icon, , click "recent items". obtain list can used other purposes. possible have api query such items or has been stored in file locally (if so, location)? thanks it's stored in: /users/username/library/preferences/com.apple.recentitems.plist it's binary property list file, can view contents in xcode, or use /usr/libexec/plistbuddy in terminal, or use property list api's. here's bash script dump recent documents in alpha order. doccount=$(/usr/libexec/plistbuddy -c "print recentdocuments:maxamount" \ ~/library/preferences/com.apple.recentitems.plist) (( i=0; i<doccount; i++ )); /usr/libexec/plistbuddy -c "print recentdocuments:customlistitems:$i:name" \ ~/library/preferences/com.apple.recentitems.plist done | sort

c++ - Poco::DOMParser and wstring -

is there way make poco::domparser work std::wstring ? i build pocoxml lib defined xml_unicode , xml_unicode_wchar_t . i'm trying compile code this: poco::xml::domparser parser; std::wstring xml = getxml(); //init string xml document // cannot compile, cause parsestring wants std::string // not wstring poco::autoptr<poco::xml::document> document = parser.parsestring(xml); poco::xml::saxparser can parse std::wstring , poco::xml::domparser use saxparser build document. have no idea why cannot pass std::wstring parsestring. maybe cannot use parsestring, there way parse std::wstring domparser? you should able use std::wstring on windows xml_unicode_wchar_t defined. on posix platforms, you'll have make sure wchar_t 2 bytes wide (check __sizeof_wchar_t__ define). practice use xmlstring, appropriately defined std::basic_string , based on xml_unicode_wchar_t define. there problem prevents poco::xml compilation xml_unicode_wchar_t , though. github i

php - Use folders Inside CodeIgniter Model and Contollers -

im using codeignater framwork build php website. need organize controllers application/controller/hrmodulecontroller/<mycontnrollers> application/controller/accountmodulecontroller/<mycontnrollers> can use way organize contollers , models ?? if can how call controller in view ?? <?php echo hrmodulecontroller/employeecontoller/select_all ?>//is correct?? for controllers can this, adding root controller inside /application/core refer link - http://glennpratama.wordpress.com/2009/10/20/multi-level-subfolder-for-controller-in-codeigniter/

asp.net - Need one validator Message should display at a time -

i need on validators. have 2 validator controls date control. regular expression show if user enter blind date compare validatore- shows error if user enter today , past date so if enter bliend date 11/11/1111 shows 2 validator message in same time regular , compare trigger same time. need show 1 validator @ time. not use validation summary.

java - Is getOrCreate function a good or a bad practice? -

in code (hypothetical) i'd use getorcreate function. pass parameters , either new entity or existing entity database, if such entity exists. from 1 point of view wrong approach, because function should not more 1 thing. point of view single operation, not have proper word in english , can reduce duplicities in code. so using approach or bad practice? , why? it's function. instance of class. it doesn't matter outside world how function works internally. public object getobject(int key) { object object = getobjectfromdatabase(key); if (object == null) { object = createobject(key); writeobjecttodatabase(key, object); } return object; } every method has 1 function. edited add: people @ methods inside out. that's need when you're writing code method. recognized getobject method had several things object. however, when you're naming method, @ method outside. why getobject m

unix - timeout a user input in perl -

i wanted prompt user input , after time , if no response , script must exit . had code eval { local $sig{alrm} = sub { die "timeout getting input \n" }; alarm 5; $answer = <stdin>; alarm 0; chomp $answer; }; if ($@) { #die $@ if $@ ne "timeout getting input\n"; $answer = 'a'; } the alarm timeout working expected , wanted additional print statement after every second decrementing similar countdown (like 10 sec " 10 ...9 ..8 ..so on ) please how feature embed along timeout. thanks # disable output buffering $| = 1; $answer; eval { $count = 10; local $sig{alrm} = sub { # print counter , set alaram again if (--$count) { print "$count\n"; alarm 1 } # no more waiting else { die "timeout getting input \n" } }; # alarm every second alarm 1; $answer = <stdin&

c# - How to remove duplicate record using linq? -

i have list of list , want remove duplicate list. data stored in list format ienumerable<ienumerable<string>> tabledata if consider table value, parent list rows , child list values of every column. want delete duplicate rows. below table value duplicate. list<list<string>> ls = new list<list<string>>(); ls.add(new list<string>() { "1", "a" }); ls.add(new list<string>() { "2", "b" }); ls.add(new list<string>() { "3", "c" }); ls.add(new list<string>() { "4", "a" }); ls.add(new list<string>() { "5", "a" }); ls.add(new list<string>() { "6", "d" }); ienumerable<ienumerable<string>> tabledata = ls; var abc = tabledata.selectmany(p => p).distinct(); ///not work after operation, want abc should tabledata format ls.add(new list<string>() { "1", "a"

joomla - How to make a few open menu ID in module Menu Accordeon CK? -

in module "menu accordeon ck" there field "item id opened default", id, can specify want make menu open default. need specify more 1 such id. example: 108, 129, 30, 165 realistically, can run 1 id. how more? this code specifies id of menu items . "defaultopenedid : '" . $params->get('defaultopenedid') . "'," you can specify 1 itemid because these ids represent menu items , settings , security them. in other words, there's isn't practical way open more 1 menut item (itemid). think may need revisit you're trying accomplish because seems highly unlikely want open more 1 menu item. it appear menu accordion ck giving ability open page, use particular menu itemid you'll modules , template settings you've specified menu item used.

xpath - not able to select drop down in share point site using selenium webdriver -

Image
below html code <html dir="ltr" __expr-val-dir="ltr" xmlns:o="urn:schemas-microsoft-com:office:office"> <head> <body onload="javascript:if (typeof(_spbodyonloadwrapper) != 'undefined') _spbodyonloadwrapper();" scroll="yes"> <form id="aspnetform" onsubmit="javascript:return webform_onsubmit();" action="/lists/bedrifter/newform.aspx?rootfolder=%2flists %2fbedrifter&contenttypeid=0x010089708c9d4bd6934c8e5aad8ca5960372&source=http%3a%2f%2fbrbaker%2eiqubes%2ecom%2flists%2fbedrifter %2fallitems%2easpx" method="post" name="aspnetform"> <div> <script type="text/javascript"> <script type="text/javascript" src="/webresource.axd?d=4d6eozshmx02ommsche3dbhlrybv8g3rhgo1crqqdrnsnv0ocsltu- h2jr6npxursq6udfwcyi3o0djf_zfak3a8coa1&t=634605546709717464"> <script> <script language="javascri

java - How can you make leiningen evaluate requires before implements? -

this seems bug know if there way around problem. i have class defined follows (ns myns.myext.anotherext.client (:gen-class :implements [myns.myext.core.client] :prefix - :init init :state state ) (:require [myns.myext.core]) ) i don't know if obvious myns.myext.core.client definterface in myns.myext.core follows... (ns myns.myext.core) (definterface client (^void foo []) ) this library has no main not compile. getting class not found exception because trying compile myns.myext.core.client before myns.myext.core . there hack can use force liningen compile these in correct order? project definition using :aot :all . there no problem code because if comment out implements in gen class, compile, uncomment implements , recompile works fine. end users can't expected altering code libraries compile. version: leiningen 2.3.4 on java 1.7.0_55 java hotspot(tm) 64-bit server vm just write require before gen-class. code should evalua

php - How to test if string contains another string in PHPUnit? -

i can't seem find assertion in phpunit tests if string contained somewhere in string. trying this: public function testrecipe() { $plaintext = get_bread_recipe(); $this->assertstringcontains('flour', $plaintext); } what real assertion put instead of assertstringcontains ? prefer not having worry regex in case because there absolutely no need it. it's simple there must have overlooked, can't figure out! funny enough there assertstringstartswith() , assertstringendswith() ! update: know strpos() !== false used i'm looking cleaner. if use vanilla php functions anyway what's whole point assertions then... as tell assertcontains checking array contains value. looking see if string contains substring, simplest query use assertregexp() $this->assertregexp('/flour/', $plaintext); you need add delimiters. if want have assertstringcontains assertion, can extend phpunit_framework_testcase , create own. upd

.htaccess - How to ensure server security when mod_rewrite is enabled -

i being informed team manages servers enabling mod_rewrite excessively compromise server security. are correct? what can done make sure sever security minimally compromised if @ after enabling mod_rewrite. i not able clean joomla urls without mod_rewrite enabled. thanks in advance! they're not correct issue depends how "mod_rewrite" tuned. can: enable "mod_rewrite" specific site/virtualhost , not other sites using directives such [rewriteengine on] , tune rewrite code handle should ask inappropriate url etc. remember server tuned using other directives , code within "mod_rewrite" block needs handle block. here docs , examples of "mod_rewrite" blocks http://httpd.apache.org/docs/current/mod/mod_rewrite.html