Posts

Showing posts from June, 2011

QML forwards/back mouse buttons handling -

i'm trying have qml application react forwards/back buttons (sometimes labeled buttons 4/5) on mice. seems mouse area/event allows signals on 3 main mouse buttons. is there way handle these buttons in qml? if @ list of predefined mouse buttons you'll see there forwardbutton , backbutton. "trick" need listen these buttons in qml mousearea set acceptedbuttons property. you either set listen forward , back: acceptedbuttons: qt.forwardbutton | qt.backbutton or listen mouse button: acceptedbuttons: qt.allbuttons putting together, mousearea this: mousearea { acceptedbuttons: qt.allbuttons onclicked: { if (mouse.button == qt.backbutton) { console.log("back button"); } else if (mouse.button == qt.forwardbutton) { console.log("forward button") } } }

c++ - GTK : Any way to mximize the window on Button trigger -

is there callback function, when click button window maximizes. way i'm using gtk 3.0 , c++ (not gtkmm). wrote function called during button click event , put line int maximise(){ gtk_window_fullscreen(gtk_window(window)); } it gets compiled, while click button program terminates showing segmentation fault. (this function inside class) check whether callback called using i.e. g_print make sure signal correctly connected button g_signal_connect (button, "clicked", g_callback (maximise), null); and window gtkwidget * type note written gtkbutton reference callback have that: void user_function (gtkbutton *button, gpointer user_data) and have type of callback int for me both versions (with int , void callback works)

C# AES and RSA File Encryption - How to use IV? -

i'm writing program @ moment works under following scenario: i've got confidential log files need backup server. i have program generates these log files every day. these log files if ever need opened. i have 1 rsa public/private key pair. the program has rsa public key. i generate random aes key each time program makes 1 of these confidential files. the program uses aes key encrypt log file. i use rsa public key encrypt aes key i backup both aes encrypted file , rsa encrypted aes key server. as far understand, protocol fitting use case. the issue i'm having coding in c#. ran needing initialization vector(iv) aes encryption, tried encrypt along aes key using public rsa key on both. 512(2 * 256) size larger rsa happy encrypt. figured out since created initialization vector randomly each time aes key, can add iv front of aes ciphertext. however, i'm not sure code inserted in functions any in right direction "protocol" or other ways write iv...

elisp - Confused when setting an Emacs face -

Image
(set-face-attribute 'diredp-dir-heading nil '(t (:foreground blue :background dark1))) what should right statements set face? bow// face attributes :foreground , :background must have string values. so try "blue" instead of blue etc. the error message see saying asked emacs evaluate blue , means find value variable. emacs tried , found symbol blue has no value variable. string "blue" , on other hand, evaluates itself, , string kind of value needed here.

java - JavaFX Application - architectural issue - diffrent lists of inherited classes -

i'm learning javafx tutorial http://code.makery.ch/library/javafx-8-tutorial/ , in app i've made login module , want create 3 diffrent views - depending on type of user: admin, patient, doctor, , of them inherit user class. create doctor view , keep list of patients in main class: private observablelist<patient> patientdata = fxcollections .observablearraylist(); public observablelist<patient> getpatientdata() { return patientdata; } public main() { patientdata.add(new patient("hans", "muster", 23)); } i dont know should next move be. if make 1 list user , keep them doctors, patients , admins problem generating proper views, cause e.g doctor have patients' list. big problem me how serialize xml. if make 3 separate list won't 'elegant' way think. you create single observablelist<user> , , populate various views using filteredlist . e.g. observablelist<use...

Call overridden method of parent class with child class object in python -

i have came around question during interview: class parent(object): def a(self): print "in a" class child(parent): def a(self): print "in b" c=child() question come here: is there way can call parent class function a child object @ instance level without doing changes in classes? have searched many question didn't find satisfactory answer.please reply. thanks. you can use super() builtin. >>> super(child, c).a() in it used call super class implementation inside subclasses, allowed outside. docs state: also note super() not limited use inside methods. 2 argument form specifies arguments , makes appropriate references.

