griswolf 304 Veteran Poster

My very first thought is that what you want to do is extremely annoying: You're grabbing the keystream away from the user right while the user is still typing. That's why word processors typically don't do that; they simply mark the (probable) error and let the user do the correction later. I have a "kitchen timer" app that pops up a modal dialog when it goes off, but that dialog accepts keystrokes to set a "pause" time. If I'm typing when it pops up, it steals my input which is extremely annoying twice: Not only does it maybe get set to some pause value and restarted, but the email (or Daniweb comment) that I'm typing into gets whatever is left. Bleaugh.

The other model to think about is how texting apps work: As you type, it displays the word(s) you are probably working on and lets you choose or take the default with a specific keystroke or gesture. This too doesn't back up: It just jumps forward in a manner dependent on the user's actions.

Can you rethink what your intention is?

griswolf 304 Veteran Poster

I'm writing a utility that will likely be called by a script that uses argparse, but should be useable by any script. The engine object constructor needs a dozen or so parameters to tune its behavior. The question is: What is the best way to allow the caller to send the necessary parameters without requiring extra work setting params that have defaults.

First thought: Since some users will have an argparse.Namespace instance already, I might make use of that. But other users would need to create a Namespace (or just a subclass of object) which seems like a problem.

Second thought: Normal methods are written to just take a sequnce of (named) parameters, which is what programmers will expect. Better yet, Python allows **kwargs in constructor's parameters, and vars(aNamespace) is a map, so it seems we could call EngineObject(*args, **vars(an_argparse_namespace)) and have the best of all worlds. But, alas, if the caller's Namespace instance has attributes that the Engine constructor doesn't recognize, it won't run.

Third thought: But... if we write the constructor as __init__(self,arg1,arg2,arg3=def3,...argN=defN, **kwargs) that final **kwargs will eat all the extra attributes. I like this... But, as I found by accident, if I pass a needed ..., misspelled=value, ... there is no warning that I got it wrong because that **kwargs eats the misspelled parameter name just like it would eat other named parameters that we don't care about.

Current thought: I now have this code:

