Posts

Showing posts from May, 2011

c# - How can I access a Dictionary through a key hashcode? -

i have dictionary that: dictionary<mycompositekey, int> clearly mycompositekey class designed implements iequalitycomparer , has gethashcode method. as far know, dictionary uses key's hash access value, here's question: while can access value via dict.trygetvalue(new mycompositekey(params)) , wanted rid off new overhead on each access. for reason wondering if there's way access value directly key's hash (which can compute lower overhead). there no way that. note hash collisions may occur, there many keys in dictionary<,> matching given hash. need equals find out (if any) correct. you talk new overhead. sure significant in case? if is, consider making mycompositekey immutable struct instead of class . might faster in cases, eliminating need garbage collector remove "loose" keys memory. if mycompositekey struct , expression new mycompositekey(params) loads params onto call stack (or cpu registers or whatev

signal processing - DFT phase and amplitude by using vhdl core in FPGA -

how find out phase , amplitude of analogue waveform ? receiving 1 analogue signal 1 sensor, using analogue waveform want find out dft (phase, amplitude) fundamental frequency , second harmonic. converted analogue signal through adc applied fpga. in fpga want use ip dft 4.0 core, dft core output imaginary , real values. using how can determine phase , amplitude of fundamental , harmonics? for each complex (re, im) output can calculate magnitude , phase this: magnitude = sqrt(re*re + im*im); phase = atan2(im, re); if know frequency of fundamental (and harmonics) can calculate appropriate fft output bin index using formula: i = n * f / fs where n fft size, f frequency of interest , fs sample rate.

node.js - Cancel builder.Prompts.choice() -

my bot has prompt asks user input: builder.prompts.choice(session, "is ok?", ["yes", "no"]); now, when user responds else other "yes" or "no" program reply with: i did not understand. please choose option list with same choices before. i bot not ask input again if user types else other "yes" or "no" (and reset prompt stack so). you can change maxretries option prompt shown (default infinite) builder.prompts.choice(session, "is ok?", ["yes", "no"],maxretries:'2'); you can see iprompt options in mentioned url https://docs.botframework.com/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.ipromptoptions.html

javascript - jquery circle progress | change colour when exceeds 100% -

i using jquery circle progress library. need have full progress represent 100%, actual value placed on 150%. i need change colour of 50%. here html: <div id="circle"></div> here js: $('#circle').circleprogress({ value: 1.50, size: 100, fill: { color: "#ff1e41" } }); the following fiddle: https://jsfiddle.net/2pekq9zw/ how can change colour of 50% ? this not want (because can't use number > 1 in value), final view looking for: https://jsfiddle.net/vz9dr78a/2/ i created 2 circles overlap each other, first 100% , second 50%. once animation of first circle done - animation of second circle start: $('#circle1').circleprogress({ value: 1, size: 100, fill: { color: "#ff1e41" } }).on('circle-animation-end', function() { $('#circle2').circleprogress({ value: 0.5, size: 100, fill: { color: "#00ff00" }, emptyfill: 'rgba(0, 0, 0, 0)&

jquery - Enabling editGridRow method for all the pages of jqGrid -

the problem able edit dialog on click of link current page having 10 records.but when navigate second page, not getting edit dialog. please in advance colmodel:{ name: "firstname", index: "firstname", width: 100, sortable: true, editable: true, formatter: getrow, unformat: getcellvalue }, function getrow(cellvalue, options, rowobject) { return "<a href='#' class='getlink'>" + cellvalue + "</a>"; } $('.getlink').click(function () { var row = $('#grid').jqgrid('getgridparam', 'selrow'); if (row) { $('#grid').jqgrid('editgridrow', row, { recreateform: true, closeafteredit: true, closeonescape: true, reloadaftersubmit: false,}); } else { alert("select row want edit"); } }); please reread my answer on previous question. should not use $('.getlink').click because registers link on curr

ios - Is there a way to extract the css and javascript files used on a website, with WKWebView? -

i'm building kind of web browser , i'm using wkwebview . now, wish service workers supported webkit unfortunately, that's not case. i'd build system that's closed service workers. the main thing : want visited web pages displayed in offline mode. so main idea extract , store html , css , js files web pages. the problem have no idea if possible or not , don't know how want if isn't possible.

javascript - Split Array of Objects -

is there way of changing array of objects few seperate arrays each property of objects? for example, have this: [ { date: mon aug 08 2016 16:59:16 gmt+0200 (cest), visits: 0, hits: 578, views: 5131 }, { date: tue aug 09 2016 16:59:16 gmt+0200 (cest), visits: -1, hits: 548, views: 722 }, { date: wed aug 10 2016 16:59:16 gmt+0200 (cest), visits: -1, hits: 571, views: 4772 } ] and want this: var dates = ["date1", "date2", ...], visits = ["visit1", "visit2", ...], hits = ["hits1", "hits2", ...], views = ["view1", "view2", ...]; so can use plot.ly. you can use map : var array = [ { "date": 'mon aug 08 2016 16:59:16 gmt+0200 (cest)', visits: 0, hits: 578, views: 5131 }, { "date": 'tue aug 09 2016 1

ios - Swift 3: sum value with group by of an array of objects -

i have code in viewcontroller var myarray :array<data> = array<data>() in 0..<mov.count { myarray.append(data(...)) } class data { var value :cgfloat var name :string="" init({...}) } my input of data as: 10.5 apple 20.0 lemon 15.2 apple 45 once loop through, return new array as: sum(value) group name delete last row because no have name ordered value expected result based on input: 25.7 apple 20.0 lemon and nothing else i wrote many rows of code , confused post it. i'd find easier way, has idea this? first of data reserved in swift 3, example uses struct named item . struct item { let value : float let name : string } create data array given values let dataarray = [item(value:10.5, name:"apple"), item(value:20.0, name:"lemon"), item(value:15.2, name:"apple"), item(value:45, name:"")

android - AeroGear UnifiedPush Cordova register devices -

i have deployed unifiedpush on jboss 6.4, can access admin ui , create new apps. m trying build new app, in order test push notifications admin console. i'm using phonegap , building android platform. i'm executing on genymotion android emulator. this index.html page: <link rel="stylesheet" type="text/css" href="css/index.css" /> <title>hello world</title> <script> var app = { // application constructor initialize: function() { this.bindevents(); }, // bind event listeners // // bind events required on startup. common events are: // 'load', 'deviceready', 'offline', , 'online'. bindevents: function() { document.addeventlistener('deviceready', this.ondeviceready, false); }, // deviceready event handler // // scope of 'this' event. in order call 'receivedevent' // function, must

git - Picking the commits to merge with master -

say have buggy function in master branch: def foo(x): return 1/x git commit -a -m "foo created" i create new branch called bug debug it. git checkout -b bug i create print statements debugging, , commit: def foo(x): print x return 1/x git commit -a -m "print statements added debugging" finally bug fixed. def foo(x): print x if x == 0: return none return 1/x git commit -a -m "foo bug fixed" now rebase second commit on bug branch master , don't add print statements (i.e. first commit), use interactive rebase follows: git rebase -i master drop b2296f0 printing pick 62beaa8 fixed and select second commit (i.e. bugfix), conflict: def foo(x): <<<<<<< head ======= print x if x == 0: return none >>>>>>> 62beaa8... fixed return 1/x is there way have git correct version, without me manually deleting debug print statements? your chec

xaml - Set a property of a nested element in an WPF style -

i have several styles 1 (left, right, center) differ in corners (if any) rounded. <style x:key="toggleradiobuttonleft" targettype="{x:type togglebutton}" basedon="{staticresource {x:type togglebutton}}"> <setter property="template"> <setter.value> <controltemplate targettype="togglebutton"> <border borderbrush="blue" background="{templatebinding background}" padding="15,0" borderthickness="1" cornerradius="10,0,0,10"> <!-- extract --> <contentpresenter horizontalalignment="center" verticalalignment="center"/> </border> </controltemplate> </setter.value>

Send .dex file via post request android studio -

for own purposes, want send other app's dex file remote server , answer. i've used answers found here. tried create simple example @ first, connect server , upload dex file. far haven't managed extract dex other apps , thought of using dex file have. i've read, not common files should stored either "/res/raw" or "assets" tried many ways load file none of them worked . path used in cases found in right click on file -> copy reference. create res folder under /raw , file f = new file("res/raw/filename.dex"); create new assets folder under /app file f = new file("filename.dex"); create assets folder under /main file f = new file("main/assets/filename.dex"); and on. the way managed using inputstream inputstream in = getresources().openrawresources(r.raw.filename_without_dex) but couldn't cast file, dropped solution.i want have file cause following post request must multipart/form. in ja

php - How to update insert data in laravel 5.2 -

i need if , else function insert record , again update same record in drop , down input. blade view <input type="hidden" id="cid" name="cid" value="{{ $collaborator->user()->first()->id }}" /> <div class="form-group{{ $errors->has('status') ? ' has-error' : '' }}"> <label for="status" class="control-label">choose permission</label> <select name="status" id="status"> <option value="">choose status</option> <option value="3">view only</option> <option value="2">edit tasks</option> <option value="1">admin</option> </select> my controller saving new record public function addp

Why are mutable values allowed in Python Enums? -

this of follow on why mutable values in python enums same object? . if values of enum mutable (e.g. list s, etc.), values can changed @ time. think poses of issue if enum members retrieved value, if inadvertently changes value of enum looks up: >>> enum import enum >>> class color(enum): black = [1,2] blue = [1,2,3] >>> val_1 = [1,2] >>> val_2 = [1,2,3] >>> color(val_1) <color.black: [1, 2]> >>> color(val_2) <color.blue: [1, 2, 3]> >>> my_color = color(val_1) >>> my_color.value.append(3) >>> color(val_2) <color.black: [1, 2, 3]> >>> color(val_1) traceback (most recent call last): ... valueerror: [1, 2] not valid color i think given normal python idioms okay , implication being users can use mutables enum values, understand can of worms might opening. however brings second issue - since can enum memeber value, , value can mutable, must doing lo

unit testing - how to write a test for Javascript -

i attempting write test code having problems. const attemptfinish = (taskid, then) => (disp) => { return api .finishtask(taskid) .then(then); }; export default attemptfinish; the finishtask function so finishtask(taskid) { return ajaclass .post(host + '/comptask/mark', { id: taskid }); } i using sinon try , create response used results. has promise makes more complex describe ("attemptfinish assess actions", () => { var participantid = 145; var prom = new promise((resolve, reject) => { resolve(); }); it("should return", () => { var astub = sinon.stub(api, "finishtask") astub.withargs(participantid, " "); var callback = sinon.spy(); attemptfinish(participantid, prom) astub.restore(); }); });

pdf - iText LocationTextExtractionStrategy/HorizontalTextExtractionStrategy splits text into single characters -

i used extended version of locationtextextractionstrategy extract connected texts of pdf , positions/sizes. did using locationalresult. worked until tested pdf containing texts different font (ttf). these texts splitted single characters or small fragments. for example "detail" not more 1 object within locationalresult list splitted 6 items (d, e, t, a, i, l) i tried using horizontaltextextractionstrategy making getlocationalresult method public: public list<textchunk> getlocationalresult() { return (list<textchunk>)locationalresultfield.getvalue(this); } and using pdfreadercontentparser extract texts: reader = new pdfreader("some_pdf"); pdfreadercontentparser parser = new pdfreadercontentparser(reader); var strategy = parser.processcontent(i, horizontaltextextractionstrategy()); foreach (horizontaltextextractionstrategy.horizontaltextchunk chunk in strategy.getlocationalresult()) { // chunk } but returns same result.

activerecord - Rails - find record with highest month/year -

i'm kinda stuck in select query question: have bill model, contains 2 integer attributes: month , year. retrieve more recent record (highest date) can check attribute value on it. ideas solving problem, since month , year independent attributes? thanks! bill.order('year desc, month desc').first

c++ - One definition rule warning -

i have been bitten nasty "one definition rule" violation. afraid of having lots of subtle bugs in projects. for example, following program result in null pointer dereference visual studio 2015: source1.cpp: ---------- struct s { double d = 0; }; void foo() { s s; } source2.cpp: ----------- struct s { int = 0; }; int main() { int value = 5; int& valueref = value; s s; // valueref erased due s::d initialization source1.cpp valueref++; // crash } this compiles no warnings. it's nasty because source2.cpp doesn't use source1.cpp . if remove source1.cpp project, still compiles, , there no problem anymore. in large projects, seems hard ensure no cpp file "locally" define struct or class defined name. i have classes such point , serie , state , item , ... though ok in small cpp files, realize it's not safe. is there compiler warning catch such bugs ? if not, best practices avoid odr violation

Standard form posting with jQuery to php does not get all index values? -

Image
i'm trying submit form php somehow not data passed php? jquery initialized post this: var fieldsdata = $('form').serialize() $.post( "index.php", fieldsdata, function(data){ console.log( data ); }); .. fieldsdata variable try send server (i test in console) [ { "name": "form_key", "value": "feyzybqefjjtkzai" }, { "name": "shipment_item_3", "value": "" }, { "name": "shipment[items][3]_1", "value": "21" }, { "name": "shipment[items][3]_2", "value": "22" }, { "name": "shipment[items][3]_3", "value": "31" }, { "name": "shipment[items][3]_4", "value": "42" }, { "name": "warehouse-shipment[items][3]_1", "value&qu

Azure SQL service in Germany -

although azure seems have datacenters in germany, cannot select region when creating new sql server on azure portal. the azure pricing page show prices region, why not listed in available options? restrictions? there restrictions on azure regions, based on azure account. based azure account typically not able use these regions tax , legal reasons. full details on german data-center ga @ blog https://azure.microsoft.com/en-us/blog/microsoft-azure-germany-now-available-via-first-of-its-kind-cloud-for-europe/ customers in eu , efta can continue use microsoft cloud options today, or, want option, they’re able use services german datacenters

php - Inserting Multiple Rows In SQL SERVER -

i making audit form takes account available fields. i have columns, session_id (the id of current form created) ,fieldname, old value, new value. old value populated if user decides change value in form , saves it. so ideally when user fills out form first time , saves it, should create new rows (3 rows in example there's 3 fields) given details. |-----------------------------------------| | id | fieldname | old value | new value | |_________________________________________| | 123 | title | | mr | |_________________________________________| | 123 | firstname | | bob | |_________________________________________| | 123 | lastname | | smith | |-----------------------------------------| that audit 1 form 3 fields. there way in 1 sql request? populate table fieldnames available in form. an example of if update field. |-----------------------------------------| | id | fieldname | old value | new value | |____________

Passing 2 strings from one PHP script to the other using href -

i trying pass 2 strings first.php file second.php file- in first.php file, tried send data <?php echo "<a href='second.php?newformat=$statusstring&macaddress=$macaddress'>link</a>"; ?> and <a href="second.php?newformat="<?php echo $statusstring; ?> &macaddress=<?php echo $macaddress; ?>link</a> and <a href="second.php?newformat=<?php echo urlencode($statusstring);?>&amp;macaddress=<?php echo urlencode($macaddres); ?>"link</a> i tried of above possibilities. same error - php parse error: syntax error, unexpected '<' in /var/www/html/first.php on line 176 my $statusstring - "u=500000;t1=1479394;s=10;r=-33;v=3.7;" my $macaddres - "500000" can tell me how differently do this? edit 1 i have tried comment line in code, , code works without errors! edit 2 if(some condition) { $statusstring = "u=".$

image - AttributeError: module 'tensorflow.python.summary.summary' has no attribute 'histogram' -

i'm following " tensorflow poets " tutorial, , i'm stuck @ image retraining, when try run command: sudo python3 tensorflow/tensorflow/examples/image_retraining/retrain.py --bottleneck_dir=/tf_files/bottlenecks --how_many_training_steps 500 --model_dir=/tf_files/inception --output_graph=/tf_files/retrained_graph.pb --output_labels=/tf_files/retrained_labels.txt --image_dir tf_files/flower_photos and seems working fine, creating bottleneck @ /tf_files/bottlenecks/roses/5960270643_1b8a94822e_m.jpg.txt creating bottleneck @ /tf_files/bottlenecks/roses/8032328803_30afac8b07_m.jpg.txt creating bottleneck @ /tf_files/bottlenecks/roses/14176042519_5792b37555.jpg.txt ... but @ last, got error, traceback (most recent call last): file "tensorflow/tensorflow/examples/image_retraining/retrain.py", line 1014, in <module> tf.app.run() file "/usr/local/lib/python3.5/dist-packages/tensorflow/python/platform/app.py", line 30, in run sys.exit

caching - Solving for hit ratio in Effective Access Time given cache access -

i given following question: consider memory system cache access time of 10 nano sec (nsec) , memory access time of 200 nano sec (nsec). if effective access time 10% more cache access time, hit ratio? my intuition tells me set using eat equation know: [h(memory access + tlb access) + (1-h)(2*memory access + tlb access)] , solve there. however, solution sets 1.1*10 = 10*h + (1-h)(210) solving there ratio 189/190. where equation use come from? have been taught 1 gave means solve problems hit ratios , access times.

android - How to do a synchronous download for Amazon S3? -

so in android project have asynctask used load image imageview control. part of logic of background asynctask download image on demand if not exist on devices storage. company moved online images amazon s3 cloud storage. have followed steps create policy, include service in project, etc... , app working fine. feel had nasty make download transferutility work within asynctask. in every example of latest library api says should use transferutility download image. , every example can find uses asynchronous call download() method returns transferobserver. because running background thread of asynctask.doinbackground(), need make download transferutility synchronous. know solution came cannot considered "best practice" way of doing things looking advice how solve issue right way. ended making empty while{} loop checking see when transfer finished. there 2 possible solutions, 1 synchronous method replace transferutility.download() or 2 solution of how design nested asynchronous

change emacs encoding of a bunch of files all at once (UTF-8) -

i wondering if there way of changing encoding in emacs permanently , if there way change encoding of bunch of files written @ once. (to utf-8) (all files in same directory, , want change encoding @ once rather file file...) i know it's possible use: "revert-buffer-with-coding-system" change encoding of file. thank response, antonio

matlab - All possible combinations of the elements/vectors/list of vectors (Cartesian product) -

i have several vectors or lists of vectors , make possible concatenations of entries. here example: a1=4; a2=[1,6;1,9;6,9]; a3=[2;7]; that should result in: [4,1,6,2] [4,1,6,7] [4,1,9,2] [4,1,9,7] [4,6,9,2] [4,6,9,7] i think question similar one: generate possible combinations of elements of vectors (cartesian product) not able adapt answers problem. edit: thank again answer , corrections! beaker said works charm in octave. have little more flexible arbitrary number of a 's combined in cell array (or other structure fit potential solution better). made work around composing string , eval ing it. not seem pretty elegant me. possible have more... algorithmic? i answering using matlab in hope same code works in octave well. here's solution based on amro's answer in question linked: a1=4; a2=[1,6;1,9;6,9]; a3=[2;7]; nrows = [size(a1,1), size(a2,1), size(a3,1)]; [x,y,z] = ndgrid(1:nrows(1),1:(nrows(2)),1:(nrows(3))); cartprod = [a1(x(:),:) a2(y(

mysql - missing operator in query expression '.ID' -

i working on visual studio 2010 project wherein make database, create tables everytime run program , click button "create tables" message error occurs: "invalid table name" , " syntax error (missing operator) in query expression .'id' " can please me? codes: imports system.data.oledb public class table public property auditionees string public property trainingagencydepartment string public property trainingagency string public property sid1 string public property sname1 string public property sfield1 string public property sage1 string public property saddress1 string public property scontact1 string public property bkid2 string public property bkname2 string public property bkaddress2 string public property bkcontact2 string public property bid3 string public property bauditioned3 string public property bconfirmed3 string public property bsid3 string public property bbnum3 string private sub querycommand(byval query string) try

constructor - CoffeeScript Class Variable undefined 1.9 -

so looking @ coffeescript code not mine, trying understand why class variable undefined. coffeescript runtime 1.9 class commandparser obj: message: null indicator: 'warning' stacktrace: null result: null isexception: false constructor: (@command, @params, @result) -> @obj.result = result //@obj undefined i trying understand why @obj undefined assuming indentation looks like: class commandparser obj: message: null indicator: 'warning' stacktrace: null result: null isexception: false constructor: (@command, @params, @result) -> @obj.result = result then you're not getting typeerror @obj being undefined , you're getting referenceerror because there no result variable. when say: m: (@i) -> ... for method @i in argument list automatically assigns parameter value @i instance variable on object there won't i local variable. constructor : constructor: (@command, @params, @result) -&g

Spring Batch - Spring Integration - outbound-channel-adapter issue -

i have below steps. 1. read files sftp 2. process files , copy local folder 3. read processed file local folder , copy sftp out folder i able first 2 steps successfully, couldn't achieve third step. using outbound-channel-adapter copy files sftp. below codes. context.xml <?xml version="1.0" encoding="utf-8"?> <beans xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:file="http://www.springframework.org/schema/integration/file" xmlns:int="http://www.springframework.org/schema/integration" xmlns:int-ftp="http://www.springframework.org/schema/integration/ftp" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:batch="http://www.springframework.org/schema/batch" xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/u

python - Create list of interval times given start and stop time -

given string start , stop dates/times , number of intervals want count time in between: import datetime datetime import timedelta start = '16 sep 2016 00:00:00' stop= '16 sep 2016 06:00:00.00' scenlength = 21600 # in seconds (21600 6 hours; 18000 5 hours; 14400 4 hours) stepsize = 10 # seconds intervals = scenlength/stepsize how create list of dates , times? i new python , don't have far: timelist=[] timespan = [datetime.datetime.strptime(stop,'%d %b %y %h:%m:%s')-datetime.datetime.strptime(start,'%d %b %y %h:%m:%s')] m in range(0, intervals): ... timelist.append(...) thanks! if understood correctly, want find time stamps in regular interval. that can done python class datetime.timedelta : import datetime start = datetime.datetime.strptime('16 sep 2016 00:00:00', '%d %b %y %h:%m:%s') stop = datetime.datetime.strptime('16 sep 2016 06:00:00', '%d %b %y %h:%m:%s

c# - Left Join on Linq to Entity issue -

i need extract data orders table not assigned , assigned orders in different table orders_assigned. below linq entity code. issue : not getting unassigned orders, rather gets both unassigned , assigned orders. below linq code has issues including , clause {and [extent2].[chem_id] null} . suggestions how correct sql in linq entity code. var query = objorder in context.orders join objorderassigned in context.orders_assigned on new { key1 = objorder.chem_id, key2 = objorder.order_nbr } equals new { key1 = objorderassigned.chem_id, key2 = objorderassigned.order_no } temptbl temp in temptbl.defaultifempty() objorder.order_status == "new" select new order { compoundid = temp.chem_id, orderno = objorder.order_nbr,

compiler construction - Is it possible to determine if the memory array is accessed out of bounds in a Brainf**k program? -

i have written own bf interpreter in assembly, , i'm writing bf compiler in java compiles assembly code. i wanted implement little nice feature detected if array of memory cells out of bounds. traditional limitation array let index in [0, 30000) , otherwise [0, inf) commonly used. option memory wrapped around, in first case mean accessing index 30000 means accessing index 0. in compiler detection done @ semantic analysis phase of traditional compiler, have obtained our ast (abstract syntax tree) syntax analysis phase. after trying come construct while have found detecting infinite loop in brainfuck program , bf's wikipedia page have found out bf program memory array [0, inf) resembles turing machine. so question is, both [0, max) , [0, inf) cases, possible detect if memory pointer goes below zero, , in former case below max? without ending in infinite loop while checking it, , i'd rather avoid setting maximum execution time well. bonus question: possible d

utf 8 - Reading a single UTF8 character from stream in C# -

i looking read next utf8 character stream or binaryreader. things don't work: binaryreader::readchar -- throw on 3 or 4 byte character. since returns 2 byte structure, has no choice. binaryreader::readchars -- throw if ask read 1 character , encounters 3 or 4 byte character. read multiple characters if ask read more 1 character. streamreader::read -- needs know how many bytes read, number of bytes in utf8 character variable. the code have seems work: private char[] readutf8char(stream s) { byte[] bytes = new byte[4]; var enc = new utf8encoding(false, true); if (1 != s.read(bytes, 0, 1)) return null; if (bytes[0] <= 0x7f) //single byte character { return enc.getchars(bytes, 0, 1); } else { var remainingbytes = ((bytes[0] & 240) == 240) ? 3 : ( ((bytes[0] & 224) == 224) ? 2 : ( ((bytes[0] & 192) == 192

File uploaded to ftp server is corrupted c# -

i'm not sure why file corrupted. i'm not using streamreader has been common problem have had. uploads can't seem find issue on why file corrupted after searching through various solved stack overflow questions. public actionresult uploadftpfile(httppostedfilebase promoimgfile) { bool issavedsuccessfully = true; string filename = null; string completedpath = "xxxxx"; string username = "xxxx"; string password = "xxxxx"; ftpwebrequest ftpclient; ftpwebrequest ftprequest; list<string> directories = new list<string>(); try { foreach (string fileitemname in request.files) { httppostedfilebase file = request.files[fileitemname]; filename = file.filename; if (file != null && file.contentlength > 0) { //create ftpwebrequest object

delphi - Why does arrow key navigation not work in TWebBrowser? -

here simple program hosts twebbrowser control in vcl application: unit1.pas unit unit1; interface uses winapi.windows, winapi.messages, system.sysutils, system.variants, system.classes, vcl.graphics, vcl.controls, vcl.forms, vcl.dialogs, vcl.olectrls, shdocvw; type tform1 = class(tform) procedure formcreate(sender: tobject); end; var form1: tform1; implementation {$r *.dfm} procedure tform1.formcreate(sender: tobject); var browser: twebbrowser; begin browser := twebbrowser.create(self); tolecontrol(browser).parent := self; browser.align := alclient; browser.navigate('http://www.bbc.co.uk/'); end; end. unit1.dfm object form1: tform1 left = 0 top = 0 caption = 'form1' clientheight = 587 clientwidth = 928 color = clbtnface font.charset = default_charset font.color = clwindowtext font.height = -11 font.name = 'ms sans serif' font.style = [] oldcreateorder = false oncreate = formcreate pixelspe

vim - Capture Line numbers of lines matching a search -

example: search: /lastword\s*\n\zs\(\s*\n\)\{6}\ze\s*startword this search searches 6 empty lines between line ending "lastword" , line starting "startword" i catch linenumbers of empty lines matching search. is there way in vim? you can use :g , :number (or :# short) print out lines line numbers. :g/lastword\s*\n\zs\(\s*\n\)\{6}\ze\s*startword/# to capture content have use :redir redirect output somewhere else. in case below redirect unamed register ( @" ) :redir @"|execute 'g/pattern/#'|redir end note: must use :execute :g otherwise redir end executed on each matching line :g command. now going print via :# starting line not want (we want empty lines between foo , bar ). can use range :# command accomplish this. :redir @"|execute 'g/foo\_.*bar/+,/bar/-#'|redir end the range +,/bar/- translate start next line ( + ) , search bar ( /bar/ ) subtract 1 line ( - ). can simplify know number

android - How can I handle when remote bluetooth device suddenly is disconnected? -

first, don't speak english well. please consider this. i'm implementing bluetooth application. when android phone(bluetooth application) moves far behind remote device , remote device disconnected, want toast message("disconnected") appeared in phone. please explain in simple word how implement task.

playframework - Get populated data map after calling Form.fill method in Play 2.5 -

in play can populate form object fill method : form<myclass> myform = formfactory.form(myclass.class).fill(new myclass("some", "data")); however when call method data() on form object, return empty set, not expecting. how find way retrieve map<> of parsed bounded data ? myform.data() // {} empty ! only way see data 1 one calling method myform.field("fielda").value() i want achieve in order beneficiate data binding have defined in custom formatter, date formats.

python - got response 200 but nothing happen (flask-mysql) -

so follow tutorial , , after reach step connect python mysql, got 200 response code, on postman see this: { "error": "%d format: number required, not str" } and check table on mysql, nothing happen, still empty. please me. here code: from flask import flask flask_restful import resource, api, reqparse flaskext.mysql import mysql mysql = mysql() app = flask(__name__) app.config['mysql_database_user'] = 'root' app.config['mysql_database_password'] = 'root' app.config['mysql_database_host'] = 'localhost' app.config['mysql_database_port'] = '5002' app.config['mysql_database_db'] = 'itemlistdb' mysql.init_app(app) api = api(app) class createuser(resource): def post(self): try: parser = reqparse.requestparser() parser.add_argument('email', type=str, help='email address create user') parser.add_argument('passwo

jquery - Formatting slider values with commas -

$("#slider-range").slider({ range: true, min: 0, max: 200000, step: 500, values: [2500, 25000], slide: function(event, ui) { $("#amount").val("$" + ui.values[0] + " - $" + ui.values[1]); } }); $("#amount").val("$" + $("#slider-range").slider("values", 0) + " - $" + $("#slider-range").slider("values", 1)); how format outcome: $2,500 - $20,000 you can wrap $("#slider-range").slider("values", 0) parameter , pass function take value , of regular expression replace() method return new string matched pattern: function thousandseparate(val) { while (/(\d+)(\d{3})/.test(val.tostring())){ val = val.tostring().replace(/(\d+)(\d{3})/, '$1'+','+'$2'); } return val; } check working code: jsfiddle

javascript - Edit all cells in a column in ng-handsontable + Angularjs -

i'm having trouble checking/unchecking cells in column in ng-handsontable. controller looks like: $scope.items= [{},{},{},{}]; $scope.columns = { data: 'foo', title: "<input type='checkbox' onclick='console.log(items)' class='foo'>, type: 'checkbox', renderer: $scope.checkboxrenderer }; $scope.checkboxrenderer = function(instance, td, row, col, prop, value, cellproperties) { handsontable.renderers.checkboxrenderer.apply(this, arguments); if (value === true) { td.style.background = '#59e817'; } else { td.style.background= '#ff2400'; }; return td; }; so far works color boxes checked in rows. checkbox in header can checked or unchecked can't connect anything. when try log items object console or call function defined in controller, error saying $scope not defined or items not defined how access variables in scope within checkbox in