c++ - How to drill down into shared_ptr [Netbeans, clang++, gdb] -

i'm using netbeans c++ 8.0.2 clang++ (ubuntu clang version 3.6.0-2ubuntu1 (tags/release_360/final) (based on llvm 3.6.0)) gdb (gnu gdb (ubuntu 7.9-1ubuntu1) 7.9) in "c++ simple tests," whenever inspect variable shared_ptr, see value is: std::shared_ptr (count 1, weak 0) 0x64d3a0 or similar. there no way drill down value of it's pointing to. if tree view in variables window shows 1 of expander icons, disappears when click it. when try dereferencing or calling get() function in "expressions" window, error messages: could not find operator*. and cannot evaluate function -- may inlined respectively. if create reference value in actual program, not allows me drill down reference, shared_ptr can drilled down (which seems fishy me). tried -g3 , -ggdb made no difference. is there debug version of standard library (is libcxx default?), or setting somewhere might improve situation? or maybe way list private members/raw view i...

php - Getting a value from text input field, then displaying on POST -

i'm trying value form, display on posting of form. can value appear in second text field, once have chosen option using ajax auto-select, how value shown stored variable display on posting? have been trying - if ($_post['action'] == 'getentity') { $value= $entity; $content .= '<div>'.$value.' hello</div>'; } <form method="post" action="?"> <input type="text" name="townid_display" size="50" onkeyup="javascript:ajax_showoptions(this,\'getentitiesbyletters\',event)"> <input type="text" name="townid" id="townid_display_hidden" value="'.$entity.'" /> <input type="hidden" name="action" value="getentity" /> <input type="submit" name="submit" value="find"/> many help. try <input type="text" name=...

java - How to make a youtube link as embed? -

<% string song = request.getparameter("songname"); string band = request.getparameter("band"); string url = request.getparameter("url"); %> <div align="center"> <br><br> <% out.print(band + " - " + song); %><br><br> <iframe width="560" height="315" src="<%out.print(url);%>" frameborder="0" allowfullscreen></iframe> </div> <% %> let's url https://www.youtube.com/watch?v=kxyiu_jcytu want make https://www.youtube.com/embed/kxyiu_jcytu can put @ src="" you can use replace() method: <% out.print(url.replace("watch?v=", "embed/")); %>

sdl - Nim and SDL2 trouble with Rect -

i have following nim+official libsdl2 wrapper code import sdl2 discard sdl2.init(init_everything) let window = createwindow("tic-tac-toe", sdl_windowpos_centered, sdl_windowpos_centered, 600, 390, sdl_window_shown) renderer = createrenderer(window, -1, renderer_accelerated or renderer_presentvsync or renderer_targettexture) proc loadimage(file: string): textureptr = let loadedimage = loadbmp(file) let texture = createtexturefromsurface(renderer, loadedimage) freesurface(loadedimage) return texture proc applysurface(x: cint, y: cint, tex: textureptr, rend: rendererptr) = var pos: rect pos.x = x pos.y = y querytexture(tex, nil, nil, pos.w, pos.h) copy(rend, tex, nil, pos) let background = loadimage("resources/bg.bmp") clear(renderer) applysurface(0, 0, background, renderer) present(renderer) var evt = sdl2.defaultevent rungame = true while rungame: while pollevent(evt): if evt.kind == quitevent: rungame = false ...

angularjs - how to test service property call -

here temp.js angular.module('temp', []) .service('tempfactory', function() { this.a = 10; }) .controller('tempctrl', function($scope, tempfactory) { $scope.a = tempfactory.a; }); and here temp.spec.js describe('temp', function() { var ctrl, scope; beforeeach(function() { module('temp'); inject(function($rootscope, $controller) { scope = $rootscope.new(); ctrl = $controller('tempctrl', {$scope: scope}); }); }); }); i know test service method call necessary use spy. how test service property call(in code $scope.a = tempfactory.a;)? how can find out property of service called? write spec tests value on scope. no spy needed. write effect of: it('sets expected value service', function () { expect(scope.a).tobe(10); });

