Search Results

Search found 19539 results on 782 pages for 'pretty print'.

Page 84/782 | < Previous Page | 80 81 82 83 84 85 86 87 88 89 90 91  | Next Page >

  • Saving a single entity instead of the entire context - revisited

    - by nite
    I’m looking for a way to have fine grained control over what is saved using Entity Framework, rather than the whole ObjectContext.SaveChanges(). My scenario is pretty straight forward, and I’m quite amazed not catered for in EF – pretty basic in NHibernate and all other data access paradigms I’ve seen. I’m generating a bunch of data (in a WPF UI) and allowing the user to fine tune what is proposed and choose what is actually committed to the database. For the proposed entities I’m: getting a bunch of reference entities (eg languages) via my objectcontext, creating the proposed entities and assigning these reference entities to them (as navigation properties), so by virtue of their relationship to the reference entities they’re implicitly added to the objectconext Trying to create & save individual entites based on the proposed entities. I figure this should be really simple & trivial but everything I’ve tried I’ve hit a brick wall, either I set up another objectcontext & add just the entity I need (it then tries to add the whole graph and fails as it’s on another objectcontext). I’ve tried MergeOptions = NoTracking on my reference entities to try to get the Attach/AddObject not to navigate through these to create a graph, no avail. I've removed the navigation properties from the reference entities. I've tried AcceptAllChanges, that works but pretty useless in practice as I do still want to track & save other entities. In a simple test, I can create 2 of my proposed entities, AddObject the one I want to save and then Detach the one I dont then call SaveChanges, this works but again not great in practice. Following are a few links to some of the nifty ideas which in the end don’t help in the end but illustrate the complexity of EF for something so simple. I’m really looking for a SaveSingle/SaveAtomic method, and think it’s a pretty reasonable & basic ask for any DAL, letalone a cutting edge ORM. http://stackoverflow.com/questions/1301460/saving-a-single-entity-instead-of-the-entire-context www.codeproject.com/KB/architecture/attachobjectgraph.aspx?fid=1534536&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=3071122&fr=1 bernhardelbl.spaces.live.com/blog/cns!DB54AE2C5D84DB78!238.entry

    Read the article

  • PHP what is faster to use

    - by user1631500
    What is faster / better to use? To put html into variables and print them later, or to just html print / echo print the content based on condition? EXAMPLE 1:(html into variables) if(!isset($_SESSION['daddy'])) { $var = "<span class='something'>Go here:<a href='#'>Click</a></span> <span class='something'>Go here:<a href='#'>Click</a></span>" } else { $one=$_SESSION["one"]; $two=$_SESSION["two"]; $three=$_SESSION["three"]; $var = You are cool enough to view the content; } echo $var; EXAMPLE 2:(print based on condition) if(!isset($_SESSION['daddy'])) { $var = 1; } else { $one=$_SESSION["one"]; $two=$_SESSION["two"]; $three=$_SESSION["three"]; $var = 0; } if ($var==1) { ?> <span class='something'>Go here:<a href='#'>Click</a></span> <span class='something'>Go here:<a href='#'>Click</a></span <?php } else { ?> You are cool enough to view the content. <?php } ?>

    Read the article

  • Printing in Silverlight 4

    - by Number8
    Hello, We have an application structured roughly like this: <Grid x:Name="LayoutRoot"> <ScrollViewer> <Canvas x:Name="canvas"> <StackPanel> < Button /><Slider /><Button /></StackPanel> <custom:Blob /> <custom:Blob /> <custom:Blob /> </Canvas> </ScrollViewer> </Grid> Each Blob consists of 1 or more rectangles, lines, and text boxes; they are positioned anywhere on the canvas. If I print the document using the LayoutRoot: PrintDocument pd = new PrintDocument(); pd += (s, pe) => { pe.PageVisual = LayoutRoot; }; pd.Print("Blobs"); ... it is like a print-screen -- the scrollbars, the sliders, the blobs that are visible -- are printed. If I set PageVisual = canvas, nothing is printed. How can I get all the blob objects, and just those objects, to print? Do I need to copy them into another container, and give that container to PageVisual? Can I use a ViewBox to make sure they all fit on one page? Thanks for any pointers....

    Read the article

  • Loop elements with Jquery and call Omniture s.tl() function to track

    - by ilovewebdev
    Hi, i have a page with a list of items. Each item has a print now link (a.printMe) to print each item. At the end of the list, there's a print all link (a.printAll) to print all items. I want to track number of times an item was printed. If a.printAll link is clicked, then i will send all the item's tracking value to Omniture. I added tracking string into individual item's a.printMe href attribute and track with the following functions: $('a.printMe').click(function() { var value = $(this).attr('href'); track(value); }); $('a.printAll').click(function() { $('a.printMe').each(function() { this.click(); }); // works in IE only. IE 6-8 }); function track(value) { var s = s_gi('account'); s.prop10 = value; s.linkTrackVars = 'prop10'; s.tl(true, 'o'); } The problem is only the last item (in the list) has its value sent to Omniture when i clicked on a.printAll. I finally got the above to work in IE but not Firefox. Anyone encounter this before?

    Read the article

  • Capturing stdout from an imported module in wxpython and sending it to a textctrl, without blocking the GUI

    - by splafe
    There are alot of very similar questions to this but I can't find one that applies specifically to what I'm trying to do. I have a simulation (written in SimPy) that I'm writing a GUI for, the main output of the simulation is text - to the console from 'print' statements. Now, I thought the simplest way would be to create a seperate module GUI.py, and import my simulation program into it: import osi_model I want all the print statements to be captured by the GUI and appear inside a Textctrl, which there's countless examples of on here, along these lines: class MyFrame(wx.Frame): def __init__(self, *args, **kwds): <general frame initialisation stuff..> redir=RedirectText(self.txtCtrl_1) sys.stdout=redir class RedirectText: def __init__(self,aWxTextCtrl): self.out=aWxTextCtrl def write(self,string): self.out.WriteText(string) I am also starting my simulation from a 'Go' button: def go_btn_click(self, event): print 'GO' self.RT = threading.Thread(target=osi_model.RunThis()) self.RT.start() This all works fine, and the output from the simulation module is captured by the TextCtrl, except the GUI locks up and becomes unresponsive - I still need it to be accessible (at the very minimum to have a 'Stop' button). I'm not sure if this is a botched attempt at creating a new thread that I've done here, but I assume a new thread will be needed at some stage in this process. People suggest using wx.CallAfter, but I'm not sure how to go about this considering the imported module doesn't know about wx, and also I can't realistically go through the entire simulation architecture and change all the print statements to wx.CallAfter, and any attempt to capture the shell from inside the imported simulation program leads to the program crashing. Does anybody have any ideas about how I can best achieve this? So all I really need is for all console text to be captured by a TextCtrl while the GUI remains responsive, and all text is solely coming from an imported module. (Also, secondary question regarding a Stop button - is it bad form to just kill the simulation thread?). Thanks, Duncan

    Read the article

  • getting another website data to manipulate it's value in perl

    - by aun ali
    use CGI qw(:standard); use CGI::Carp qw(fatalsToBrowser warningsToBrowser); our @a=param(src="http://fxrates.forexpros.com/index.php?pairs_ids=1525=last_update"); print header(),start_html('results.pl'); $a=http://fxrates.forexpros.com/index.php?pairs_ids=1525=last_update; '<iframe frameborder="0" scrolling="no" height="95" width="213" allowtransparency="true" marginwidth="0" marginheight="0" src="http://fxrates.forexpros.com/index.php?pairs_ids=1525;&header-text-color=%23FFFFFF&curr-name-color=%230059b0&inner-text-color=%23000000&green-text-color=%232A8215&green-background=%23B7F4C2&red-text-color=%23DC0001&red-background=%23FFE2E2&inner-border-color=%23CBCBCB&border-color=%23cbcbcb&bg1=%23F6F6F6&bg2=%23ffffff&bid=hide&ask=hide&last=hide&high=hide&low=hide&change=hide&change_in_percents=hide&last_update=show"></iframe><br /><div style="width:213"><span style="float:left"><span style="font-size: 11px;color: #333333;text-decoration: none;">The <a href="http://www.forexpros.com/quotes" target="_blank" style="font-size: 11px;color: #06529D; font-weight: bold;" class="underline_link">Forex Quotes</a> are Powered by Forexpros - The Leading Financial Portal.</span></span></div>'; print '<br/>'; print "$a"; print end_html();' getting error: Can't modify constant item in scalar assignment at livedata.pl line 4, near ""http://fxrates.forexpros.com/index.php?pairs_ids=1525=last_update")" syntax error at livedata.pl line 6, near "http:" Execution of livedata.pl aborted due to compilation errors.

    Read the article

  • How to insert and call by row and column into sqlite3 python, great tutorial problem.

    - by user291071
    Lets say i have a simple array of x rows and y columns with corresponding values, What is the best method to do 3 things? How to insert, update a value at a specific row column? How to select a value for each row and column, import sqlite3 con = sqlite3.connect('simple.db') c = con.cursor() c.execute('''create table simple (links text)''') con.commit() dic = {'x1':{'y1':1.0,'y2':0.0},'x2':{'y1':0.0,'y2':2.0,'y3':1.5},'x3':{'y2':2.0,'y3':1.5}} ucols = {} ## my current thoughts are collect all row values and all column values from dic and populate table row and columns accordingly how to call by row and column i havn't figured out yet ##populate rows in first column for row in dic: print row c.execute("""insert into simple ('links') values ('%s')"""%row) con.commit() ##unique columns for row in dic: print row for col in dic[row]: print col ucols[col]=dic[row][col] ##populate columns for col in ucols: print col c.execute("alter table simple add column '%s' 'float'" % col) con.commit() #functions needed ##insert values into sql by row x and column y?how to do this e.g. x1 and y2 should put in 0.0 ##I tried as follows didn't work for row in dic: for col in dic[row]: val =dic[row][col] c.execute("""update simple SET '%s' = '%f' WHERE 'links'='%s'"""%(col,val,row)) con.commit() ##update value at a specific row x and column y? ## select a value at a specific row x and column y?

    Read the article

  • Android 2.1 How to get Phone Numbers of contacts.

    - by Brandon Delany
    Hi, I am new to Android and have been working on an app that needs to get all of the user's contact's phone numbers. Apparently the code I have does not work with the 2.1 SDK. So far here is the code I am using: String[] projection = new String[] { Phone.NUMBER }; Cursor c = managedQuery( Phone.CONTENT_URI, projection, null, null, null ); int colIndex = -1; try { colIndex = c.getColumnIndexOrThrow( Phone.NUMBER ); } catch( Exception e ) { print( e.getMessage() ); } print( "Column Index = " + colIndex ); //count is equal to 3 for( int i = 0; i < count; i++ ){ try { print( c.getString( 2 ) ); //the 2 used to be colIndex } catch ( Exception e ) { print( e.getMessage() ); } } It seems that no matter what I pass into c.getString() it keeps telling me that I passed in -1. But I even hardcoded the 2, and it says the same thing. Any help would be much appreciated.

    Read the article

  • Java Recursion Triangle Standing on Tip

    - by user1629075
    I was wondering how to create triangle out of asterisks on its tip rather than on its base. I have the code for making it stand on its base: public static String printTriangle (int count) { if( count <= 0 ) return ""; String p = printTriangle(count - 1); p = p + "*"; System.out.print(p); System.out.print("\n"); return p; } But then I'm stuck on how to have the greatest number of stars on the top, and then the next least, and so on. I was thinking something along the terms of having (count - p) to have the input of rows be subtracted from the amount of decrease, but then i was confused by this idea because p is string. EDIT: I tried changing the position of printTriangle(count - 1) using my original method without iterations and got 1 star per each line; how can I fix this? public class triangles { public static void main(String[] args) { printTriangle(5); } public static String printTriangle (int count) { if( count <= 0 ) return ""; String p = ""; p = p + "*"; System.out.print(p); System.out.print("\n"); p = printTriangle(count - 1); return p; } }

    Read the article

  • Why is my Perl script that calls FTP all of a sudden failing?

    - by Mel
    I have a script that has been running for over a year and now it is failing: It is creating a command file: open ( FTPFILE, ">get_list"); print FTPFILE "dir *.txt"\n"; print FTPFILE "quit\n"; close FTPFILE; Then I run the system command: $command = "ftp ".$Server." < get_list | grep \"\^-\" >new_list"; $code = system($command); The logic the checks: if ($code == 0) { do stuff } else { log error } It is logging an error. When I print the $code variable, I am getting 256. I used this command to parse the $? variable: $exit_value = $? >> 8; $signal_num = $? & 127; $dumped_core = $? & 128; print "Exit: $exit_value Sig: $signal_num Core: $dumped_core\n"; Results: Exit: 1 Sig: 0 Core: 0 Thanks for any help/insight.

    Read the article

  • Java: over-typed structures?

    - by HH
    Term over-type structure = a data structure that accepts different types, can be primitive or user-defined. I think ruby supports many types in structures such as tables. I tried a table with types 'String', 'char' and 'File' in Java but errs. How can I have over-typed structure in Java? How to show types in declaration? What about in initilization? Suppose a structure: INDEX VAR FILETYPE //0 -> file FILE //1 -> lineMap SizeSequence //2 -> type char //3 -> binary boolean //4 -> name String //5 -> path String Code import java.io.*; import java.util.*; public class Object { public static void print(char a) { System.out.println(a); } public static void print(String s) { System.out.println(s); } public static void main(String[] args) { Object[] d = new Object[6]; d[0] = new File("."); d[2] = 'T'; d[4] = "."; print(d[2]); print(d[4]); } } Errors Object.java:18: incompatible types found : java.io.File required: Object d[0] = new File("."); ^ Object.java:19: incompatible types found : char required: Object d[2] = 'T'; ^

    Read the article

  • How can I override list methods to do vector addition and subtraction in python?

    - by Bobble
    I originally implemented this as a wrapper class around a list, but I was annoyed by the number of operator() methods I needed to provide, so I had a go at simply subclassing list. This is my test code: class CleverList(list): def __add__(self, other): copy = self[:] for i in range(len(self)): copy[i] += other[i] return copy def __sub__(self, other): copy = self[:] for i in range(len(self)): copy[i] -= other[i] return copy def __iadd__(self, other): for i in range(len(self)): self[i] += other[i] return self def __isub__(self, other): for i in range(len(self)): self[i] -= other[i] return self a = CleverList([0, 1]) b = CleverList([3, 4]) print('CleverList does vector arith: a, b, a+b, a-b = ', a, b, a+b, a-b) c = a[:] print('clone test: e = a[:]: a, e = ', a, c) c += a print('OOPS: augmented addition: c += a: a, c = ', a, c) c -= b print('OOPS: augmented subtraction: c -= b: b, c, a = ', b, c, a) Normal addition and subtraction work in the expected manner, but there are problems with the augmented addition and subtraction. Here is the output: >>> CleverList does vector arith: a, b, a+b, a-b = [0, 1] [3, 4] [3, 5] [-3, -3] clone test: e = a[:]: a, e = [0, 1] [0, 1] OOPS: augmented addition: c += a: a, c = [0, 1] [0, 1, 0, 1] Traceback (most recent call last): File "/home/bob/Documents/Python/listTest.py", line 35, in <module> c -= b TypeError: unsupported operand type(s) for -=: 'list' and 'CleverList' >>> Is there a neat and simple way to get augmented operators working in this example?

    Read the article

  • Cant fetch production db results using Google app engine remote_api

    - by Alon
    Hey, im trying to work out with /remote_api with a django-patch app engine app i got running. i want to select a few rows from my online production app locally. i cant seem to manage todo so, everything authenticates fine, it doesnt breaks on imports, but when i try to fetch something it just doesnt print anything. Placed the test python inside my local app dir. #!/usr/bin/env python # import os import sys # Hardwire in appengine modules to PYTHONPATH # or use wrapper to do it more elegantly appengine_dirs = ['myworkingpath'] sys.path.extend(appengine_dirs) # Add your models to path my_root_dir = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, my_root_dir) from google.appengine.ext import db from google.appengine.ext.remote_api import remote_api_stub import getpass APP_NAME = 'Myappname' os.environ['AUTH_DOMAIN'] = 'gmail.com' os.environ['USER_EMAIL'] = '[email protected]' def auth_func(): return (raw_input('Username:'), getpass.getpass('Password:')) # Use local dev server by passing in as parameter: # servername='localhost:8080' # Otherwise, remote_api assumes you are targeting APP_NAME.appspot.com remote_api_stub.ConfigureRemoteDatastore(APP_NAME, '/remote_api', auth_func) # Do stuff like your code was running on App Engine from channel.models import Channel, Channel2Operator myresults = mymodel.all().fetch(10) for result in myresults: print result.key() it doesnt give any error or print anything. so does the remote_api console example google got. when i print the myresults i get [].

    Read the article

  • perl system command return code

    - by Mel
    I have a script that has been running for over a year and now it is failing: It is creating a command file: open ( FTPFILE, ">get_list"); print FTPFILE "dir *.txt"\n"; print FTPFILE "quit\n"; close FTPFILE; Then I run the system command: $command = "ftp ".$Server." < get_list | grep \"\^-\" >new_list"; $code = system($command); The logic the checks: if ($code == 0) { do stuff } else { log error } It is logging an error. When I print the $code variable, I am getting 256. I used this command to parse the $? variable: $exit_value = $? >> 8; $signal_num = $? & 127; $dumped_core = $? & 128; print "Exit: $exit_value Sig: $signal_num Core: $dumped_core\n"; Results: Exit: 1 Sig: 0 Core: 0 Thanks for any help/insight.

    Read the article

  • In Python, how to make sure database connection will always close before leaving a code block?

    - by Cawas
    I want to prevent database connection being open as much as possible, because this code will run on an intensive used server and people here already told me database connections should always be closed as soon as possible. def do_something_that_needs_database (): dbConnection = MySQLdb.connect(host=args['database_host'], user=args['database_user'], passwd=args['database_pass'], db=args['database_tabl'], cursorclass=MySQLdb.cursors.DictCursor) dbCursor = dbConnection.cursor() dbCursor.execute('SELECT COUNT(*) total FROM table') row = dbCursor.fetchone() if row['total'] == 0: print 'error: table have no records' dbCursor.execute('UPDATE table SET field="%s"', whatever_value) return None print 'table is ok' dbCursor.execute('UPDATE table SET field="%s"', another_value) # a lot more of workflow done here dbConnection.close() # even more stuff would come below I believe that leaves a database connection open when there is no row on the table, tho I'm still really not sure how it works. Anyway, maybe that is bad design in the sense that I could open and close a DB connection after each small block of execute. And sure, I could just add a close right before the return in that case... But how could I always properly close the DB without having to worry if I have that return, or a raise, or continue, or whatever in the middle? I'm thinking in something like a code block, similar to using try, like in the following suggestion, which obviously doesn't work: def do_something_that_needs_database (): dbConnection = MySQLdb.connect(host=args['database_host'], user=args['database_user'], passwd=args['database_pass'], db=args['database_tabl'], cursorclass=MySQLdb.cursors.DictCursor) try: dbCursor = dbConnection.cursor() dbCursor.execute('SELECT COUNT(*) total FROM table') row = dbCursor.fetchone() if row['total'] == 0: print 'error: table have no records' dbCursor.execute('UPDATE table SET field="%s"', whatever_value) return None print 'table is ok' dbCursor.execute('UPDATE table SET field="%s"', another_value) # again, that same lot of line codes done here except ExitingCodeBlock: closeDb(dbConnection) # still, that "even more stuff" from before would come below I don't think there is anything similar to ExitingCodeBlock for an exception, tho I know there is the try else, but I hope Python already have a similar feature... Or maybe someone can suggest me a paradigm move and tell me this is awful and highly advise me to never do that. Maybe this is just something to not worry about and let MySQLdb handle it, or is it?

    Read the article

  • Django ModelForm Imagefield Upload

    - by Wei Xu
    I am pretty new to Django and I met a problem in handling image upload using ModelForm. My model is as following: class Project(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=2000) startDate = models.DateField(auto_now_add=True) photo = models.ImageField(upload_to="projectimg/", null=True, blank=True) And the modelform is as following: class AddProjectForm(ModelForm): class Meta: model = Project widgets = { 'description': Textarea(attrs={'cols': 80, 'rows': 50}), } fields = ['name', 'description', 'photo'] And the View function is: def addProject(request, template_name): if request.method == 'POST': addprojectform = AddProjectForm(request.POST,request.FILES) print addprojectform if addprojectform.is_valid(): newproject = addprojectform.save(commit=False) print newproject print request.FILES newproject.photo = request.FILES['photo'] newproject.save() print newproject.photo else: addprojectform = AddProjectForm() newProposalNum = projectProposal.objects.filter(solved=False).count() return render(request, template_name, {'addprojectform':addprojectform, 'newProposalNum':newProposalNum}) the template is: <form class="bs-example form-horizontal" method="post" action="">{% csrf_token %} <h2>Project Name</h2><br> {{ addprojectform.name }}<br> <h2>Project Description</h2> {{ addprojectform.description }}<br> <h2>Image Upload</h2><br> {{ addprojectform.photo }}<br> <input type="submit" class="btn btn-success" value="Add Project"> </form> Can anyone help me or could you give an example of image uploading? Thank you!

    Read the article

  • Rollback doesn't work in MySQLdb

    - by Anton Barycheuski
    I have next code ... db = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db, charset='utf8', use_unicode=True) db.autocommit(False) cursor = db.cursor() ... for col in ws.columns[1:]: data = (col[NUM_ROW_GENERATION].value, 1, type_topliv_dict[col[NUM_ROW_FUEL].value]) fullgeneration_id = data[0] type_topliv = data[2] if data in completions_set: compl_id = completions_dict[data] else: ... sql = u"INSERT INTO completions (type, mark, model, car_id, type_topliv, fullgeneration_id, mark_id, model_id, production_period, year_from, year_to, production_period_url) VALUES (1, '%s', '%s', 0, %s, %s, %s, %s, '%s', '%s', '%s', '%s')" % (marks_dict[mark_id], models_dict[model_id], type_topliv, fullgeneration_id, mark_id, model_id, production_period, year_from, year_to, production_period.replace(' ', '_').replace(u'?.?.', 'nv') ) inserted_completion += cursor.execute(sql) cursor.execute("SELECT fullgeneration_id, type, type_topliv, id FROM completions where fullgeneration_id = %s AND type_topliv = %s" % (fullgeneration_id, type_topliv)) row = cursor.fetchone() compl_id = row[3] if is_first_car: deleted_compl_rus = cursor.execute("delete from compl_rus where compl_id = %s" % compl_id) for param, row_id in params: sql = u"INSERT INTO compl_rus (compl_id, modification, groupparam, param, paramvalue) VALUES (%s, '%s', '%s', '%s', %s)" % (compl_id, col[NUM_ROW_MODIFICATION].value, param[0], param[1], col[row_id].value) inserted_compl_rus += cursor.execute(sql) is_first_car = False db.rollback() print '\nSTATISTICS:' print 'Inserted completion:', inserted_completion print 'Inserted compl_rus:', inserted_compl_rus print 'Deleted compl_rus:', deleted_compl_rus ans = raw_input('Commit changes? (y/n)') db.close() I has manually deleted records from table and than run script two times. See https://dpaste.de/MwMa . I think, that rollback in my code doesn't work. Why?

    Read the article

  • Tkinter, Python: How do I save text entered in the Entry widget? How do I move a label?

    - by user3692825
    I am a newbie at programming and my program is not stellar but hopefully it's ok because I have only been using it for a couple days now. I am having trouble in my class "Recipie". In this class I am having trouble saving the text in my Entry widget. I know to use the .get() option but when I try to print it, it doesn't (whether it is within that defined method or not). So that is my main concern. I want it to save the text entered as a string when I press the button: b. My other minor question is, how can I move the label. When I have tried I have used the height and width options, but that just expands the label. I want to move the text to create a title above my Entry boxes. Is label the right widget to use or would it be easier to use a message box widget? So it would look like, for example (but like 8 pixels down and 20 to the right): ingredients textbox button labeled as: add an ingredient And I am not sure the option .pack(side="...") or .place(anchor="...") are the right options to use for my buttons or entry boxes or labels. Any help is greatly appreciated!!! And if you could add comments to your code explaining what you did, that would be so helpful. Thank you!!! import Tkinter class Recipie(Tkinter.Tk): def __init__(self): Tkinter.Tk.__init__(self) self.title("New Recipie") self.geometry("500x500") def name(self): name = Tkinter.Label(self, text="Title:", width=39) name.place(anchor="nw") insert_name = Tkinter.Entry(self) insert_name.pack() insert_name.focus_set() def ingredients(self): e = Tkinter.Entry(self) e.pack() e.focus_set() def addingredient(self): but = Tkinter.Button(self, text="Add Ingredients", width=15, command=self.ingredients) but.pack(side="bottom") def procedure(self): txt = Tkinter.Label(self, text="List the Steps:") txt.place(anchor="n") p = Tkinter.Entry(self) p.place(anchor="nw") p.focus_set() def savebutton(self): print insert_name.get() print e.get() print p.get() b = Tkinter.Button(self, text="Save Recipie", width=15, command=savebutton) top = Recipie() top.mainloop()

    Read the article

  • Full and Partial Matching of Sets

    - by jeffrey
    I have several sets of the same type [Y, M, D] and am trying to write a function to search these sets and return an array of the available sets that fit my parameters. ReturnedSets = return_matches(Y,M,D); I want the three parameters of the function return_matches to be optional. Which means any combination of values can be used to return the sets. For example, one could write - return_matches(13,null,2); - and the function would look for all sets that contain [13, anyValue, 2]; I'm writing this in PHP, to allow users to manage dated files on my website, but I'd like to be able to use this function again for other uses. Thanks! edit: (This, or variations of this, is all I can come up with so far... There is something extra that I don't understand, because this function ends up / would not work to return sets that contain y and d, but leaving m arbitrary. if(y == s[0]){ if(m == s[1]){ if(d == s[2]){ print "day match"; } } else {print "month match";} } else {print "year match";} } else {print "no match";}

    Read the article

  • how to delete a line from file using awk filtered by some string

    - by embedded
    I have a file delimited by space. I need to write an awk command that receives a host name argument and it should replace the host name if it already defined in the file. It must be a full match not partially - if the file contains this host name: localhost searching for "ho" will fail and it will be added to the end of the file. another option is a delete: again awk receives host name argument and it should remove it from the file if exists. This is what I have so far: (It needs some enhancements) if [ "$DELETE_FLAG" == "" ]; then # In this case the entry should be added or updated # if clause deals with updating an existing entry # END clause deals with adding a new entry awk -F"[ ]" "BEGIN { found = 0;} \ { \ if ($2 == $HOST_NAME) { \ print \"$IP_ADDRESS $HOST_NAME\"; \ found = 1; \ } else { \ print \$0; \ } \ } \ END { \ if (found == 0) { \ print \"$IP_ADDRESS $HOST_NAME\"; } \ } " \ /etc/hosts > /etc/temp_hosts else # Delete an existing entry awk -F'[ ]' '{if($2 != $HOST_NAME) { print $0} }' /etc/hosts > /etc/temp_hosts fi Thanks

    Read the article

  • Python: Behavior of object in set operations

    - by Josh Arenberg
    I'm trying to create a custom object that behaves properly in set operations. I've generally got it working, but I want to make sure I fully understand the implications. In particular, I'm interested in the behavior when there is additional data in the object that is not included in the equal / hash methods. It seems that in the 'intersection' operation, it returns the set of objects that are being compared to, where the 'union' operations returns the set of objects that are being compared. To illustrate: class MyObject: def __init__(self,value,meta): self.value = value self.meta = meta def __eq__(self,other): if self.value == other.value: return True else: return False def __hash__(self): return hash(self.value) a = MyObject('1','left') b = MyObject('1','right') c = MyObject('2','left') d = MyObject('2','right') e = MyObject('3','left') print a == b # True print a == c # False for i in set([a,c,e]).intersection(set([b,d])): print "%s %s" % (i.value,i.meta) #returns: #1 right #2 right for i in set([a,c,e]).union(set([b,d])): print "%s %s" % (i.value,i.meta) #returns: #1 left #3 left #2 left Is this behavior documented somewhere and deterministic? If so, what is the governing principle?

    Read the article

  • zipping file problem on the server PHP

    - by Ahmet vardar
    Hi, here is my code; error_reporting(-1); require("zip_min.php"); $f = $_SERVER['DOCUMENT_ROOT'] ."/mp3/allmp3s.zip"; if (!file_exists($f)) { $zipfile = new zipfile(); $folder = $_SERVER['DOCUMENT_ROOT'] ."/mp3; if (is_dir($folder)) { if($dir = opendir ($folder)) { while (false !== ($file = readdir($dir))) { if($file != ".") { if($file != "..") { $zipfile -> addFile(file_get_contents($folder."/".$file), $file); } } } closedir($dir); $contents = $zipfile -> file(); if (file_put_contents($f, $contents)) { print "ok"; } else { print "error creating file"; } } } else { print "error"; } } else { print "file already exists"; } there are 10 mp3 files total size of 100 mb, when i execute this script, i got just a blank page, nothing happens. but with 30-40 mb of size it works great. what should i do ? thanks so much

    Read the article

  • Help with HTTP Intercepting Proxy in Ruby?

    - by Philip
    I have the beginnings of an HTTP Intercepting Proxy written in Ruby: require 'socket' # Get sockets from stdlib server = TCPServer.open(8080) # Socket to listen on port 8080 loop { # Servers run forever Thread.start(server.accept) do |client| puts "** Got connection!" @output = "" @host = "" @port = 80 while line = client.gets line.chomp! if (line =~ /^(GET|CONNECT) .*(\.com|\.net):(.*) (HTTP\/1.1|HTTP\/1.0)$/) @port = $3 elsif (line =~ /^Host: (.*)$/ && @host == "") @host = $1 end print line + "\n" @output += line + "\n" # This *may* cause problems with not getting full requests, # but without this, the loop never returns. break if line == "" end if (@host != "") puts "** Got host! (#{@host}:#{@port})" out = TCPSocket.open(@host, @port) puts "** Got destination!" out.print(@output) while line = out.gets line.chomp! if (line =~ /^<proxyinfo>.*<\/proxyinfo>$/) # Logic is done here. end print line + "\n" client.print(line + "\n") end out.close end client.close end } This simple proxy that I made parses the destination out of the HTTP request, then reads the HTTP response and performs logic based on special HTML tags. The proxy works for the most part, but seems to have trouble dealing with binary data and HTTPS connections. How can I fix these problems?

    Read the article

  • PHP include taking too long

    - by wxiiir
    I have a php file with around 100mb which is full of arrays (only arrays). I've made a script that includes this file (for processing), first it exhausted the default Xampp 128mb memory limit, i've raised it to 1024mb but it just takes forever and doesn't do anything. I'm sure the problem is being created by the sheer size of the file because i've tried removing all lines of code and just leaving the include and an echo for me to know when it finishes executing, and it does the same thing (which is taking forever), i've also tried to run the 100mb file in separate and same thing again. A 10mb file is taking forever as well but a similar 1mb file is almost instantly read and executed so the problem must be more than just the file size. I was avoiding using c++ for a simple project as this and would rather not to as php is easier for me and the task that will be executed doesn't need to benefit from the added speed that it would have if it had been done in c++ but if i have no luck in solving this problem i guess i'll have to. EDIT Reasons for not using a database: 1-Whoever made it didn't used a database and it will be pretty hard to store this in an organized database if i'm not able to do something with it first, like just reading it, copying parts from it or putting in memory or something. 2-I don't have experience working with databases as pretty much all stuff i've ever done in php didn't needed large amounts of stored data, 50kb at best, if i was thinking about a big project or huge chunks of data as this one, i definitely would, but i didn't made this mess to start with and now i have to undo it. 3-The logic for having to store a small portion of data like 10mb in hard drive when now every computer has pretty much enough ram to fit the whole OS in it is pretty much incomprehensible unless someone gives a good explanation about it, if i had to access a lot of said files simultaneously i would understand but like i said, this is a simple project, this is the only file that will be accessed at a given time this isn't even to make some kind of website, it's to run a few times and be done with it.

    Read the article

  • Passing Data to Multi Threads

    - by alaamh
    I study this code from some book: #include <pthread.h> #include <stdio.h> /* Parameters to print_function. */ struct char_print_parms { /* The character to print. */ char character; /* The number of times to print it. */ int count; }; /* Prints a number of characters to stderr, as given by PARAMETERS, which is a pointer to a struct char_print_parms. */ void* char_print(void* parameters) { /* Cast the cookie pointer to the right type. */ struct char_print_parms* p = (struct char_print_parms*) parameters; int i; for (i = 0; i < p->count; ++i) fputc(p->character, stderr); return NULL; } /* The main program. */ int main() { pthread_t thread1_id; pthread_t thread2_id; struct char_print_parms thread1_args; struct char_print_parms thread2_args; /* Create a new thread to print 30,000 ’x’s. */ thread1_args.character = 'x'; thread1_args.count = 30000; pthread_create(&thread1_id, NULL, &char_print, &thread1_args); /* Create a new thread to print 20,000 o’s. */ thread2_args.character = 'o'; thread2_args.count = 20000; pthread_create(&thread2_id, NULL, &char_print, &thread2_args); usleep(20); return 0; } after running this code, I see different result each time. and some time corrupted result. what is wrong and what the correct way to do that?

    Read the article

< Previous Page | 80 81 82 83 84 85 86 87 88 89 90 91  | Next Page >