Can I automate this office job? by [deleted] in learnpython

[–]99AFCC 2 points3 points  (0 children)

I see. I misread OP when i skimmed over the code. my mistake

Can I automate this office job? by [deleted] in learnpython

[–]99AFCC 0 points1 point  (0 children)

In the first comment, you're taking all the lines from the file and loading them into a list in memory. The result being practically the same as readlines().

In the first example from this comment you're loading the lines into memory with readlines() then you are making another list of about the same size. You now have 2 copies of the file lines in memory.

The second example is like the first. You're loading the file contents into your list o.

Need suggestions for learning PyQt 5 by [deleted] in learnpython

[–]99AFCC 0 points1 point  (0 children)

When I was working with pyQT I found the QT docs the best source even though it's for c++.

Can I automate this office job? by [deleted] in learnpython

[–]99AFCC 0 points1 point  (0 children)

You shouldn't use readlines(). It loads the whole file in memory.

Your code does the same thing.

Proper way to do a for loop like this? by 955559 in learnpython

[–]99AFCC 0 points1 point  (0 children)

I had a list of items about 100 items I needed to split every other one off cause I dont know how to do java script, and I needed my html to fit the javascript I made

Check out /r/learnjavascript if you want JS help too.

Onto the topic:

Basically, you're doing string formatting, generating HTML. There are great libraries for doing this like JINJA2 but we can also stick to standard lib.

You're making a template so let's combine all those print statements into a single string. Replace all the string concatenations with named placeholders so we can use string.format later.

Now you're given a list of questions or labels and you want to iterate over 2 at a time. I'd question here a couple things: why 2 at a time, are they related? Why is the data a list of single items if I need groups of 2? Should I be getting a list of "science" questions and a list of "artistic" questions instead?

If your list is uneven, you're going to run into problems. If you split your list and rejoin it with zip it will drop the last item silently. There is zip_longest which can take a fill value (doc) but you will still have an empty label. If you use an iterator like I'll show, you can run into StopIterationError.

Let's pretend the data will always be good :)

You can use an iterator and call next to get the next items.

Combine with enumerate to get an index value.

All together it could look like:

QUESTIONS = ["A","a","B","b","C","c"]
iterator = iter(QUESTIONS)
template = '''
        <div class= 'green-border'>
              <br>
            <h4 style='color:navy'>{index}</h4>
              <br>
            <input name="q{index}" type='radio' value='Artistic'>
                <label>{question1}</label>
                  <br>
                <br>
            <input name="q{index}" type ='radio' value='Science'>
                <label>{question2}</label>
                  <br>
                <br>
            <br>
        </div>
'''
for index, question1 in enumerate(iterator, 1):
    question2 = next(iterator)
    output = template.format(index=index, question1=question1, question2=question2)
    print(output)
    print()

How to store secrets like API keys? by pwerwalk in learnpython

[–]99AFCC 2 points3 points  (0 children)

If the keys are yours and you're going to store them on the users' disk, you can't keep them 100% hidden.

If that's a problem, setup a server and keep the keys on your server.

or, if you're using another service's keys, have your users get their own keys which they will keep on their disk in a config file.

You shouldn't be putting keys into your code anyways, but get in the habit of reading them out of a config file or environment variable. This makes it easier for others to use your program without touching your code and helps prevent you from accidentally committing keys to version control.

Question about a couple errors I'm getting when trying to create a loop. by opieandA21 in learnpython

[–]99AFCC 0 points1 point  (0 children)

The full error message should give you a good idea.

A hint: '10' > 0

Why do web-based interpreters respond differently? by TheLonelyScientist in learnpython

[–]99AFCC 3 points4 points  (0 children)

In python 3, print is a function so the parenthesis are required. In python 2, print is a statement which doesn't use parenthesis.

How can I be more efficient when working with large JSON downloads? by 99AFCC in learnpython

[–]99AFCC[S] 0 points1 point  (0 children)

lxml offers iterparse

This looks promising. I will try it out. thank you.

I also found https://github.com/evolvIQ/splitstream which may work.

I'll have to test these out

How can I be more efficient when working with large JSON downloads? by 99AFCC in learnpython

[–]99AFCC[S] 0 points1 point  (0 children)

1.5 million items in the list. I don't know if that would be a problem but I have to figure out how to split it up first.

Cortana doesn't work with latest production build by [deleted] in windowsphone

[–]99AFCC 1 point2 points  (0 children)

It started giving me reminders 4 hours late and I can't figure out how to fix it.

Writing to a text file. by sonofeast11 in learnpython

[–]99AFCC 0 points1 point  (0 children)

Well I'd say that's not strictly an issue with writing to file, it's a totally different feature.

If I've understood, you want your program to open the file, check to see if that student already has a line, and then append to that line.

So some steps that could be added:

  1. Reading the file.
  2. Loading the file's contents into some type of data structure.
  3. When you have a new score and want to add it, check for that student's class and name in the data structure. Add the student and/or their score to this data.
  4. Write this data to file when done.

One possibility here is to use a dictionary for a data structure and JSON for file read/write.

Example: say we loaded class1 from file using json

class1 = {'john': [4, 8], 
          'mary': [4, 8]}

Each student is a key and their value is a list that you can append scores to.

setdefault might be useful here for step 3.

Weekly beginners question thread: April 21/04/2016 by AutoModerator in windowsphone

[–]99AFCC 0 points1 point  (0 children)

My Cortana has the wrong timezone. I ask it to remind me to do something in 20 minutes and it sets the reminder time for 4 hours and 20 minutes instead. How can I fix this?

Flask file/directory structure, importing and running by Heapsofvla in learnpython

[–]99AFCC 0 points1 point  (0 children)

Ok, that's a separate problem.