class Engine:
    @classmethod
    def clean_map(cls, amap):
      """return a map holding …
griswolf 304 Veteran Poster

And your question is?

griswolf 304 Veteran Poster

For a (ba)sh script I'd look at (g)awk, which allows you to write little functions based on a regex match. You can set (global) variables within the functions, and you can check their values which gives you something resembling a state machine.

griswolf 304 Veteran Poster

http://en.wikipedia.org/wiki/Benchmark_%28computing%29#Open_source_benchmarks

(less than 30 seconds to use Google, decide on Wikipedia, find the Open Source section. Another minute or so to write this reply)

griswolf 304 Veteran Poster

Pick a programming language. One language. Python is a good choice, but there are many other good choices. Then do some tutorials in that language. When you get stuck, ask (here) for help with what you ran up against. Be sure to show what work you have done.

griswolf 304 Veteran Poster

Think about the flow of logic: Why are you asking the user for a new pair of words on every line? Shouldn't you do that at the top, then just use them in the loop?

Here's a function that (almost) returns the line that is manipulated, but if there are multiple adjacent spaces in the line, they are replaced by one space, or if the line has indentation, it is lost.

def collapse_spaces(line):
    build = []
    for w in line.split():
        build.append(w)
    return ' '.join(build)

You should be able to modify this to get a 90% on the homework problem, maybe more if the grader misses the point about indentation. What they probably want you to use, though, is slice replacement, based on http://docs.python.org/library/stdtypes.html#str.find

griswolf 304 Veteran Poster

There is one further consideration: Both fields of study are difficult and time consuming: Unless you are brilliant or/and have much better study habits than most, you will need longer to finish such a double major than most students. Where I attended school, both degrees were in the Engineering department; where most students these days take 5 years to finish. I would expect closer to 6 for this double major.

griswolf 304 Veteran Poster

Agile is a way of thinking about requirements, then creating what is needed. Agile practice doesn't even need to be about coding a program, it can be used for any requirements about any product, though programming is the place it is most used. There is no part of Agile development that specifies how requirements are described, nor how you use those requirements to create a product. Your concern about this makes it clear that you do not yet understand what Agile development really is.

You can use UML, DFD, a spreadsheet, voicemail or sending signals by tapping your water glass: Whatever works best in your environment. Use what the client is equipped to deal with. If you are in a software class, then the professor is your client.

Be aware that because Agile makes heavy use of code refactoring, the specifics of your data (data flow) may change with each iteration: Make sure your tool can easily cope with changes.

griswolf 304 Veteran Poster

I prefer to send the quit condition as a second argument to the list entry function. That way, if you need 'q' as a valid list member, you can use something else to stop the loop (also works better for folks whose language does not use a 'q' word to mean "quit"). The second argument can be a string to match against, or it could be a function that takes a string and returns a boolean. The latter is the most general, but also more trouble than it is worth in many cases.

griswolf 304 Veteran Poster
  1. You need to understand the with statement at my lines 5 and 8: not more important than def, but less likely to be covered in an intro course.

  2. You need to understand how to read the python manual: http://docs.python.org/index.html so as to make best use of the library features. You tried to use randint which is not best suited to this problem. It is mostly a matter of searching and then reading more than just a little bit.

  3. I don't understand "close". I suspect you're using Python in an environment other than the command line. I just use the command line so I'm not the person to ask about how to deal with your environment.

  4. In passing, the Python style guide: Indentation calls for using 4 spaces per indent level. It is very good to just grit your teeth and follow the style guide even if you have a different preference: It is practical, well thought out, everybody understands how to read it (and code reading happens much more than code writing). In particular, because tabs and spaces look the same on the screen, don't ever mix them, but to conserve screen space (width) do prefer spaces alone. Your editor will have a setting to help make that happen.

griswolf 304 Veteran Poster

This is not the most efficient or tight code, but it works. In particular, the function populate(...) could be shorter. In a real world situation populate() should raise a useful error if the files aren't found or aren't as expected (many more lines of code)

I have also deliberately made the output print incorrectly unless you are using Python 3. Note also that raw_input would be incorrect with Python 3.

I've broken the work into two functions and a driver loop. This is typical style for interactive programs; though usually the driver loop is also in its own function which is called from the bottom of the file.

import random
def populate(first_file_name, last_file_name):
    first_names = []
    last_names = []
    with open(first_file_name,'r') as f:
        for line in f:
            first_names.append(line.strip())
    with open(last_file_name,'r') as f:
        for line in f:
            last_names.append(line.strip())
    return first_names, last_names

def print_random_name(first_names,last_names):
    if not first_names:
        first_names = ['Henry']
    if not last_names:
        last_names = ['Jones']
    print(random.choice(first_names), random.choice(last_names))

first_names, last_names = populate('fname.txt','lname.txt')

response = 'y'
while response == 'y':
    print_random_name(first_names,last_names)
    response = raw_input('Print another? ').lower()[0]
griswolf 304 Veteran Poster

I see no need to make the deep copy. Pick an attr, save its value, try to change it, then if it changed, put back the original.

But I'm with lrh9: A function that does two different things is an odd duck: The code that calls it cannot depend on the return value to be what it expects. Why not always return a mutated copy rather than only sometimes?

griswolf 304 Veteran Poster

You can use an NDFA (NFA) where each transition character in your short string triggers a transition in the NFA, if possible. The google knows about how you might want to start doing that.

griswolf 304 Veteran Poster

you use the * operator on the list: attr_gen = attrgetter(*my_list)

griswolf 304 Veteran Poster

If you want to convert lists (tuples) to strings using the same string between each item, such as ZZucker suggests, you should use the join method on a string, as for instance:

my_list = ['one', 'two', 'three', 'the end']
print('\n'.join(my_list))

which results in this output:

one
two
three
the end
griswolf 304 Veteran Poster

If you want to save the actual email, see the tee command, or just send it to a post box that has a mail filter that refiles it as needed.

griswolf 304 Veteran Poster

Be sure to notice the method setdefault. Or use class Counter.

griswolf 304 Veteran Poster

If you need to write your own instead of using strftime/strptime, the right answer is probably regular expressions

Regular expression syntax is tricky if you don't already know it (and sometimes, if you do).

import re
timeS = r'(?P<hour>[01]?\d):(?P<minute>[0-5]\d) *((?P<am>[Aa]\.?[Mm].?)|(?P<pm>[Pp]\.?[Mm]\.?))
timeRE = re.compile(timeS)
# ... get somestring "some how"
m = timeRE.match(somestring)
# now look at m.groups, being careful to cope with failure modes

Beware that this regex will pass bad strings such as "19:18 pm" or "12:15 xx" and will not accept a valid time 24 hour time such as "22:23" (easy to fix in timeS if you want it).

BustACode commented: I have got to learn RedEx, as that looks like Chinese to me. +1
griswolf 304 Veteran Poster

I see several problems:

  • inpt is a string, so your line 21 will never be true. If you want integer types (as your code indicates), use the isdigit() method on strings. See also point 3
  • Your lines 20 and further should not be in the loop. Indentation counts!
  • Your line 13 will never succeed in breaking the loop. Better if at line 11: inpt = sys.stdin.readline().strip() or line 13:if inpt.strip().lower().startswith('e') or some combination

In addition, I find myself typing your inpt with a 'u' in it to spell a word. In general, it is good practice to use fully spelled words. Python best practices suggest is that functions/methods and variables are spelled_with_underbars and class names are spelled in CapitalCamelCase. By doing so, you avoid the need to remember the way things are spelled and need only remember the name (or concept) itself. Exceptions being: Loop variables may be i, x, etc. and of course if the "natural" name for something is a keyword or common Python name, you must find an alternative such as from_limit (avoids keyword 'from'), user_input (avoids global function 'input') or max_value (avoids global function 'max').

griswolf 304 Veteran Poster

As someone mentioned in another thread (Computer Science): It is important to get clarification when the spec is ambiguous. The OP (original poster) has not asked a specific question.

griswolf 304 Veteran Poster

Consider the decimal module.

griswolf 304 Veteran Poster

I would use the interactive function input something like this snippet

prompt = "Enter a number or 'e' to end "
user_list = []
while True:
   value = input(prompt)
   if value.lower().startswith('e'):
      break
   user_list.append(value)

print(user_list)

Beware that input() returns a string, not a number, so you will need to convert if you really need numbers.

griswolf 304 Veteran Poster

Was there a question there?

griswolf 304 Veteran Poster

The Python break key word is a way to break out of a loop. Just that. So, for instance

result=None
for i in range(1000000000): # really long loop
    result = check_item(i)
    if are_we_done_looking(i, result):
        break # so we don't have to finish the loop
if result:
    generate_report(result)
else:
    print("Useful result not found.")

Please go read an introduction to Python programming. For instance these, though there are probably hundreds.

griswolf 304 Veteran Poster

No need for subprocesses to run things in sequence:

import os
os.sytem('music_player loud_music.mp3') # silly example
os.system('video_player spinning_things.mp4') # more silliness
# etc
griswolf 304 Veteran Poster

I think that you are posting in the wrong forum: How is this a Python question? Ignoring that issue, you are confused again: A "music file" doesn't "play all the way through" because it holds music, but does not play it. In general terms: To have something happen after something else, you create a supervisor program that tells the system what to do in what order, and you run that program.

griswolf 304 Veteran Poster

What you have shown so far will not run because indents matter in Python and your code shows none.

griswolf 304 Veteran Poster

This does not appear to belong in the C++ forum

griswolf 304 Veteran Poster

Look in the top right hand corner of this page, in the purple part. See the button labeled "Search" with a text box immediately to its left. Fill in "Scrape website" and press search. Be aware that the top few entries are commercials. Enjoy.

griswolf 304 Veteran Poster

Hmm. I thought I was being clear.

If you chant myscript.py with no further arguments, then sys.argv has just one list element: "myscript.py". If you chant myscript.py argumentOne then sys.argv has two list elements: "myscript.py" and "argumentOne" ... and so forth for any number of command line arguments. Your script requires that you invoke it with exactly three arguments. If you were to invoke it with, say, two arguments or four arguments, it would fail. I'm not really sure what part of what I said was a problem. Does this help?

griswolf 304 Veteran Poster

Either it isn't in your python path (examine sys.path) or it isn't being recognized as a module. Most modules are a file, such as in your case a file named mechanize.py if you have a directory, then to find files within it, you need a file named __init__.py (which might be empty).

griswolf 304 Veteran Poster

First, let me recommend to you that you use the (CODE) button. Either click it and then paste your code between the tags, or highlight your code and click it. This is prettier

# Get command line arguments from the sys module 
from sys import argv
# ...

than yours, don't you you agree?

Second, for future reference. Note the "mark thread as solved" link near the bottom of the page. Only you, the original poster, can see that link. Using it after the thread is solved helps keep DaniWeb functioning smoothly.

Finally: Your comments are not quite right. For one thing, no real programmer would over-comment so much, but ignore that: You are indicating your understanding of the code, not "real comment"ing. The issue I still have is that you are skipping over how things are put into sys.argv When I invoke a python script from the command line: python myscript.py some subsequent words the python interpreter puts the script name into sys.argv[0] and any subsequent arguments into the rest of the sys.argv list. So from the command line above, you would end up with sys.argv == ['myscript.py', 'some', 'subsequent', 'words'] If you don't put exactly three arguments on the console command line when invoking your script, you will get a failure. Your comment almost seems to imply that the program interacts with the user to get the values. Not true.

griswolf 304 Veteran Poster

Stepping back a bit, why don't you have a single column for your date information and make use of MySql date and time functions to deal with your query? MySql will handle such things both more quickly and more robustly than your program. See http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html Replace the /5.6/ with whatever version is yours if you need to (recent changes are about the precision of partial seconds, which I doubt matters to you). See particularly the MONTH() and YEAR() functions which will extract the month and year from a date (or datetime or timestamp)

griswolf 304 Veteran Poster

There are issues about scraping data from a website. Programs work so much more quickly than humans that even if the website owner doesn't restrict who can use the data, they may restrict how much data a program can access, to avoid overloading the server. Aside from being nice about how you access the data, there are also legal issues. If the site has a usage agreement, your program must work within the requirements of that agreement. Some sites prohibit access by programs that scrape data, for instance.

In this case, you need to read and understand this: http://www.bet-mate.com/terms-and-conditions. There are two sections that would cause me to ask them for permission: Section 6 says you cannot use this for commercial purposes. Assuming this is for your own personal use, that isn't a stopper. Section 10 reserves all rights to the web site owner. One of those rights, which doesn't have to be specifically mentioned, is the right to copy the data. Your proposed program will copy their data, so you need their permission to do it. There is a 'contact' link below section 11. I strongly urge you to use it.

griswolf 304 Veteran Poster

from sys import argv Says: From the module named sys (which, if it were in a file would be in a file named 'sys.py') import the thing named 'argv' into the current name context. That makes it possible to refer to 'argv' without having to mention the module it came from. If you had instead said import sys then you would have all the things in sys available, but you would have to access them scoped by their module name. For instance script, first, second, third = sys.argv script, first, second, third = argv Says: unpack into the four named variables, the values contained in the variable named 'argv'. Python allows you do do simultaneous assignments so v_1,v_2 = "one",2 for instance works as if you said both v_1="one" and v_2=2 This is one of the cool syntactical features of Pyrhon. The quoted line assumes that argv holds exactly 4 values which can be unpacked into the four named variables. In real code, that assumption would be a very bad idea. print whatever You are using a 2.x version of Python which has an operator named print. Versions 3.x and above have a function named print. The difference is that operator print prints everything that follows it on the line: print "Hello", "world" whereas function print requires the things to be printed be passed as parameters in a function call: print("Hello","world") There is no urgent reason to choose Python 3.x over Python 2.x. Whichever one you have …

griswolf 304 Veteran Poster

A recursive function calls itself (or calls a function that calls a function that ... calls the original). If you think about a magic square, where would there be a chance to recurse? Since we need to test the main diagonals as well as the rows and columns, we can't recurse on the test for magicness. So, I suppose the only option is to write a recursive function to build the square to test. I'll leave that as an exercise...

griswolf 304 Veteran Poster

the code does not work as the web page is not word message and cannot be printed. any help
thanks

I'm sorry, I do not understand this. Do you need to create a web page using Python? There are many options to do that. I use Django for large projects with simple database needs; you may also like to look at Web2Py or an overview: http://wiki.python.org/moin/WebFrameworks

griswolf 304 Veteran Poster

Because Python has 2.x and 3.x versions, it is wise to mention the python version in the module comment or string

It would be nice of you to print a summary of the state of the game in the game loop. Such as print("Correct guesses: %s; Wrong guesses: %s"%(correct_guesses, wrong_guesses)) To avoid having duplicate code to accept the user's guess, I usually use a loop like this

prompt = "Guess a letter " # note the trailing space
while True:
  # display
  print(whatever)
  # ask
  answer = input(prompt)
  # analyze
  # 
  if [I]end_condition[/I]:
     break
  # get ready for next loop, for instance:
  prompt="correct prompt for this loop"

Your line 64 is redundant. Just the if/else is enough.

Usually, you don't require the user to end the game unless the "leave the game" condition is inside the game loop. Or unless the game is running inside a window that will close when the code stops.

the variable name wordTuple is misleading because it is not a tuple: word_from_tuple might make sense, but I would prefer to_guess , or target (I don't expect perfect English). Every variable should be a good name that you never have to think about how it is spelled or what it means. Standard Python naming prefers that classes be named in CamelCase; and that variables and functions should have words_separated_by_underbars. Note that good variable names are much better than comments for self-documenting code: The variable name is seen everywhere it is used, but …

griswolf 304 Veteran Poster

I get a factor of 1.67 . If you need to explain that 1.2 is the correct factor, then you have to say that something else is important. Maybe I/O on the new machine is faster or the new machine has faster/larger CPU-side cache or ...

griswolf 304 Veteran Poster

Python doesn't allow overloading functions the way you're trying to do it at lines 44 and 49 (use *args or **kwargs to provide default trailing parameters: http://docs.python.org/tutorial/controlflow.html#default-argument-values

Your player class should be spelled with a capital 'P' to avoid confusion (http://www.python.org/dev/peps/pep-0008/)

I don't see anything else obvious just looking.

griswolf 304 Veteran Poster

Yeah. One of the many advantages of normal form is that it is pretty easy to be sure you have a chain of connection between any related entity, no matter how remote. Though you do have to think about the direction of the relationship. I've ended up with many-to-many join tables a few times when I realized I needed to go either direction along what might otherwise have been a one-to-one relationship.

I've found in my own work that it is good to think "nearly first" about what reports you will need: When you have options about details of the schema, thinking about how you will make a query to give you the (whatever) report can help you get it right.

griswolf 304 Veteran Poster

OK, I see your point. But. If I were doing it, I'd have a CATALOG of items, and each store would have an INVENTORY of count (and other stuff?) and FK into the catalog. There would be no VIDEO table. All the advantages you note above and no need to individually mark each "Forrest Gump" disc. Probably the price table has a STORE FK to allow the possibility that Forrest Gump sells for more in New Orleans than in Boise, or whatever.

griswolf 304 Veteran Poster

The issue you're still seeing, I think, is that T* doesn't match std::string. Stop and think about what T really is here.

griswolf 304 Veteran Poster

Please use the CODE button to show indents, line numbers, syntax coloring...

Hints:

  • You can get the list of words by simply saying words = sentence.split()
  • You need to think about punctuation, in case user inputs some. For instance, if you got the words from the first sentence of this hint, "punctuation," and "some." have trailing punctuation.
  • I would write the function english_to_piglatin so the parameter is a single word rather than a list of words.
  • The usual idiom for modules that need to (also) run as a script is if __name__ == "__main__": main() You might as well get into the habit of invoking main() that way.
griswolf 304 Veteran Poster

I'm having a hard time wrapping my mind around individual UID for each item in stock. That makes sense for one-off things like original artwork, or service calls; but for the things in a video store, not so much (in my opinion). And having a one-to-one relationship between your database items and actual items leads to your issue about whether to remove the database items when they are (sold/discarded/stolen). On that point: Just don't remove them. Use a status to indicate what happened. That way, you don't have to think about what happens in tables that have a FK referencing that item's entry when the item goes away. If necessary (its not), you can partition tables by date to avoid overfilling them.

griswolf 304 Veteran Poster

...
And it's better not to use the built in types until you know how to make them yourself. When you learn how they work, you can then use the easy version. Otherwise you can't program worth beans if you get into a language that doesn't magically define all your special data types.

Of course your opinion is the best one: Its yours! But in the opinion of most programming educators, it is more important to learn how to program at the first stage, and only then learn nuts and bolts details about some language or other. But this isn't the right forum for that discussion.

griswolf 304 Veteran Poster

I have to dispute your "pretty much done". I spotted a half dozen problems before I looked at your errors. That said:

If you actually read the error messages, they give you pretty good clues about what the problem is. Main clue: What line is the parser on when it gives up and emits an error? (The problem will be on or before that line). Secondary clue: What did the parser say the problem is? Even if you can't understand it, you can often get a hint.

I have to admit, the first error is a doozy to figure out. If you scan backward in your code from line 29 until you find an unmatched '(', though, you will see a problem on line 16.

P.S. I'd rename that function to "bubbleSortArray"

P.P.S. <rant>Why are you using a raw array in a C++ class? (Yeah, I see what the prof says to do, but it is, in my opinion, a very poor use of your time and the compiler.) Introductory C++ should make much use of the STL and all the built in C++ types until you get your feet under you about what it means to program. Arrays are efficient C structures, but there's no reason to care about efficiency in a beginning programming class; and very little reason to ever need them in professional C++ programming (unless you end up writing library code, which is very unlikely). </rant>

griswolf 304 Veteran Poster

What have you tried? What worked? What didn't? Do you have a specific question?

griswolf 304 Veteran Poster

Not clear to me why you have table CATALOG instead of having that information directly in table VIDEO (unless you are planning to add non-video items? Even so, I think that the VIDEO table is the CATALOG table (and add a "type" column to it so you know if it is a video or a bag of popcorn)

This ER diagram doesn't describe the "manyness" of the connection, unless the double-edge diamonds are many-to-many?

Does a customer have to be a member? Why? In the real world, you convince them by offering something, but not all customers will accept that offer. You may be ok with a special "non-member member" who gets every non-member sale (you can insist on membership for rentals, I suppose). Did you ever deal with Radio Shack when they used to insist on collecting your contact info for every transaction? I didn't notice when it stopped, but it is a relief that they did stop.

Are you sure every video has exactly one vendor? If you design it that way, then videos that mere humans consider "the same" end up with different VideoID. On the other hand maybe the vendor really is part of the item: Pricing might be different, or you might buy rentals from one place and sale items from another.

Ditto employees. Are there some folks who work weekends at store #44 and weekday evenings at store #77?

You want that video ID are never removed from the …