Posts

Showing posts from April, 2010

php - CSS - removing space between looped form buttons -

Image
*edited include screenshot i have form looped using php , trying remove spaces between each submit button. aesthetic reasons want able style space between them exactly. can lend insight how can accomplish this? the positiontext class seems some, , can't seem display:none have affect. <!doctype html> <html> <head> <meta charset="utf-8"> </head> <style> .positiontext { line-height: 0%; } </style> <body> <div class="positiontext"> <?php ini_set('display_errors',1); error_reporting(e_all); $result = file_get_contents('php://input'); require_once 'ircconfig.php'; $connection = new mysqli($db_hostname, $db_username, $db_password, $db_database); if ($connection->connect_error) die($connection->connect_error); $date = empty($result) ? date('y-m-d') : $result; { $query = "select * client_checkin date(

java - Morse code decoding - 1 word -

i working on encoding/decoding morse code program in java. i'm having trouble decoding. i'm working strictly uppercase alphabet , 1 word. no sentences. when debugged, program infinitely loops between lines 1 & 2. here have far: m[0] = .-; m[25] = --..; string decode (string m) { m = m + " "; string temp = ""; string word = ""; { temp = m.substring(0,m.indexof(" ")); //line 1 (int = 0; < m.length(); i++) { if (temp.equals(m[i])){ // line 2 word += (char)i + 'a'; m = m.substring(m.indexof(" " + 1)); } } } while (m.contains(" ")); return word; } try changing line inside loop this: m = m.substring(m.indexof(" ")+1);

Python series algorithm -

i have list of sort : numbers = [12, none, none, 17, 20, none, 28] what's best path consider in order fill in none values appropriate numbers none values numbers in between defined values. example : numbers = [12, **14**, **16**, 17, 20, **24**, 28] interpolating on fly create linear interpolation: def interpolate(l): last = none count = 0 num in l: if num none: # count number of gaps count += 1 continue if count: # fill gap based on last seen value , current step = (num - last) / float(count + 1) in xrange(count): yield last + int(round((1 + i) * step)) count = 0 last = num yield num demo: >>> list(interpolate([12, none, none, 17, 20, none, 28])) [12, 14, 15, 17, 20, 24, 28]

python 3.x - Why does printing a png file in Python3 result in extra characters in IDAT chunk? -

so i've been testing out reading uncompressed png files following code in python3: f = open(r'img1.png', 'rb') pixel = f.read() print(pixel) however results give strange additional characters besides hex pairs expect in idat chunk: b'\x89png\r\n\x1a\n\x00\x00\x00\rihdr\x00\x00\x00\x02\x00\x00\x00\x02\x08\x02\x00\x00\x00\xfd\xd4\x9as\x00\x00\x00\x19idat\x08\x1d\x01\x0e\x00\xf1\xff\x00\x00\x00\x00\x00\xff\xff\x01\x00\xff\xff\x13\x90\x90\x1b\xe4 \x0510o\xffc \x00\x00\x00\x00iend\xaeb`\x82' [finished in 0.1s] any idea is? under assumption in idat when data uncompressed pixel data in hex pairs. i've searched both stackoverflow/online looked through documentation png without luck. here link image using test (it's 4 pixels): img1.png fyi i'm running tests via archlinux if helps. i suspect senshin's comment on spot. when printing binary data, python prints printable ascii characters such, , remainder bytes \xhh h he

python - Can I force my enable Container to redraw from a traitsui Handler? -

i have employed traitsui.api.handler catch , handle events traitsui.api.view , view includes button, behavior remove plot container containing multiple plots. container's components list accessed when remove button used, pop() method called, , plot removed. however, view not redraw, , plot appears remain in place. resizing window through dragging corner force redraw, confirming pop() the question is: how can force redraw programmatically ? it seems me right place in handler's setattr method, after pop() -ing plot. # major library imports numpy import linspace scipy.special import jn # enthought library imports enable.api import container, componenteditor traits.api import hastraits, instance, button, int, str traitsui.api import item, hgroup, view, vsplit, uitem, instanceeditor, handler # chaco imports chaco.api import arrayplotdata, gridcontainer, plot # =============================================================================== # attributes use plot view

node.js - Nodejs / Q : Chaining promises sequentially -

i want simple, don't understand little thing ... var q = require('q'); var funcs = ["first", "second", "third", "fourth"]; function main(){ // don't know how chain sequentially here ... var result = q(); funcs.foreach(function (f) { result = treat(f).then(f); }); } function treat(t){ var deferred = q.defer(); settimeout(function(){ deferred.resolve("treated "+ t); },2000); return deferred.promise; } main(); i each element of funcs array "treated" sequentially, output : treated first //2 seconds later treated second //2 seconds later treated third //2 seconds later treated fourth i cannot achieve :( should simple , don't catch :( judging example, assume saw sequences part of q readme , failed understand it. original example used "waterfall" model, when output of each function passed input next one: var funcs = [foo, bar

java - Spring boot and maven exec plugin issue -

i've created bare-bone maven project, empty except pom.xml . with pom (note parent element commented-out): <project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelversion>4.0.0</modelversion> <groupid>springboot-test</groupid> <artifactid>springboot-test</artifactid> <version>1.0.0-snapshot</version> <!-- <parent> --> <!-- <groupid>org.springframework.boot</groupid> --> <!-- <artifactid>spring-boot-starter-parent</artifactid> --> <!-- <version>1.1.9.release</version> --> <!-- </parent> --> <build> <plugins> <plugin> <artifactid>maven-compiler-plugin</artifactid> <

java - MongoDB distinct too big 16mb cap -

i have mongodb collection. simply, has 2 columns: user , url. has 39274590 rows. key of table {user, url}. using java, try list distinct urls: mongodbmanager db = new mongodbmanager( "website", "userlog" ); return db.getdistinct("url"); but receive exception: exception in thread "main" com.mongodb.commandresult$commandfailure: command failed [distinct]: { "serverused" : "localhost/127.0.0.1:27017" , "errmsg" : "exception: distinct big, 16mb cap" , "code" : 10044 , "ok" : 0.0} how can solve problem? there plan b can avoid problem? thanks. take @ answer 1) easiest way via aggregation framework. takes 2 "$group" commands: first 1 groups distinct values, second 1 counts of distinct values 2) if want map/reduce can. two-phase process: in first phase build new collection list of every distinct value key. in second count() on new collection.

node.js - Node host configuration -

i have vps 10 ip directions , need configure installation of sails.js run on 1 ip direction. default when run project "sails lift" runs on ip directions , dont want it.... want run node projects in specific ip. :) root@c352 [/home/node/shamman]# sails lift info: starting app... info: info: info: sails.js <| info: v0.9.16 |\ info: /|.\ info: / || \ info: ,' |' \ info: .-'.-==|/_--' info: --'-------' info: __---___--___---___--___---___--___ info: ____---___--___---___--___---___--___-__ info: info: server lifted in /home/node/shamman` info: see app, visit localhost:1337 info: shut down sails, press + c @ time. debug: -------------------------------------------------------- debug: :: fri dec 05 2014 15:44:32 gmt-0430 (vet) debug: debug: environment : development debug: port : 1337 debug: ------

php - symfony2 upgrade 2.0 > 2.3 issue with Symfony\Component\HttpFoundation\Session -

here's custom security listener (from sym 2.0) namespace mine\userbundle\eventlistener; use symfony\component\security\http\event\interactiveloginevent; use symfony\component\security\core\securitycontext; use symfony\component\httpfoundation\session session; class securitylistener { protected $security; protected $session; /** * constructs new instance of securitylistener. * * @param securitycontext $security security context * @param session $session session */ public function __construct(securitycontext $security, session $session)//<-- here { //you can bring whatever need here, start should useful $this->security = $security; $this->session = $session; } /** * invoked after successful login. * * @param interactiveloginevent $event event */ public function onsecurityinteractivelogin(interactiveloginevent $event) { //your logic needs go here //you can addrole //even persist if wa

C# Datagridview selected row -

i have datagridview have implemented search function. entering characters while datagridview in focus first row of grid characters selected. i use: dtgview[index].selected = true; dtgview.firstdisplayedscrollingrowindex = index; the row gets selected, when press or down arrows navigate or down selected row, datagridview starts row index 0 in datagrid , not newly selected row? here op's original code / method private void dtgview_keyup(object sender, keyeventargs e) { if (e.keyvalue >= 65 && e.keyvalue <= 90 ) { searchstrings += e.keycode; (int = 0; < dtgview.rowcount; i++) { if (dtgview.rows[i].cells[0].value.tostring(). substring(0, searchstrings.length) == searchstrings) { dtgview.clearselection(); dtgview.firstdisplayedscrollingrowindex = i; dtgview.rows[i].selected = true; dtgview.rows[i].cells[0].selected = true

javascript - JQuery- Change the id of an element and call a function on click -

i have element id, changed id , when click on element (with new id now), still calls function previous id $('#1st').click(function(){ $('#1st').attr('id','2nd'); alert("id changed 2nd"); }); $('#2nd').click(function(){ alert("clicked on second"); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <a href="javascript:;" id="1st">click</a> example here because add event before element exists. not find element. either attach event when change id or need use event delegation. $('#1st').on("click.one", function(e) { $('#1st').attr('id', '2nd'); alert("id changed 2nd"); e.stoppropagation(); $(this).off("click.one"); }); $(document).on("click", '#2nd', function()

javascript - Multi-threaded Nashorn: o.constructor === o.constructor gives false -

i'm experimenting multi-threaded scripts loading , evaluation in nashorn , kind of shocking behavior: // having object o loaded in thread print(o.constructor === o.constructor); // false print(o.constructor === object); // false print(o.foo === o.foo); // true - ok how can possible within single script engine? o above object created using object literal notation (in thread). printing o.constructor gives usual function object() { [native code] }; . at same time: print({}.constructor === {}.constructor); // true any ideas? update it turned out unrelated multi-threading @ all. see answer below details. it turned out not relate multi-threading @ all. here simple scala program reproduces problem: object test extends app { val engine = new scriptenginemanager().getenginebyname("nashorn") var o = engine.eval("({ foo: 'bar' })") var result = engine.eval("(o.constructor === o.constructor)", new simplebindings() {

php - My script downloads the source of the page and not the actual file -

i've got problem downloading script.. made uploading script -> adds files in folder called uploads , inserts id, filename , link database.but can't find way download uploaded file. here's download script: <?php include('config.php'); $dwquery = mysqli_query($db, "select id, filename files"); $id = intval($_get['id']); while ($row = mysqli_fetch_array($dwquery)) { echo '<a href="download.php?id='.$row['id'].'">'.$row['filename'].'</a><br />'; } $download = mysqli_query($db, "select link files id=$id"); $link = mysqli_fetch_array($download); if($id != '') { header('content-disposition: attachment; filename='.$link[0]); readfile($_server['document_root'] . '/project/' .$link[0]); } ?> when select file download downloads source

Converting a text file to an array in Java -

i'm beginner @ java , have list of 25 students include name, age, income , iq in text file. i'm struggling how take text file , put in array can sort them , such. far have: file myfile = new file ("./src/project2/studentlist"); scanner myscan = new scanner(myfile); while (myscan.hasnext()) { string line = myscan.nextline(); scanner scanner = new scanner(line); scanner.usedelimiter(","); while (scanner.hasnext()) { string name = scanner.next(); string age = scanner.next(); string income = scanner.next(); string smart = scanner.next(); student students = new student(name, age, income, smart); system.out.println(students); } } i want know easiest way go this. i'm close, can feel it! in advance. define array: student[] students = new student[25]; int = 0; then in loop student student = new student(name, age, income, smart); students[i++] = student; or dynamic a

cqrs - Rebuild queries from domain events by multiple aggregates -

i'm using ddd/cqrs/es approach , have questions modeling aggregate(s) , queries. example consider following scenario: a user can create workitem, change title , associate other users it. workitem has participants (associated users) , participant can add actions workitem. participants can execute actions. let's assume users created , need userids. i have following workitem commands: createworkitem changetitle addparticipant addaction executeaction these commands must idempotent, cant add twice same user or action. and following query: workitemdetails (all info work item) queries updated handlers handle domain events raised workitem aggregate(s) (after they're persisted in eventstore). these events contain workitemid. able rebuild queries on fly, if needed, loading relevant events , processing them in sequence. because users won't access workitems created 1 year ago, don't need have these queries processed. when fetch query doesn't exis

ios - How to increase UISegmentedControl total width? -

to clear front, i'm not asking how modify width of individual uisegmentedcontrol segments, or buttons. my end-goal create uisegmentedcontrol embedded in uiscrollview . uisegmentedcontrol have ability indefinitely increase number of segments. to accomplish this, need increase total width of uisegmentcontrol itself, each time segment added. there way can increase total width without recreating brand new uisegmentedcontrol object each time add segment? thank you, in advance! @matthiasbauch's comment helped me track down whole solution, detailed below: note : i'm using autolayout, anywhere use storyboard you'll have substitute programmatic equivalent. 1) first, drag "segmented control" out on the storyboard. 2) create outlet control added. 3) also, ctrl+click on control, , drag itself. click on "width" add width constraint. 4) now, open document outline (editor > "reveal document outline") 5) open "view

sql - Decimal(19,4) or Decimal(19.2) - which should I use? -

this sounds silly question, i've noticed in lot of table designs e-commerce related projects see decimal(19, 4) being used currency. why 4 on scale? why not 2? perhaps i'm missing potential calculation issue down road? first off - receiving incorrect advice other answers. obseve following (64-bit os on 64-bit architecture): declare @op1 decimal(18,2) = 0.01 ,@op2 decimal(18,2) = 0.01; select result = @op1 * @op2; result ---------.---------.---------.--------- 0.0001 (1 row(s) affected) note number of underscores underneath title - 39 in all. (i changed every tenth period aid counting.) precisely enough 38 digits (the maximum allowable, , default on 64 bit cpu) plus decimal point on display. although both operands declared decimal(18,2) calculation performed, , reported, in decimal(38,4) datatype. (i running sql 2012 on 64 bit machine - details may vary based on machine architecture , os.) therefore, clear no precision being lost. on contrar

html - navbar list items changing size depending on list string length -

i made navbar supposedly has list items evenly distributed along navbar, although seems list items longer string lengths have bigger width others. there way fix this? <div id="menu-bar"> <ul> <li><a href=#>home</a></li> <li><a href="ferrari.html">ferrari</a></li> <li><a href="lamborghini.html">lamborghini</a></li> <li><a href="bugatti.html">bugatti</a></li> </ul> </div> css: * { margin: 0px; padding: 0px; } #menu-bar { background-color: #51f069; width: 100%; height: 40px; border-top: 2px solid #8f8f8f; border-bottom: 2px solid #8f8f8f; display: table; } #menu-bar li { list-style-type: none; display: inline-block; font-family: ferrari; display: table-cell; text-align: center; } #menu-bar { display: block; font-size: 25px; line-height: 40px; } #menu-bar ul { width: 100%

c++ - Undefine reference error for static function -

this question has answer here: what undefined reference/unresolved external symbol error , how fix it? 27 answers i have below code , getting undefined reference `stinit::instance()' file stinit.h class stinit { public: static stinit* instance(); }; file stinit.cc #include "stinit.h" stinit* stinit::instance() { static stinit *myptr = null; ...... ...... return myptr; } file nm.cc #include "stinit.h" stinit* stor_init = stinit::instance(); i don't know why getting error. how resolve error? you not including 2nd file stinit.cc binary, hence linker error. not familiar tup, looking @ manual seems need include both files in tup file. look @ last example in documentation: http://gittup.org/tup/ex_a_first_tupfile.html , copying should going. so change tupfile to: : foreach *.c |> gcc -wall -c %f

python - How can I create a z3c.form that has multiple schemas? -

i using cms plone build form contains 2 other schemas. with group forms , have been able include both of fields of 2 schemas. however, lose of properties such hidden or when use datagridfield build table. want able have both of these forms fields , on save able save them in object link clicked parent -> object 1 [top of form] -> object 2 [bottom of form] here python code: class questionpart(group.group): label = u'question part' fields = field.fields(iquestionpart) template = viewpagetemplatefile('questionpart_templates/view.pt') class question(group.group): label = u'question' fields = field.fields(iquestion) template = viewpagetemplatefile('question_templates/view.pt') class questionsinglepart(group.groupform, form.addform): grok.name('register') grok.require('zope2.view') grok.context(isiteroot) label = u"question single part" ignorecontext = true enable_f

Make object return float value python -

i can't think of similar in other language python can this... what need following: when referencing object's value, need object return float. eg: b = anyobject(3, 4) print(b) #should output 0.75 i have tried following: def __get__(self, instance, owner): return float(self.param1/self.param2) but not work. when printing b this, object's reference: <(...) object @ 0x10fa77e10> please help! thanks you're seeing <fraction object @ 0xdeadbeef> because that's __str__ method of object class returns in python implementation: class name , address. make print work, need override __str__ method own code replace method inherited object . , while you're @ it, can make float(obj) work implementing __float__ method. from __future__ import division class fraction(object): def __init__(self, num, den): self.num, self.den = num, den # built-in function float(obj) calls obj.__float__() def __floa

ocaml - Implementing a simple factorial function using continuation passing style -

i'm trying implement function returns factorial in ocaml don't know if i'm using continuation passing style: let fact n = let rec factorial n cont = match n | 0 -> cont () | _ -> factorial (n-1) (fun () -> cont () * n) in factorial n (fun () -> 1) it seems me i'm not delaying computation displacing computation in code. well, code interesting. not usual, tail-recursive, work. show "usual" way of doing cps. usually, returning function using continuation, why idea name continuation return . also, start identity function initial value continuation. , finally, you're using continuation assembly, build answer. let factorial n = let rec loop n return = match n | 0 -> return 1 | n -> return (loop (n-1) (fun x -> x * n)) in loop n (fun x -> x) so in example, pass continuation accumulate and, finally, build answer. to summarize, 3 simple rules: return continuation start identity update cont

php - PHPUnit Explicit Testsuites -

is possible define testsuite not run default? run when explicitly called. the definition looks like: <testsuite name="1st"> <file>test/1sttest.php</file> </testsuite> <testsuite name="2nd" explicit="true"> <file>test/2ndtest.php</file> </testsuite> sadly no, phpunit not support feature. as alternatives: you use 2 separate config files phpunit, define "2nd" testsuite in 1 file , use them -c <config_name>.xml option when run phpunit. same base principle above, time 2 separate bash files, instead of xml config files. call phpunit each --testsuite="<suite_name>" option.

multithreading - UI Update from secondary thread - Performselectoron mainthread or dispatch_get_main_queue -

i using (simplified): dispatch_async(dispatch_get_main_queue(),^{ [progresslevel2 setdoublevalue:songcount]; }); id not redo using performselectoronmainthread find have other issue. shouldn't code working?

Create Variable from MySQL Cell Inside Loop PHP -

i hope title sufficient contents of question... i've patched little script various sources writes every row in mysql database separate xml file. supposed do, i'm hung on naming convention. i'd name xml file 'id' column of row being exported, $id is name of file sans extension. tried accessing through xpath no avail. how access particular column's data (cell) , assign variable? <?php $host = ""; $user = ""; $pass = ""; $database = ""; // replace query matches database $sql_query = "select * data"; $db_link = mysql_connect($host, $user, $pass) or die("could not connect host."); mysql_select_db($database, $db_link) or die ("could not find or access database."); $result = mysql_query ($sql_query, $db_link) or die ("data not found. sql query didn't work... "); //rows while ($row = mysql_fetch_array($result, mysql_assoc)) { $id; $xml =

sql server 2008 - SQL TRIGGER THE MULTI-PART IDENTIFIER CANT BE BOUND -

i new programming. trying teach myself sql. made video store database customer, rental, , inventory table. looking @ examples online try learn sql, please kind. want trigger stop person renting same movie @ same time. have been reading on triggers , code below. i getting syntax errors on last end, syntax error on raiseerror, , inserted. still getting message "trigger multipart identifier cannot bound" on i.rental.rentnum inserted i; any appreciated! create trigger insteadofinsert on rental instead of insert declare @rentnum int, @action varchar(60) select @rent_rentnum=i.rental.rentnum inserted i; set @action='stop rental trigger.' @rent_rentnum=(select rentnum inserted; begin begin tran set nocount on if (@rent_rentnum=rental.rentnum) begin raiseerror ('you cannot rent same move twice'); rollback end else begin insert rental(rentnum)

scroll - Macbook retina CSS: scrollable div scrollbar overlapped by parent scrollbar -

found strange problem, did googling , didn't find similar issues. in short. have position fixed div inside position fixed div. on non-retina, everything's fine, on macbook retina (webkit browsers) scrollbar of parent overlaps scrollbar of div should on top: http://jsfiddle.net/3by6ohq0/ position:fixed does have ideas? in advance. visual comparison of non-retina vs. retina: http://i.imgur.com/itlrgmh.png the reason behind relates usage of pixels. right now, inner fixed div of class "floating" have set to: right:7px; in hope make off scrollbar. however, unfortune, scrollbars not same width in every operating system. on retina macbooc pro,there more pixels make width of scrollbar (so it's not tiny eye), 2x amount, , therefore 7px right not justify greater amount of pixels. nor on ubuntu use. best method this: .floating { position:relative; float:right; } or absolute positioning better fixed. because right since parent element

SQLite persisting data via php to MySQL server iOS -

sorry in advance sounding novice i'm new app development , hope can me! i'm trying create ios app store data locally when offline (i.e. email address) , once connectivity internet available persist data across server. first created sqlite database done using db browser tool, , part working way should. app uses core data persist sqlite db. next created php file check internet connection select sqlite db , it's data insert data mysql db. this got stuck. right in thinking data saved in sqlite db when running on device saved in device's document directory? if true how gain access via php file persisted on mysql server? am missing something? correct way of persisting data across sqlite db on device mysql server? many in advance help. it sounds want store data in cookie (the email address), , post server when online. not need offline client db data small email address. you ajax (asynchronous javascript), posting awaiting php file based upon javas

Creating a Wordpress masonry style gallery with a lightbox that only cycles through images with the same category/tag -

i trying create wordpress image gallery few things no 1 plugin seems on own. basically want to: 1. split media library categories/albums 2. display every image albums mixed on same page in masonry style layout (an image category a, image category b, image category c etc etc) 3. bring lightbox when image clicked cycles through images same category the difficulty i'm not sure begin, i'm looking ideas on how should approach it. starting plugin separates media library categories/albums place start? native wordpress masonry/tiled gallery , lightbox adapted rest? update: i've registered new taxonomy applies attachments, images belong categories really sorry not giving better starting point! to sum understanding of need: need posts, attached images belong categories. replying points: forget splitting media library; you loop through posts; you install simple lightbox gallery plugin , loop posts need. to accomplish this: register custom post type (w

performance - Python - Reducing Import and Parse Time for Large CSV Files -

my first post: before beginning, should note relatively new oop, though have done db/stat work in sas, r, etc., question may not posed: please let me know if need clarify anything. my question: i attempting import , parse large csv files (~6mm rows , larger come). 2 limitations i've run repeatedly have been runtime , memory (32-bit implementation of python). below simplified version of neophyte (nth) attempt @ importing , parsing in reasonable time. how can speed process? splitting file import , performing interim summaries due memory limitations , using pandas summarization: parsing , summarization: def parseints(instring): try: return int(instring) except: return none def texttoyearmo(instring): try: return 100*instring[0:4]+int(instring[5:7]) except: return 100*instring[0:4]+int(instring[5:6]) def parseallelements(elmvalue,elmpos): if elmpos in [0,2,5]: return elmvalue elif elmpos == 3: ret

javascript - Check module version -

i need check if module of version. i can check if module exists in same folder doing this: var other; try { other = require("../theothermodule"); } catch(e){ // module doesn't exist or } however, doesn't tell me version of module. need able tell if module of version or higher. i don't think there's built-in function this. instead, can version package.json file: var packagejson = require('./package.json'); console.log(packagejson.version);

php - Update array but don't add new items -

so have 2 arrays. old , new one. want update new array variables old array don't want add new indexes in old array aren't in new array. $old_array = array("1" => "one", "2" => "two", "3" => "three", "4" => "four"); $new_array = array("1" => "1", "2" => "2", "3" => "3"); so want new array be: $updated_array = array("1" => "one", "2" => "two", "3" => "three"); could me effective way this? can try using foreach() . example: $old_array = array("1" => "one", "2" => "two", "3" => "three", "4" => "four"); $new_array = array("1" => "1", "2" => "2", "3" => "3"); $updated_array = a

c# - accessing a non-static member error while using form/controls from static method -

in project of mine have code following in class i've written named keyboardhook... private static intptr keyboardhookid = intptr.zero; public static intptr hookcallback(int ncode, intptr wparam, intptr lparam) { if (ncode >= 0 && wparam == (intptr)wm_keydown) { int vkcode = marshal.readint32(lparam); //update ui here... } return callnexthookex(keyboardhookid, ncode, wparam, lparam); } i'd update ui statement like form1.label1.text = vkcode.tostring(); ...but causes problem c# compiler; namely accessing non-static member. need create reference form1 object,ie. application.run(new form1()); what do? in solutionexplorer open program.cs , change code there following static class program { public static form1 mainform = null; /// <summary> /// main entry point application. /// </summary> [stathread] static void main

how to handle unix command having \x in python code -

i want execute command sed -e 's/\x0//g' file.xml using python code. but getting error valueerror: invalid \x escape you not showing python code, there room speculation here. but first, why file contain null bytes in first place? not valid xml file. can fix process produces file? secondly, why want sed ? using python; use native functions sort of processing. if expect read file line line, like with open('file.xml', 'r') xml: line in xml: line = line.replace('\x00', '') # ... processing here or if expect whole file 1 long byte string: with open('file.xml', 'r') handle: xml = handle.read() xml = xml.replace('\x00', '') if want use external program, tr more natural sed . syntax use depends on dialect of tr or sed well, fundamental problem backslashes in python strings interpreted python. if there shell involved, need take shell's processing account.

java - Add a method on the x Button on JFrame and WordWrap -

so i'm making notepad on java gui, have lot of problems @ time please me. first problem stated on title want add method x button on jframe. have method on codes below don't know how input on x button. and other problem word-wrap jcheckboxmenuitem . not work don't know why . want behave in ordinary notepad (if click it word wrap , if click again stop). import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.scanner; import java.io.*; import javax.swing.text.defaulteditorkit; public class sample extends jframe implements actionlistener { private jtextarea textarea = new jtextarea("", 0,0);// textarea private jmenubar menubar = new jmenubar(); // menubar item private jmenu edit =new jmenu("edit"); // edit menu private jmenu file = new jmenu("file"); // file menu private jmenu format = new jmenu ("format");// format menu // private wordbuttonhandler wordhandler; //in f

c# - WebBrowser using Google map shows script error after it loaded a couple of times succesful -

i working on c# windows form application , show google map in application through webbrowser control google map direction url here url of google map direction m putting url in winform webbrowser navigate , show me map give him addresses point , adresses come **textboxes** here c# code : webbrowser1.navigate( @"https://www.google.com/maps/dir/" + textbox1.text + "/" + textbox2.text + "///@28.1925465,68.3193684,7z"); working fine sometime , shows me script error when sript error navigate , google map stuck in c# webbrowser control if surpress script error error hide map still in stuck position. how can solve this? you can using gds google map winforms control . here how: drag gdsgooglemap form, name _gdsgooglemap , set dock property "fill"; create event handler map initialized event , code as: private void ggdsgooglemapmapinitializedeventhandler(object sender, mapinitialize

c++ - garbage values for vector push_back -

i'm trying assign array's values vector. seems working fine 1 vector, when second, i'm getting garbage values. cout number , know it's correct, it's not assigning correctly. don't understand because it's working fine first vector. int sorted[] = {0,1,2,3,4,5,6,7,8,9,10}; // make 2 smaller arrays, untill base case size; void split(int *datain, int datasize){ // new data broken 2 vectors each half of // original array. these size firsthalfsize , secondhalfsize. int firsthalfsize; int secondhalfsize; vector<int> firsthalf; vector<int> secondhalf; // test see if array in odd or bool isodd; if (datasize%2 == 1){ isodd = true; }else if (datasize%2 == 0){ isodd = false; } // determine length of new vectors // second half firsthalf + 1 if odd. firsthalfsize = datasize/2; if (isodd){ secondhalfsize = firsthalfsize + 1; }else

ruby - What is the difference between a method and a proc object? -

i know methods in ruby not objects procs , lambdas are. there difference between them other that? because both can pass around. makes proc objects different method? method: 1.8.7-p334 :017 > def a_method(a,b) 1.8.7-p334 :018?> puts "a method args: #{a}, #{b}" 1.8.7-p334 :019?> end 1.8.7-p334 :021 > meth_ref = object.method("a_method") => #<method: class(object)#a_method> 1.8.7-p334 :022 > meth_ref.call(2,3) proc object: = lambda {|a, b| puts "#{a}, #{b}"} a.call(2,3) you said in question "methods not objects" have careful distinguish between "method" , "method". a "method" defined set of expressions given name , put method table of particular class easy lookup , execution later. a "method" object (or "unboundmethod" object) actual ruby object created calling method / instance_method / etc. , passing name of "method" argument.

javascript - radio button list with text option cakephp -

i new cakephp. need make form radio buttons , last 1 "other" user can type in answer in text box. is there way formhelper can that's built in? one way going create radio list , text field. when "other" selected javascript show text field. don't understand how use other variables besides fields in database. how 1 create variable model can accessed view , value returned processing? for model have: class user extends appmodel { /** * display field * * @var string */ public $displayfield = 'title'; var $sourceother = ' '; var $passwordrepeat = ' '; public function beforesave($options = array()) { if (isset($this->data[$this->alias]['password'])) { $this->data[$this->alias]['password'] = sha1( $this->data[$this->alias]['password']); } // $this->data[$this->alias]['created']= c