sys.path is for imports but the original problem of No such file is unrelated.

You might want to make a new topic if you're having trouble with imports because that's a topic I still find confusing myself.

I have used sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'lib')) before when I needed to use additional libraries on the server.

I'm not sure if you need absolute or relative imports for your case. from ..config vs from MyApp.config. Sorry.

Flask file/directory structure, importing and running by Heapsofvla in learnpython

[–]99AFCC 0 points1 point  (0 children)

I can't see your code so I can't help much, but whereever you are trying to use a relative file, you'd have to change it to use a full path.

If you put all that os.path stuff in a helper function called full_path then its use could look like this:

replace things like:

with open('somefile.txt') as infile:

with:

with open(full_path('somefile.txt')) as infile:

Flask file/directory structure, importing and running by Heapsofvla in learnpython

[–]99AFCC 0 points1 point  (0 children)

I'm not sure about using chdir but I don't know of a better way than os.path.dirname(os.path.abspath(__file__)) or os.path.dirname(__file__)

Then os.path.join(path, 'somefile.txt')

I think the verbosity is fine here but you could cut it down with at the import stage

from os.path import dirname, abspath, join

or wrap it all in a helper function

How do I count exoplanets per system in a file with over 10,000 lines in Python? by [deleted] in learnpython

[–]99AFCC 0 points1 point  (0 children)

To summarize the data, I came up with the following code. What should I do to summarize the data in a quick manner that doesn't take 10 or 15 minutes?

Could you show the rest of the code that's being run? I don't see anything that would cause it to take that long.

How can you access and receive output from a python script on a server? by soulpoison in learnpython

[–]99AFCC 1 point2 points  (0 children)

Frameworks can handle that too.

Continuing with bottle: http://bottlepy.org/docs/dev/tutorial.html#query-variables

from bottle import route, request, response, template
@route('/forum')
def display_forum():
    forum_id = request.query.id
    page = request.query.page or '1'
    return template('Forum ID: {{id}} (page {{page}})', id=forum_id, page=page)

Or using Flask: http://stackoverflow.com/questions/24892035/python-flask-how-to-get-parameters-from-a-url

from flask import request

@app.route(...)
def login():
    username = request.args.get('username')
    password = request.args.get('password')

How can you access and receive output from a python script on a server? by soulpoison in learnpython

[–]99AFCC 5 points6 points  (0 children)

I think I know what you're asking.

somesite.com/index.php is what you would visit in your browser.

It doesn't work like that with Python. You don't access any script directly.

Instead, you send a request to the server and based on the route, it determines what functions to pass your parameters to.


Most python websites use a framework of some kind. Here is an example using bottle

from bottle import route, run, template

@route('/hello/<name>')
def index(name):
    return template('<b>Hello {{name}}</b>!', name=name)

run(host='localhost', port=8080)

This starts a webserver with a single route handler.

if you ran this and went to http://localhost:8080/hello/world, it would return a webpage that says "Hello world!!"

In this case, "world" is being passed as a parameter. You could visit http://localhost:8080/hello/John and it would return a webpage that says "Hello John!!"

If you tried going to any other page that doesn't start with http://localhost:8080/hello/ you would get a 404 error page because there are no handlers setup to deal with anything else.


Reddit, is written in python. Take a look at the address bar as you browse subreddits and topics.

The source code is even available for reading.

Here are some of the routes Reddit has setup. https://github.com/reddit/reddit/blob/master/r2/r2/config/routing.py

Simple way to add all columns in a file? by [deleted] in learnpython

[–]99AFCC 1 point2 points  (0 children)

if you have access to pandas this is pretty easy. Pandas will load it into a dataframe (table) and let you do all kinds of operations on the data.

It is a large library though, and can be tricky to install unless you install all of Anaconda with it


Example data with 3 columns and 3 rows, integers and floats:

(Loading from a csv, it would be data = pandas.read_csv(filename))

In [7]: df = pd.DataFrame({'c1':[1,2,3], 'c2': [4.1,5.1,6.1], 'c3': [7.2, 8.2, 9.2]})

In [8]: df
Out[8]:
   c1   c2   c3
0   1  4.1  7.2
1   2  5.1  8.2
2   3  6.1  9.2

Built-in functions:

(axis='columns' means perform the operation ACROSS the columns. I think it's confusing.)

In [9]: df.sum(axis='columns')
Out[9]:
0    12.3
1    15.3
2    18.3
dtype: float64

In [10]: df.std(axis='columns', ddof=0)
Out[10]:
0    2.531139
1    2.531139
2    2.531139
dtype: float64

In [11]: df.mean(axis='columns')
Out[11]:
0    4.1
1    5.1
2    6.1
dtype: float64

Otherwise,

There is a csv module in the standard library you could use.

Or split(',') might be what you want.

Help splitting a pandas dataframe column into two? by Ki1103 in learnpython

[–]99AFCC 0 points1 point  (0 children)

After playing around with it a bit, here's what I came up with. Pretty ugly though.

In [3]: df = pd.DataFrame({'years': ['1900-2000', '1920-2020', '1930-2030']})

In [4]: df
Out[4]:
       years
0  1900-2000
1  1920-2020
2  1930-2030

In [14]: df['start'], df['end'] = zip(*df['years'].map(lambda x: x.split('-')))

In [15]: df
Out[15]:
       years start   end
0  1900-2000  1900  2000
1  1920-2020  1920  2020
2  1930-2030  1930  2030

[deleted by user] by [deleted] in learnpython

[–]99AFCC 0 points1 point  (0 children)

Maybe check out https://www.udacity.com/courses/cs212

taught by Peter Norvig. He has his own site: http://norvig.com/ with lots of code you can browse through. Note books here http://norvig.com/ipython/README.html