javascript - Bounce a ball from one point to another - Vector and Acceleration -

Image
i have ball drops point, should bounce , reach point. my ball starts acceleration towards first point, hits point , bounces off left side. want velocity & acceleration applied ball after hitting first point, both has bouncing effect, , reaches it's destination (doesn't go offside, bright trail). i have linear vector between points, coordinates of points , angle between them. first figure out how long take higher point lower point solving t : at 2 + v iy t = dy then take t , use our lateral velocity: v x = dx / t once have lateral velocity, slice time finely , move ball each calculated point in turn.

ios - Swift - Checking size of UIImageView -

i trying print line debugger/console show dimensions of uiimageview object have. trying use following code error saying uiimageview doesn't have member named 'size'. code: @iboutlet var image: uiimageview! override func viewdidload() { super.viewdidload() var imageheight = image.size.height var imagewidth = image.size.width print (imageheight) print (imagewidth) } before question, several points: don't start name of instance variable upper case. don't use "image" variable name of image view. suggests uiimage . it's uiimage view , not uiimage . call theimageview . now question: uiview objects not have size property ( uiimage objects do have size property. might cause of confusion.) have bounds rectangle , frame rectangle. can use theimageview.bounds.size or theimageview.frame.size .

accessing program listing in prolog -

i'm having strange (or not strange) problems defining variables in swi-prolog. example: i'd below: :- initialization(main). main :- x = listing(main), write(x). but it's printing "listing(main)" maybe, using casual predicate instead of main/0... ?- with_output_to(atom(x), listing(pattern)), write(x). gram:pattern(a, b, c) :- dig(a, b, c). gram:pattern(a+c, b, e) :- ten(a, b, d), dig(c, d, e). ...

Android dynamically stacking views -

it seems issue pretty confusing me. i want view added on click on top of one. this: view view view view does know how this? that depends on "on top of one" means. if mean on y axis (vertically screen), use vertical linearlayout . if mean on z axis (perpendicular screen, heading towards user's eyes), use framelayout or relativelayout , later children higher on z axis earlier children. or, if minsdkversion 21 or higher, can use elevation property control z axis positioning.

How to correctly set the current time stamp into this Java CRUD method that insert a value into a MySql table? -

i have following table mysql database: create table log( timestamp timestamp not null, action enum('addperson', 'getperson', 'getpeople', 'updateperson', 'deleteperson', 'deleteall') not null, primary key (timestamp) ); now implementing java insert crud method dao finding problem setting timestamp value (initialized current date time) related prepared statment. so doing this: public void addentry(string message) throws sqlexception { // connection object singleton , used connection same crud methods: connection conn = database.getinstance().getconnection(); preparedstatement p = conn.preparestatement("insert log (timestamp, action) values (?,?)"); p.settimestamp(1, new timestamp(time)); } but gime men error on creation of timestamp object because need long value. think not !!! how can set current timestamp (the current date-time)? tnx try this: p.settimestamp(1, new ti...

c# - How to use AutoMapper with PagedList? -

i'd use automapper in order map viewmodel domain model class. i'm using pagedlist nuget package. i'm using way: [authorize] [automap(typeof(errorslog), typeof(errorslogviewmodel))] public actionresult errors(string searchstring, string currentfilter, int? page) { if (searchstring != null) { page = 1; } else { searchstring = currentfilter; } var el = _er.geterrorslog(); viewbag.currentfilter = searchstring; if (!string.isnullorempty(searchstring)) { el = el.where(s => s.errorsource.contains(searchstring)); } const int pagesize = 3; int pagenumber = (page ?? 1); return view("errors", el.topagedlist(pagenumber, pagesize)); } unfortunately got error: missing type map configuration or unsupported mapping. mapping types: errorslog -> errorslogviewmodel digitalhubonlinestore.models.errorslog -> digitalhubonlinestore.viewmodels.errorslogviewmodel destination path: erro...

facebook - Symfony2 and PHP SDK 4.0 session issue while login -

i trying integrate facebook php-sdk 4 , symfony2 i installed facebook sdk using composer , using basic code facebook developer documentation generate facebook login url public function indexaction(request $request) { //generate facebooksession::setdefaultapplication('appid', 'secret'); $redirecturl = $this->generateurl('auth_facebookredirect'); $helper = new facebookredirectloginhelper($redirecturl); $helper->disablesessionstatuscheck(); $loginurl = $helper->getloginurl(); return $this->render('userbundle:fb:index.html.twig', array('loginurl'=>$loginurl)); } callback or facebook redirect after login success public function successaction(request $request) { facebooksession::setdefaultapplication('appid', 'secret'); $redirecturl = $this->generateurl('auth_facebookredirect'); $helper = new facebookredirectlog...

Swift ios is it possible to swipe between images using UIImageView -

first off, new swift / ios. in viewcontroller have uiimageview, in load in url form extrenal api in order show image. what want to able swipe between image(s), dont want pageviewcontroller. is possible uiimageview? if please share example / github library, alot. thanks in advance, no, can't swipe between images using image view. could, however, put image view inside view , swipe/pan slide between images. fair amount of work implement. you should not quick reject uipageviewcontroller . has slide style alternative page curl style. handles want beautifully. setting page view controller lot setting table view or collection view. do search in xcode system on "photoscroller". point demo app provides ui scrolling through series of images. handles tiling of large images it's more need, serves example of ui think after.

android - Dealing with Fragment and listView and JSON -

i trying make application menudrawer contains 4 fragments. how application show do. when starts, should retrieve data website. retrieved data should in listview in first fragment. second fragment should contain webview view page in android device. third show text details. application crashes when first fragment gets details website. here code : fragment layout following: my first fragment contains following: <listview android:layout_margintop="10dp" android:layout_below="@+id/txtlabel" android:layout_width="match_parent" android:layout_height="300dp" android:background = "@android:color/transparent" android:padding="3dp" android:dividerheight="1dp" android:id="@+id/mlv"></listview> the first fragment called when app starts. have list adapter , list model worked well. my main class contains inner class gets data. made model class , adapter class: ...

jquery - How to redirect the request to another controller after successful ajax request? -

here code $("#ajaxform").submit(function(e){ var info = $(this).serialize(); $.ajax( { url : "ctrl1", type: "post", data : info, success:function(data, textstatus, jqxhr) { $('.valid-error').html(data); if(data == "success"){ $.get("ctrl2", info); // request not come servlet } } }); e.preventdefault() }); $(".submit").click(function(){ $("#ajaxform").submit(); }); how redirect request controller after successful ajax request , data == "success"? have breakpoint in servlet's doget() , not called. code here not work tested it. how make request work? $("#ajaxform").submit(function(e){ var info = $(this).serialize(); ...

javascript - Stop Angular UI bootstrap dropdown from closing in certain cases? -

i have dropdown contains tabs , buttons. want able click tabs without dropdown closing if click button close. i used $event.stoppropagation() stop closing blocks buttons closing too. is there way this? by default dropdown automatically close if of elements clicked, can change behavior setting auto-close option follows: always - (default) automatically closes dropdown when of elements clicked. outsideclick - closes dropdown automatically when user clicks element outside dropdown. disabled - disables auto close. can control open/close status of dropdown manually, using is-open . please notice dropdown still close if toggle clicked, esc key pressed or dropdown open. here sample : plunker <div class="btn-group" dropdown auto-close="disabled"> <button type="button" class="btn btn-danger">action</button> <button type="button" class="btn btn-danger dropdown-toggle" dr...

excel - Can a VBA custom function knows that the formula is entered as an array formula? -

is possible make following function returns either multiple values or single value according how user enters formula? public function test(byval flnumber double) variant dim flresult1 double dim sresult2 string dim barrayformula boolean flresult1 = round(flnumber / 10 ^ 6, 1) sresult2 = "million" ' how know formula entered array formula? if barrayformula test = array(flresult1, sresult2) else test = flresult1 & " " & sresult2 end if end function just examine application.caller public function smartfunction() string addy = application.caller.address if range(addy).hasarray smartfunction = "array formula" else smartfunction = "normal formula" end if end function

linux - debian 8 iptables-persistent -

i have vps debian 8 jessie x64 stable release. after installation im trying configure iptables (like in debian 7). apt-get install iptables-persistent executed succesefully, packets installed. when im trying service iptables-persistent start im getting error says thar service iptables-persistent unrecognized halp! persist ip tables debian/ubuntu to persist changes make iptables rules, following. install iptables-persistent: sudo apt-get install -y iptables-persistent make changes want iptables rules, eg sudo iptables -t nat -a prerouting -p tcp --dport 80 -j redirect --to-ports 8080 then run sudo dpkg-reconfigure -y iptables-persistent the rules should persist after reboot now. extra info the dpkg-reconfigure causes iptables-persistent again @ install, save current iptables file using command like: iptables-save >/etc/iptables/rules.v4 ip6tables-save >/etc/iptables/rules.v6 the iptables-persistent package causes os run following on r...

How to bind Kendo grid to json data using angularjs -

hi using kendo grid bind data json , angularjs here code below. .cshtml page code below. <div ng-app="sample" ng-controller="samplecontroller"> <div>products: {{products.length}}</div> <div kendo-grid k-data-source="products" k-selectable="'row'" k-pageable='{ "pagesize": 2, "refresh": true, "pagesizes": true }' k-columns='[ { "field": "employeekey", "title": "employeeid"}, { "field": "firstname", "title": "first name"}, { "field": "lastname", "title": "last name"}, { "field": "departmentname", "title": "department name" }, { "field": "emailaddress", "title": "email id" } ]'> ...

How do I change the color of all text and backgrounds with javascript? -

i write script reduce eye strain, converts color of text on page , backgrounds each element. (i guess backgrounds become darker , text have become lighter). there simple javascript techniques making global changes elements on page? or have somehow cycle through every element , check text color , background color element (and how go if so)? realise there different options different levels of complexity, interesting have outline of various ways. since need check each element's color individually, there no global way of doing vanilla javascript. you still need select elements , check colors individually loop. while going through elements, need retrieve "computed" colors, , alter them according requirements: the snippet below alter contrast of elements, making background darker , text lighter, can adjusted via global variable contrastchange according needs. var pageelements = document.queryselectorall("*"); //define how change contr...

php - Magento export error 500 -

when try export 1200 product export > data profile > export tool, throws error 500. when same thing 1 group of products, works out fine. my server setup: log_errors on max_execution_time 36000 max_input_time 300 max_input_vars 10000 memory_limit 1024m it says should in error log, there no errors showing. running out oof things test here. broken product? app/code/core/mage/importexport/model/export/entity/product.php line: 873 $datarow += $stockitemrows[$productid]; in order update code to: $datarow = array_merge($datarow,$stockitemrows[$productid]);

swing - Java: TextField Doesn't Convert to Integer Variable i -

i doing work text field make program in user type in text field converts int problem when user type doesn't convert int i.the condition not work correctly why happening. public class extends jframe{ private jtextfield entervar; private jbutton button; public a(){ getcontentpane().setlayout(null); entervar = new jtextfield(); entervar.settooltiptext("variable must 'i'"); entervar.setbounds(37,26,89,28); getcontentpane().add(entervar); button = new jbutton("click"); button.addactionlistener(new actionlistener() { public void actionperformed(actionevent arg0) { string p = entervar.gettext(); try { int i; if ( p.equals("i") ) { = integer.parseint(p); } } catch (exception e) { joptionpane.sho...

PHP - sending email with attachment does not show message content -

trying create script can send email attachments. works except when don't add file in email can still see attachment 0b , no name. if(isset($_post["my_send"])){ $email_to = $_post['my_email_to']; //required $email_from = "myemail@example.co.uk"; // required $subject = $_post['my_subject']; // not required $comments = $_post['write_my_email']; // required $email_message .= stripcslashes("$comments"); $attachment = chunk_split(base64_encode(file_get_contents($_files['file']['tmp_name']))); $filename = $_files['file']['name']; // create email headers $headers = 'from: '.$email_from."\r\n". $headers .= "mime-version: 1.0\r\n"; $headers .= "content-type: multipart/mixed; boundary=\"_1_$boundary\"\r\n"; 'reply-to: '.$email_from."\r\n" . 'x-mailer: php/' . phpversion(); $message="th...

html - Checking function for sliding puzzle javascript -

i created sliding puzzle different formats like: 3x3, 3x4, 4x3 , 4x4. when run code can see on right side selection box can choose 4 formats. slidingpuzzle done. but need function checks after every move if puzzle solved , if case should give out line "congrantulations solved it!" or "you won!". idea how make work? in javascript code can see first function loadfunc() replace every piece blank 1 , functions after select format , change format it. function shiftpuzzlepieces makes can move each piece blank space. function shuffle randomizes every pieces position. if have more question or understanding issues feel free ask in comments. many in advance. since don't have enough reputation post link images here: http://imgur.com/a/2nmlt . these images placeholders right now. here jsfiddle: http://jsfiddle.net/cuttingtheaces/vkyxgwo6/19/ as always, there "hacky", easy way this, , there more elegant 1 requires significant changes code. ...

Connect to elasticsearch in google app engine through java transport client -

i want connect elasticsearch cluster in google appengine through java transportclient . appengine sandbox settings prevent me creating transportclient since employs thread pooling. there way enable thread pooling in app?

android - Fragment not showing in activity -

i have fragment own layout, , activity in fragment should added has layout: <?xml version="1.0" encoding="utf-8"?> <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" android:paddingbottom="@dimen/activity_vertical_margin"> <fragment android:name="com.myapp.myfragment" android:id="@+id/myfragment" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" tools:layout="@layout/myfragment_layout" /> </relativelayout...

ios - Is it possible to get a crash log due to expiration of provisioning profile? -

Image
when application doesn't start or goes home screen right after tapping application, have way know whether because of expiration of provisioning profile or other reason? i couldn't find them in crash logs finder. thanks. if app's provisioning profile has expired, see in device console. if have access device, plug mac , fire xcode. starting xcode 6, view console output of connected device: connect device. build , deploy app device using either cli or studio. sync application device using itunes (if not building directly device). launch xcode. open devices window. menu, select window > devices. select device left bar. click show device console button ( ) expand console. once have console up, click trash can clear it, on device try launch app. if provisioning profile app has expired, believe see message following: a valid provisioning profile executable not found

301 Redirect Regex Pattern - Sitecore Redirect module -

i apologize if seems rudimentary question, i'm trying setup redirect pattern 301 module in sitecore , having hard time proper pattern. i need have following path: http://www.example.com/some-path/videos/2014/08/08/15/20/some-item-title converted to: http://www.example.com/some-path/videos/some-item-title basically strip numerical folders out. how can preserve beginning of path , item name @ end. an https-safe version appreciated. thanks. edit : note, numerical folders in above format: there 4 digit folder, followed four, 2 digit folders. some-path/whatever/4444/22/22/22/22/item-name this fit "less global" requirement. var pattern = @"^(https?://[^/]*/some-path/videos/)\d{4}/\d{2}/\d{2}/\d{2}/\d{2}/(.*)$"; var match = regex.match(myurl, pattern, regexoptions.ignorecase); var rewrittenurl = string.empty; if (match.success) { rewrittenurl = match.groups[1].value + match.groups[2].value; } note chose ignore case. correct behavio...

mysql - What SQL privileges is it best to use to satisy requirements of most popular CMS -

what privileges better use satisfy requirements of popular content management systems? is safe say: grant privileges on sitex.* sitex@localhost or better use like: grant select, insert, update, delete, create, drop, references, index, alter, create temporary tables, lock tables, execute, create view, show view, create routine, alter routine on sitex.* sitex@localhost this depends on cms large extent (assuming mean content management system). keep in mind specific requirements may vary implementations. example things, delete may not want support. this being said, usually in common case, want support database operations on tables cms expects use. again, not case. need take individual instance requirements account.

java - Display Data from Database in ListView With Fragment -

i trying display data second column of database listview inside scrollview . i using fragment, i'm having problem using getsupportloadermanager().initloader(1, data, this); sais " getsupportloadermanager() undefined method", create new class inside fragment experiment, , result there no error when execute it, there's nothing happening ie. expected data not showing in listview. here layout: main.xml <?xml version="1.0" encoding="utf-8"?> <scrollview xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/main_body" android:layout_width="match_parent" android:layout_height="match_parent" android:fillviewport="true" android:background="@drawable/b"> <listview android:id="@+id/lv_countries_main" android:layout_width="match_parent" android:layout_height="wrap_content...

Python: How do i sort data in a text file? -

i trying write inside .txt file , sort in alphabetical order names inside, print. how this? if can't done there alternative? print("well done " + name + "! total score is: {}/10 :)\n".format(score)) #os.system("color 0a") time.sleep(3) file = open(str(age) + ".txt" , "a") # creates file.txt if hasn't been created , ammends 'a' file.write(name + " " + str(age) + " {}\n".format(score)) # writes file, .format(x) replaces {} variable x file.close f = open(str(age) + ".txt" , "r") lines = f.readlines() f.close() lines.sort() f = open(str(age) + ".txt" , "w") line in lines: f.write(line) print(lines) f.flush() f.close() i guessing input looks - a 10 1 b 10 2 c 10 8 d 10 5 making sure each name on separate line, not seem case code, since file.write() not automatically append \n end, have manually - file.write(name + " " + str(age) + ...

c# - Calling function on thread, trying to send command for invalid thread -

i have console application developed c#. console run threads. works fine today need call webbrowser , information page. faced errors , decided add part of code on thread.i put code in method named mybrowsercall. called : var t = new thread(mybrowsercall); t.setapartmentstate(apartmentstate.sta); t.start(); this function works fine , when want call function in method faced error: unhandled exception: system.systemexception: trying send command invalid thread do know how can fix ? i not fix issue change code. called functions has issue after webbrowser part. called getdata function cause problem after thread of webbrowser. working fine now.

SQL Server: Accessing transactional data in nested triggers -

i have following setup in ms sql server tablea id uniqueidentified status nvarchar ('unknown', 'inprogress', 'completed') other columns... tableb id uniqueidentified lastmodifieddate date other columns... tablea has update trigger changes lastmodifieddate on tableb every time there change in tablea tableb has trigger puts message ssb queue every time lastmodifieddate changed. question: how modify trigger tableb in such way fire when status of table completed. the challenge during modification of status in tablea trigger caused in tableb doesn’t have access latest value of tablea (e.g. completed) i not interested in: 1) adding column tableb modified triggera when status == complete 2) using global temp table. is there clever way this? (e.g. read "updated" value of triggera while in nested triggerb) due transactional nature of things update triggers. after update triggers indeed simplify whole scen...

How can I have different color for each bar of stack barplots? in R -

Image
my question maybe simple couldn't find answer! have matrix 12 entries , made stack barplot barplot function in r. code: mydata <- matrix(nrow=2,ncol=6, rbind(sample(1:12, replace=t))) barplot(mydata, xlim=c(0,25),horiz=t, legend.text = c("a","b","c","d","e","f"), col=c("blue","green"),axisnames = t, main="stack barplot") here image code: what want give each of group (a:f , blue part) different color couldn't add more 2 color. and know how can start plot x=2 instead of 0. know it's possible choose range of x using xlim=c(2,25) when choose part of bars out of range , picture this: what want ignore part of bars smaller 2 , start x-axis 2 , show rest of bars instead of put them out of range. thank in advance, i'm not entirely sure if you're looking for: 'a' has 2 values (x1 , x2), legend seems hint otherwise. here way appro...

html - Background image not show fully on mobile's -

body background image not showing on mobile height wise. show on half of body. image size (1600*1050) here css code body { background:url('img/dot.png') repeat, url('img/bg2.jpg') center fixed no-repeat; background-size:auto, cover; min-width:100%; height:100%; margin: 0; } kindly advice me solution. set background height , width 100% background-size: 100% 100%;

Are functions passed as parameters always callbacks? JavaScript -

if have code below, pass 2 functions parameters function sayhi , example of callback? i notice there 2 ways of running these 'parameter functions': either below, call functions defined (as arguments), or alternatively call parameter in sayhi function. difference between callback , anonymous function? function sayhi(name, testfortrue) { if (testfortrue == true) { console.log(name); } } sayhi(function() { return 'zach' }(), function() { return true; }()); another way same result, below. in case evaluating functions @ different time? there practical difference between two? function sayhi(name, testfortrue) { if (testfortrue() == true) { console.log(name()); } } sayhi(function() { return 'zach' }, function() { return true; }); yes, functions passed parameters callbacks, if intention function called synchronously (c.f. array.prototype.map ) rather asynchronously (c.f. window.settimeout ). in f...

c - why does a integer type need to be little-endian? -

i curious little-endian , know computers have little-endian method. so, praticed through program , source below. int main(){ int flag = 31337; char c[10] = "abcde"; int flag2 = 31337; return 0; } when saw stack via gdb, i noticed there 0x00007a69 0x00007a69 .... ... ... .. .... ... 0x62610000 0x00656463 .. ... so, have 2 questions. for 1 thing, how can value of char c[10] under flag? i expected there value of flag2 in top of stack , value of char c[10] under flag2 , value of flag under char c[10]. like this 7a69 "abcde" 7a69 second, i expected value stored in way of little-endian. as result, value of "abcde" stored '6564636261' however, value of 31337 wasn't stored via little-endian. it '7a69'. thought should '697a' why doesn't integer type conform little-endian? there confusion in understanding of endianness, stack , compilers. first, locations of variables in stack may no...

python - Heroku+Django+Postgres error: "FATAL: database "python_getting_started" does not exist" -

i'm trying getting started python exercise @ heroku ( https://devcenter.heroku.com/articles/getting-started-with-python#introduction ). i'm following instructions , using git repo provided in tutorial. when go /db page of web app, uses database functionality, error trace: environment: request method: request url: http://localhost:5000/db django version: 1.8.1 python version: 2.7.5 installed applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hello') installed middleware: ('django.contrib.sessions.middleware.sessionmiddleware', 'django.middleware.common.commonmiddleware', 'django.middleware.csrf.csrfviewmiddleware', 'django.contrib.auth.middleware.authenticationmiddleware', 'django.contrib.auth.middleware.sessionauthenticationmiddleware', ...

How can i print and return a value from a function in python? -

i cant figure out how make return value function return , print, example def exe(a,b): if == b: return 1 how 1 print return? in advance. know stupid question , pretty useless, im pretty sure can done , not knowing how driving me nuts. you can have multiple statements, "return" ends function. print statement when combined expressions (the stuff right of it) (in python 2) sends expressions standard out, (stdout), typically console. in python 3, print function, , it's preferable use print function in modern python. so want print come before return. def exe(a,b): if == b: print(1) return 1

android with viewpager When i click on Button in the first fragment I want the app to navigate to another activity -

i have 2 fragments implemented using view pager. in fragment 1 have 2 button , in fragment 2 have list of item. when click on particular button in first fragment want app navigate activity. but scenario when click on particular button in first fragment it's click on second fragment list item , open list item detail. if knows, please suggest me solution. need possible. thanks one thing came on top of head this: store fragments in viewpager. listen button click events in first fragment. from first fragment, notify activity of said click event. your activity (which houses viewpager) should respond click event commanding viewpager move second page (which contains second fragment). can calling yourviewpager.setcurrentitem() . and there have it. fragment contains button move pager onto next page/fragment.