<commit_before>import argparse
import os
from pkg_resources import find_distributions

from .checker import Checker
from .loader import Loader

def make_local_settings(argv=None):
    """Generate a local settings file."""
    parser = argparse.ArgumentParser(
        description=make_local_settings.__doc__,
    )

    parser.add_argument('env', help='Environment name (e.g., dev or prod)')
    parser.add_argument(
        '-b', '--base-settings-module', default=None,
        help='Base settings module as a dotted path')
    parser.add_argument(
        '-f', '--file-name', default=None,
        help='Name of file to write settings into')
    parser.add_argument(
        '-s', '--section', default=None,
        help='Section to read/write settings from/to (default = <env>)')
    parser.add_argument('-o', '--overwrite', action='store_true', default=False)

    args = parser.parse_args(argv)

    os.environ['DISABLE_LOCAL_SETTINGS'] = '1'
    if args.base_settings_module is None:
        dist = next(find_distributions('.', only=True), None)
        if dist is not None:
            args.base_settings_module = '{0.project_name}.settings'.format(dist)
        else:
            msg = 'Could not guess which base settings module to use; specify with -b'
            parser.exit(1, msg)

    module = __import__(args.base_settings_module, fromlist=[''])
    base_settings = vars(module)

    if args.file_name is None:
        file_name = 'local.{0.env}.cfg'.format(args)
        section = args.env
    elif '#' in args.file_name:
        file_name, section = args.file_name.rsplit('#', 1)
    else:
        file_name = args.file_name
        section = args.env

    file_name = os.path.normpath(os.path.abspath(file_name))

    if args.section:
        section = args.section

    registry = None

    if os.path.exists(file_name):
        if args.overwrite:
            print('Overwriting {0.file_name}'.format(args))
            with open(file_name, 'w'):
                pass
        else:
            loader = Loader(file_name, section)
            loader.load(base_settings)
            registry = loader.registry

    checker = Checker(file_name, section, registry=registry)
    try:
        checker.check(base_settings)
    except KeyboardInterrupt:
        print('\nAborted')

if __name__ == '__main__':
    make_local_settings()
<commit_msg>Unwrap lines<commit_after>import argparse
import os
from pkg_resources import find_distributions

from .checker import Checker
from .loader import Loader

def make_local_settings(argv=None):
    """Generate a local settings file."""
    parser = argparse.ArgumentParser(description=make_local_settings.__doc__)

    parser.add_argument('env', help='Environment name (e.g., dev or prod)')
    parser.add_argument(
        '-b', '--base-settings-module', default=None,
        help='Base settings module as a dotted path')
    parser.add_argument(
        '-f', '--file-name', default=None,
        help='Name of file to write settings into')
    parser.add_argument(
        '-s', '--section', default=None,
        help='Section to read/write settings from/to (default = <env>)')
    parser.add_argument('-o', '--overwrite', action='store_true', default=False)

    args = parser.parse_args(argv)

    os.environ['DISABLE_LOCAL_SETTINGS'] = '1'
    if args.base_settings_module is None:
        dist = next(find_distributions('.', only=True), None)
        if dist is not None:
            args.base_settings_module = '{0.project_name}.settings'.format(dist)
        else:
            msg = 'Could not guess which base settings module to use; specify with -b'
            parser.exit(1, msg)

    module = __import__(args.base_settings_module, fromlist=[''])
    base_settings = vars(module)

    if args.file_name is None:
        file_name = 'local.{0.env}.cfg'.format(args)
        section = args.env
    elif '#' in args.file_name:
        file_name, section = args.file_name.rsplit('#', 1)
    else:
        file_name = args.file_name
        section = args.env

    file_name = os.path.normpath(os.path.abspath(file_name))

    if args.section:
        section = args.section

    registry = None

    if os.path.exists(file_name):
        if args.overwrite:
            print('Overwriting {0.file_name}'.format(args))
            with open(file_name, 'w'):
                pass
        else:
            loader = Loader(file_name, section)
            loader.load(base_settings)
            registry = loader.registry

    checker = Checker(file_name, section, registry=registry)
    try:
        checker.check(base_settings)
    except KeyboardInterrupt:
        print('\nAborted')

if __name__ == '__main__':
    make_local_settings()
<|endoftext|>


<commit_before>#!/usr/bin/python
import pywapi
import subprocess
import re
from getIndoorTemp import getIndoorTemp

from flask import Flask, request, session, g, redirect, url_for, \
     abort, render_template, flash, jsonify

app = Flask(__name__)
#hard to be secret in open source... >.>
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'

ZIP = 37216

#start the daemon in the background
subprocess.Popen("./rubustat_daemon.py", shell=True)

def getWeather():
    result = pywapi.get_weather_from_yahoo( str(ZIP), units = 'imperial' )
    string = result['html_description']
    string = string.replace("\n", "")

    #You will likely have to change these strings, unless you don't mind the additional garbage at the end.
    string = string.replace("(provided by The Weather Channel)
", "")
    string = string.replace("
Full Forecast at Yahoo! Weather

", "")
    return string

@app.route('/')
def my_form():
    f = open("status", "r")
    targetTemp = f.readline().strip()
    mode = f.readline()
    f.close()
    weatherString = getWeather()

    #find out what mode the system is in, and set the switch accordingly
    #the switch is in the "cool" position when the checkbox is checked

    if mode == "heat":
        checked = ""
    elif mode == "cool":
        checked = "checked=\"checked\""
    else:
        checked = "Something broke"
    return render_template("form.html", targetTemp = targetTemp, \
                                        weatherString = weatherString, \
                                        checked = checked)

@app.route("/", methods=['POST'])
def my_form_post():

    text = request.form['target']
    mode = "heat"

    #default mode to heat
    #cool if the checkbox is returned, it is checked
    #and cool mode has been selected

    if 'onoffswitch' in request.form:
        mode = "cool"
    newTargetTemp = text.upper()
    match = re.search(r'^\d{2}$',newTargetTemp)
    if match:
        f = open("status", "w")
        f.write(newTargetTemp + "\n" + mode)
        f.close()
        flash("New temperature of " + newTargetTemp + " set!")
        return redirect(url_for('my_form'))
    else:
        flash("That is not a two digit number! Try again!")
        return redirect(url_for('my_form'))

@app.route('/_liveTemp', methods= ['GET'])
def updateTemp():

    indoor_temp=getIndoorTemp()
    rounded_indoor_temp = round(indoor_temp,1)
    return jsonify(rounded_indoor_temp=rounded_indoor_temp)

if __name__ == "__main__":
    app.run("0.0.0.0", port=80)<commit_msg>Comcast helped with debugging. Always TRY to fetch internet resources...<commit_after>#!/usr/bin/python
import pywapi
import subprocess
import re
from getIndoorTemp import getIndoorTemp

from flask import Flask, request, session, g, redirect, url_for, \
     abort, render_template, flash, jsonify

app = Flask(__name__)
#hard to be secret in open source... >.>
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'

ZIP = 37216

#start the daemon in the background
subprocess.Popen("./rubustat_daemon.py", shell=True)

def getWeather():
    result = pywapi.get_weather_from_yahoo( str(ZIP), units = 'imperial' )
    string = result['html_description']
    string = string.replace("\n", "")

    #You will likely have to change these strings, unless you don't mind the additional garbage at the end.
    string = string.replace("(provided by The Weather Channel)
", "")
    string = string.replace("
Full Forecast at Yahoo! Weather

", "")
    return string

@app.route('/')
def my_form():
    f = open("status", "r")
    targetTemp = f.readline().strip()
    mode = f.readline()
    f.close()
    try:
        weatherString = getWeather()
    except:
    weatherString = "Couldn't get remote weather!"

    #find out what mode the system is in, and set the switch accordingly
    #the switch is in the "cool" position when the checkbox is checked

    if mode == "heat":
        checked = ""
    elif mode == "cool":
        checked = "checked=\"checked\""
    else:
        checked = "Something broke"
    return render_template("form.html", targetTemp = targetTemp, \
                                        weatherString = weatherString, \
                                        checked = checked)

@app.route("/", methods=['POST'])
def my_form_post():

    text = request.form['target']
    mode = "heat"

    #default mode to heat
    #cool if the checkbox is returned, it is checked
    #and cool mode has been selected

    if 'onoffswitch' in request.form:
        mode = "cool"
    newTargetTemp = text.upper()
    match = re.search(r'^\d{2}$',newTargetTemp)
    if match:
        f = open("status", "w")
        f.write(newTargetTemp + "\n" + mode)
        f.close()
        flash("New temperature of " + newTargetTemp + " set!")
        return redirect(url_for('my_form'))
    else:
        flash("That is not a two digit number! Try again!")
        return redirect(url_for('my_form'))

@app.route('/_liveTemp', methods= ['GET'])
def updateTemp():

    indoor_temp=getIndoorTemp()
    rounded_indoor_temp = round(indoor_temp,1)
    return jsonify(rounded_indoor_temp=rounded_indoor_temp)

if __name__ == "__main__":
    app.run("0.0.0.0", port=80)<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
# Python2 compat
from __future__ import unicode_literals, print_function, division
try:
    input = raw_input
except NameError: # python3
    pass

# Local imports
from definitions import journalAbbrevs, bcolors

# Imports
import ads
import argparse
# from gooey import Gooey
import re
import requests
from tqdm import tqdm
import os

# import codecs
# import sys

# UTF8Writer = codecs.getwriter('utf8')
# sys.stdout = UTF8Writer(sys.stdout)

class BuildQuery:

    def __init__(self):
        "Creates a build object query"
        self.query = dict()
        return

    def setKey(self, key, val):
        '''Set the key to val in the query'''
        if val is not None:
            self.query[key] = val

    def execute(self):
        return ads.SearchQuery(**self.query)

def createQueryParser(parser):
    parser.description = """Example:

    adsquery query --first-author Einstein relativity
    adsquery query "Gravitational wave" --year 2015
    """
    query_param = parser.add_argument_group('Query parameters')

    query_param.add_argument(metavar='query', dest='q', type=str, nargs='*',
                             help='The search query. Can be either fielded (field:value) or unfielded (value).')
    query_param.add_argument('--rows', type=int, default=10,
                             help="number of results to return.")
    query_param.add_argument('--start', type=int, default=1,
                             help="starting point for returned results (for pagination).")
    query_param.add_argument('--fl', nargs='*',
                             help="Fields list: specify the fields contained in each returned document. Value should be a comma-separated list of field names.")
    query_param.add_argument('--fq',
                             help="Filter query: filter your results using a particular field:value condition. This parameter is repeatable.")
    query_param.add_argument('--sort', type=str, nargs=2, help='Foo')

    fields = parser.add_argument_group('Fields')
    fields.add_argument('--abstract',
                        help='the abstract of the record')
    fields.add_argument('--ack',
                        help='the acknowledgements section of an article')
    fields.add_argument('--aff',
                        help='an array of the authors affiliations')
    fields.add_argument('--alternate_bibcode',
                        help='list of alternate bibcodes for a single record')
    fields.add_argument('--alternate_title',
                        help='list of alternate titles for a single record (usually if they are in multiple languages)')
    fields.add_argument('--arxiv_class',
                        help='the arXiv class the pre-print was submitted to')
    fields.add_argument('--author',
                        help='an array of the author names associated with the record')
    fields.add_argument('--bibcode',
                        help='the canonical ADS bibcode identifier for this record')
    fields.add_argument('--bibgroup',
                        help='the bibliographic groups that the bibcode has been associated with')
    fields.add_argument('--bibstem',
                        help='the abbreviated name of the journal or publication, e.g., ApJ.')
    fields.add_argument('--body',
                        help='the full text content of the article')
    fields.add_argument('--citation_count',
                        help='number of citations the item has received')
    fields.add_argument('--copyright',
                        help='the copyright applied to the article')
    fields.add_argument('--data',
                        help='the list of sources that have data related to this bibcode')
    fields.add_argument('--database',
                        help='Which database the record is associated with.')
    fields.add_argument('--doi',
                        help='the digital object identifier of the article')
    fields.add_argument('--doctype',
                        help='the type of document it is (see here for a list of doctypes)')
    fields.add_argument('--first-author',
                        help='the first author of the article')
    fields.add_argument('--grant',
                        help='the list of grant IDs and agencies noted within an article')
    fields.add_argument('--id',
                        help='a (non-persistent) unique integer for this record, used for fast look-up of a document')
    fields.add_argument('--identifier',
                        help='an array of alternative identifiers for the record. May contain alternative bibcodes, DOIs and/or arxiv ids.')
    fields.add_argument('--indexstamp',
                        help='time at which the document was (last) indexed')
    fields.add_argument('--issue',
                        help='issue the record appeared in')
    fields.add_argument('--keyword',
                        help='an array of normalized and un-normalized keyword values associated with the record')
    fields.add_argument('--lang*',
                        help='the language of the article s title')
    fields.add_argument('--orcid-pub',
                        help='ORCiD iDs supplied by publishers')
    fields.add_argument('--orcid-user',
                        help='ORCiD iDs supplied by knonwn users in the ADS')
    fields.add_argument('--orcid-other',
                        help='ORCiD iDs supplied by anonymous users in the ADS')
    fields.add_argument('--page',
                        help='starting page')
    fields.add_argument('--property',
                        help='an array of miscellaneous flags associated with the record (see here for a list of properties')
    fields.add_argument('--pub',
                        help='the canonical name of the publication the record appeared in')
    fields.add_argument('--pubdate',
                        help='publication date in the form YYYY-MM-DD (DD value will always be "00")')
    fields.add_argument('--read-count',
                        help='number of times the record has been viewed within in a 90-day windows (ads and arxiv)')
    fields.add_argument('--title',
                        help='the title of the record')
    fields.add_argument('--vizier',
                        help='the subject tags given to the article by VizieR')
    fields.add_argument('--volume',
                        help='volume the record appeared in')
    fields.add_argument('--year',
                        help='the year the article was published')

def createGetParser(parser):
    """

    """
    parser.add_argument('--bibcode',
                        help='the canonical ADS bibcode identifier for this record')
    return

def createBibParser(parser):
    """

    """
    return

def printResults(results):
    for i, res in enumerate(results):

        # Format author
        if res.author is not None and len(res.author) > 3:
            authors = res.author[0] + ' et al. ({} more)'.format(len(res.author[1:]))
        elif res.author is None:
            authors = 'No author'
        else:
            authors = ', '.join(res.author)

        # Format journal
        pub = res.pub
        if pub in journalAbbrevs:
            pub = journalAbbrevs[pub]

        if pub is None:
            pub = '?'

        # Format year journal
        print('{c.HEADER}[{i}]: {c.OKGREEN}{year}, {pub} — {c.OKBLUE}{author}{c.ENDC}, {title}'.format(
            i=i, year=res.year, title=res.title[0], author=authors, c=bcolors, pub=pub))

def doQuery(args, **kwargs):
    query = BuildQuery()

    for key in vars(args):
        if key not in ['interactive', 'func']:
            query.setKey(key, vars(args)[key])
    for key in kwargs:
        if key not in ['interactive', 'func']:
            query.setKey(key, kwargs[key])

    # get results
    results = query.execute()

    res_as_array = []

    # loop over results
    res_as_array = [res for res in results]
    printResults(res_as_array)

    if len(res_as_array) == 0:
        print('No results')
        return

    if args.interactive or ('interactive' in kwargs and kwargs['interactive']):
        print('')
        inp = input('Comma separated articles to download [e.g. 1-3, 4] or [m] for more: ')
        # match any string like "5m", "10 more", …
        grp = re.match('(\d+) ?[mM](ore)?', inp)
        if grp is not None:
            nmore = int(grp.group(1))

            # load more
            if 'rows' in kwargs:
                kwargs['rows'] += nmore
            else:
                kwargs['rows'] = 10 + nmore

            doQuery(args, **kwargs)
            return

        mask = parseAsList(inp)
        papers = [r for i, r in enumerate(res_as_array) if i in mask]
        print('Selected:')
        printResults(papers)

        action = getInput(
            'Download [d], bibtex[b], quit[q]? ', lambda e: e.lower())

        # Download selected articles
        if 'd' in action:
            print('Downloading…')
            for paper in papers:
                print('Downloading "{}"'.format(paper.title[0]))
                downloadPaper(paper)

        # Get bibtex reference
        if 'b' in action:
            print('Bibentries…')
            bibtex = [p.bibtex for p in tqdm(papers)]
            print(''.join(bibtex))

        return papers
    else:
        return res_ar_array

def downloadPaper(paper):
    '''Download the paper.
    :arg paper
    a result given by the ads'''
    url = "http://adsabs.harvard.edu/cgi-bin/nph-data_query?bibcode={paper.bibcode}&link_type=ARTICLE".format(
        paper=paper)
    fname = '{paper.bibcode}_{author}.pdf'.format(
        paper=paper,
        author=paper.first_author.split(',')[0])
    fname = os.path.join('/home/ccc/ADS', fname)

    if not os.path.isfile(fname):
        r = requests.get(url, stream=True)

        with open(fname, 'wb') as f:
            try:
                total_length = int(r.headers.get('content-length'))
            except:
                total_length = -1
            for chunk in tqdm(r.iter_content(chunk_size=1024), total=(total_length / 1024)):
                if chunk:
                    f.write(chunk)
                    f.flush()

def getInput(help_string, parse_fun):
    valid = False
    while not valid:
        try:
            ret = input(help_string)
            ret_parsed = parse_fun(ret)
            valid = True
        except ValueError:
            valid = False

    return ret_parsed

def parseAsList(string):
    '''Parse the input as a list

    :param string
    the string to parse

    :return
    a list containing the input from the user
    '''
    # prompt for article to download
    dl_input = string

    # split around commas (with blanks)
    dl_input = re.split('\s?,\s?', dl_input)
    mask = []
    regexp = re.compile('(\d+)(-(\d+))?')
    for inp in dl_input:
        match = regexp.match(inp)
        if match is None:
            print('Invalid predicate `{}`'.format(inp))
            continue

        beg, end = match.group(1, 3)
        if end is None:
            mask.append(int(beg))
        else:
            mask += range(int(beg), int(end) + 1)
    return mask

def doGet(args):
    query = BuildQuery()
    for key in vars(args):
        query.setKey(key, vars(args)[key])

def doBib(args):
    pass

def main():
    parser = argparse.ArgumentParser(description='Get papers from the ADS')
    parser.add_argument('--no-interactive', help='Deactivate interaction',
                        dest='interactive', action='store_false')
    parser.add_argument('--token', type=str,
                        help='Your ADS token. Leave empty to use the value from ~/.ads/dev_key or from the environment variable ADS_DEV_KEY.',
                        default=None)

    subparsers = parser.add_subparsers()
    query_parser = subparsers.add_parser('query', description='Query the ADS')
    createQueryParser(query_parser)
    query_parser.set_defaults(func=doQuery)

    get_parser = subparsers.add_parser(
        'get', description='Get a paper from the ADS')
    createGetParser(get_parser)
    get_parser.set_defaults(func=doGet)

    bib_parser = subparsers.add_parser(
        'bib', description='Get bib data from the ADS')
    createBibParser(bib_parser)
    bib_parser.set_defaults(func=doBib)

    args = parser.parse_args()
    if 'q' in vars(args):
        args.q = ' '.join(args.q)

    try:
        return args.func(args)
    except AttributeError: # func not in namespace
        parser.print_help()
        return

if __name__ == '__main__':
    try:
        results = main()
    except KeyboardInterrupt:
        print('Interrupted via keyboard')
        pass
<commit_msg>add more possibilities!<commit_after># -*- coding: utf-8 -*-
# Python2 compat
from __future__ import unicode_literals, print_function, division
try:
    input = raw_input
except NameError: # python3
    pass

# Local imports
from definitions import journalAbbrevs, bcolors

# Imports
import ads
import argparse
# from gooey import Gooey
import re
import requests
from tqdm import tqdm
import os

# import codecs
# import sys

# UTF8Writer = codecs.getwriter('utf8')
# sys.stdout = UTF8Writer(sys.stdout)

class BuildQuery:

    def __init__(self):
        "Creates a build object query"
        self.query = dict()
        return

    def setKey(self, key, val):
        '''Set the key to val in the query'''
        if val is not None:
            self.query[key] = val

    def execute(self):
        return ads.SearchQuery(**self.query)

def createQueryParser(parser):
    parser.description = """Example:

    adsquery query --first-author Einstein relativity
    adsquery query "Gravitational wave" --year 2015
    """
    query_param = parser.add_argument_group('Query parameters')

    query_param.add_argument(metavar='query', dest='q', type=str, nargs='*',
                             help='The search query. Can be either fielded (field:value) or unfielded (value).')
    query_param.add_argument('--rows', type=int, default=10,
                             help="number of results to return.")
    query_param.add_argument('--start', type=int, default=1,
                             help="starting point for returned results (for pagination).")
    query_param.add_argument('--fl', nargs='*',
                             help="Fields list: specify the fields contained in each returned document. Value should be a comma-separated list of field names.")
    query_param.add_argument('--fq',
                             help="Filter query: filter your results using a particular field:value condition. This parameter is repeatable.")
    query_param.add_argument('--sort', type=str, nargs=2, help='Foo')

    fields = parser.add_argument_group('Fields')
    fields.add_argument('--abstract',
                        help='the abstract of the record')
    fields.add_argument('--ack',
                        help='the acknowledgements section of an article')
    fields.add_argument('--aff',
                        help='an array of the authors affiliations')
    fields.add_argument('--alternate_bibcode',
                        help='list of alternate bibcodes for a single record')
    fields.add_argument('--alternate_title',
                        help='list of alternate titles for a single record (usually if they are in multiple languages)')
    fields.add_argument('--arxiv_class',
                        help='the arXiv class the pre-print was submitted to')
    fields.add_argument('--author',
                        help='an array of the author names associated with the record')
    fields.add_argument('--bibcode',
                        help='the canonical ADS bibcode identifier for this record')
    fields.add_argument('--bibgroup',
                        help='the bibliographic groups that the bibcode has been associated with')
    fields.add_argument('--bibstem',
                        help='the abbreviated name of the journal or publication, e.g., ApJ.')
    fields.add_argument('--body',
                        help='the full text content of the article')
    fields.add_argument('--citation_count',
                        help='number of citations the item has received')
    fields.add_argument('--copyright',
                        help='the copyright applied to the article')
    fields.add_argument('--data',
                        help='the list of sources that have data related to this bibcode')
    fields.add_argument('--database',
                        help='Which database the record is associated with.')
    fields.add_argument('--doi',
                        help='the digital object identifier of the article')
    fields.add_argument('--doctype',
                        help='the type of document it is (see here for a list of doctypes)')
    fields.add_argument('--first-author',
                        help='the first author of the article')
    fields.add_argument('--grant',
                        help='the list of grant IDs and agencies noted within an article')
    fields.add_argument('--id',
                        help='a (non-persistent) unique integer for this record, used for fast look-up of a document')
    fields.add_argument('--identifier',
                        help='an array of alternative identifiers for the record. May contain alternative bibcodes, DOIs and/or arxiv ids.')
    fields.add_argument('--indexstamp',
                        help='time at which the document was (last) indexed')
    fields.add_argument('--issue',
                        help='issue the record appeared in')
    fields.add_argument('--keyword',
                        help='an array of normalized and un-normalized keyword values associated with the record')
    fields.add_argument('--lang*',
                        help='the language of the article s title')
    fields.add_argument('--orcid-pub',
                        help='ORCiD iDs supplied by publishers')
    fields.add_argument('--orcid-user',
                        help='ORCiD iDs supplied by knonwn users in the ADS')
    fields.add_argument('--orcid-other',
                        help='ORCiD iDs supplied by anonymous users in the ADS')
    fields.add_argument('--page',
                        help='starting page')
    fields.add_argument('--property',
                        help='an array of miscellaneous flags associated with the record (see here for a list of properties')
    fields.add_argument('--pub',
                        help='the canonical name of the publication the record appeared in')
    fields.add_argument('--pubdate',
                        help='publication date in the form YYYY-MM-DD (DD value will always be "00")')
    fields.add_argument('--read-count',
                        help='number of times the record has been viewed within in a 90-day windows (ads and arxiv)')
    fields.add_argument('--title',
                        help='the title of the record')
    fields.add_argument('--vizier',
                        help='the subject tags given to the article by VizieR')
    fields.add_argument('--volume',
                        help='volume the record appeared in')
    fields.add_argument('--year',
                        help='the year the article was published')

def createGetParser(parser):
    """

    """
    parser.add_argument('--bibcode',
                        help='the canonical ADS bibcode identifier for this record')
    return

def createBibParser(parser):
    """

    """
    return

def printResults(results):
    for i, res in enumerate(results):

        # Format author
        if res.author is not None and len(res.author) > 3:
            authors = res.author[0] + ' et al. ({} more)'.format(len(res.author[1:]))
        elif res.author is None:
            authors = 'No author'
        else:
            authors = ', '.join(res.author)

        # Format journal
        pub = res.pub
        if pub in journalAbbrevs:
            pub = journalAbbrevs[pub]

        if pub is None:
            pub = '?'

        # Format year journal
        print('{c.HEADER}[{i}]: {c.OKGREEN}{year}, {pub} — {c.OKBLUE}{author}{c.ENDC}, {title}'.format(
            i=i, year=res.year, title=res.title[0], author=authors, c=bcolors, pub=pub))

def doQuery(args, **kwargs):
    query = BuildQuery()

    for key in vars(args):
        if key not in ['interactive', 'func']:
            query.setKey(key, vars(args)[key])
    for key in kwargs:
        if key not in ['interactive', 'func']:
            query.setKey(key, kwargs[key])

    # get results
    results = query.execute()

    res_as_array = []

    # loop over results
    res_as_array = [res for res in results]
    printResults(res_as_array)

    if len(res_as_array) == 0:
        print('No results')
        return

    if args.interactive or ('interactive' in kwargs and kwargs['interactive']):
        print('')
        inp = input('Comma separated articles to download [e.g. 1-3, 4], [m] for more [q] to quit or add more parameters to request [e.g. year:2016]: ')

        # Match quit request
        if inp == 'q':
            return

        # Match requests for more articles
        # match any string like "5m", "10 more", …
        grp = re.match('(\d+) ?[mM](ore)?', inp)
        if grp is not None:
            nmore = int(grp.group(1))

            # load more
            if 'rows' in kwargs:
                kwargs['rows'] += nmore
            else:
                kwargs['rows'] = 10 + nmore

            print('Loading {} more!'.format(nmore))
            doQuery(args, **kwargs)
            return

        # Match selection
        mask = parseAsList(inp)
        if len(mask) > 0:
            papers = [r for i, r in enumerate(res_as_array) if i in mask]
            print('Selected:')
            printResults(papers)

            action = getInput(
                'Download [d], bibtex[b], quit[q]? ', lambda e: e.lower())

            # Download selected articles
            if 'd' in action:
                for paper in papers:
                    print('Downloading "{}"'.format(paper.title[0]))
                    downloadPaper(paper)

            # Get bibtex reference
            if 'b' in action:
                print('Downloading bibtex entries')
                bibtex = [p.bibtex for p in tqdm(papers)]
                print(''.join(bibtex))

            return papers
        else: # match more request
            if args.q is not None:
                args.q = args.q + ' ' + inp
            elif 'q' in kwargs:
                kwargs['q'] += ' ' + inp
            else:
                kwargs['q'] = inp
            doQuery(args, **kwargs)
            return
    else:
        return res_ar_array

def downloadPaper(paper):
    '''Download the paper.
    :arg paper
    a result given by the ads'''
    url = "http://adsabs.harvard.edu/cgi-bin/nph-data_query?bibcode={paper.bibcode}&link_type=ARTICLE".format(
        paper=paper)
    fname = '{paper.bibcode}_{author}.pdf'.format(
        paper=paper,
        author=paper.first_author.split(',')[0])
    fname = os.path.join('/home/ccc/ADS', fname)

    if not os.path.isfile(fname):
        r = requests.get(url, stream=True)

        with open(fname, 'wb') as f:
            try:
                total_length = int(r.headers.get('content-length'))
            except:
                total_length = -1
            for chunk in tqdm(r.iter_content(chunk_size=1024), total=(total_length / 1024)):
                if chunk:
                    f.write(chunk)
                    f.flush()

def getInput(help_string, parse_fun):
    valid = False
    while not valid:
        try:
            ret = input(help_string)
            ret_parsed = parse_fun(ret)
            valid = True
        except ValueError:
            valid = False

    return ret_parsed

def parseAsList(string):
    '''Parse the input as a list

    :param string
    the string to parse

    :return
    a list containing the input from the user
    '''
    # prompt for article to download
    dl_input = string

    # split around commas (with blanks)
    dl_input = re.split('\s?,\s?', dl_input)
    mask = []
    regexp = re.compile('(\d+)(-(\d+))?')
    for inp in dl_input:
        match = regexp.match(inp)
        if match is None:
            return []

        beg, end = match.group(1, 3)
        if end is None:
            mask.append(int(beg))
        else:
            mask += range(int(beg), int(end) + 1)
    return mask

def doGet(args):
    query = BuildQuery()
    for key in vars(args):
        query.setKey(key, vars(args)[key])

def doBib(args):
    pass

def main():
    parser = argparse.ArgumentParser(description='Get papers from the ADS')
    parser.add_argument('--no-interactive', help='Deactivate interaction',
                        dest='interactive', action='store_false')
    parser.add_argument('--token', type=str,
                        help='Your ADS token. Leave empty to use the value from ~/.ads/dev_key or from the environment variable ADS_DEV_KEY.',
                        default=None)

    subparsers = parser.add_subparsers()
    query_parser = subparsers.add_parser('query', description='Query the ADS')
    createQueryParser(query_parser)
    query_parser.set_defaults(func=doQuery)

    get_parser = subparsers.add_parser(
        'get', description='Get a paper from the ADS')
    createGetParser(get_parser)
    get_parser.set_defaults(func=doGet)

    bib_parser = subparsers.add_parser(
        'bib', description='Get bib data from the ADS')
    createBibParser(bib_parser)
    bib_parser.set_defaults(func=doBib)

    args = parser.parse_args()
    if 'q' in vars(args):
        args.q = ' '.join(args.q)

    try:
        return args.func(args)
    except AttributeError: # func not in namespace
        parser.print_help()
        return

if __name__ == '__main__':
    try:
        results = main()
    except KeyboardInterrupt:
        print('Interrupted via keyboard')
        pass
<|endoftext|>


<commit_before>#!/usr/bin/env python

from soccerpy.agent import Agent as baseAgent
from soccerpy.world_model import WorldModel

# methods from actionHandler are
# CATCH = "catch"(rel_direction)
# CHANGE_VIEW = "change_view"
# DASH = "dash"(power)
# KICK = "kick"(power, rel_direction)
# MOVE = "move"(x,y) only pregame
# SAY = "say"(you_can_try_cursing)
# SENSE_BODY = "sense_body"
# TURN = "turn"(rel_degrees in 360)
# TURN_NECK = "turn_neck"(rel_direction)

# potentially useful from aima
# learning.py
# mdp
#

class Agent(baseAgent):
    """
    The extended Agent class with specific heuritics
    """

    def think(self):
        """
        Performs a single step of thinking for our agent.  Gets called on every
        iteration of our think loop.
        """

        # DEBUG:  tells us if a thread dies
        if not self.__think_thread.is_alive() or not self.__msg_thread.is_alive():
            raise Exception("A thread died.")

        # take places on the field by uniform number
        if not self.in_kick_off_formation:

            # used to flip x coords for other side
            side_mod = 1
            if self.wm.side == WorldModel.SIDE_R:
                side_mod = -1

            if self.wm.uniform_number == 1:
                self.wm.teleport_to_point((-5 * side_mod, 30))
            elif self.wm.uniform_number == 2:
                self.wm.teleport_to_point((-40 * side_mod, 15))
            elif self.wm.uniform_number == 3:
                self.wm.teleport_to_point((-40 * side_mod, 00))
            elif self.wm.uniform_number == 4:
                self.wm.teleport_to_point((-40 * side_mod, -15))
            elif self.wm.uniform_number == 5:
                self.wm.teleport_to_point((-5 * side_mod, -30))
            elif self.wm.uniform_number == 6:
                self.wm.teleport_to_point((-20 * side_mod, 20))
            elif self.wm.uniform_number == 7:
                self.wm.teleport_to_point((-20 * side_mod, 0))
            elif self.wm.uniform_number == 8:
                self.wm.teleport_to_point((-20 * side_mod, -20))
            elif self.wm.uniform_number == 9:
                self.wm.teleport_to_point((-10 * side_mod, 0))
            elif self.wm.uniform_number == 10:
                self.wm.teleport_to_point((-10 * side_mod, 20))
            elif self.wm.uniform_number == 11:
                self.wm.teleport_to_point((-10 * side_mod, -20))

            self.in_kick_off_formation = True

            return

        else:
            # determine the enemy goal position
            self.enemy_goal_pos = None
            self.own_goal_pos = None
            if self.wm.side == WorldModel.SIDE_R:
                self.enemy_goal_pos = (-55, 0)
                self.own_goal_pos = (55, 0)
            else:
                self.enemy_goal_pos = (55, 0)
                self.own_goal_pos = (-55, 0)

            # The main decision loop
            return self.decisionLoop()

        # # kick off!
        # if self.wm.is_before_kick_off():
        #     # player 9 takes the kick off
        #     if self.wm.uniform_number == 9:
        #         if self.wm.is_ball_kickable():
        #             # kick with 100% extra effort at enemy goal
        #             self.wm.kick_to(self.enemy_goal_pos, 1.0)
        #         else:
        #             # move towards ball
        #             if self.wm.ball is not None:
        #                 if (self.wm.ball.direction is not None and
        #                     -7 <= self.wm.ball.direction <= 7):
        #                     self.wm.ah.dash(50)
        #             else:
        #                 self.wm.turn_body_to_point((0, 0))

        #         # turn to ball if we can see it, else face the enemy goal
        #         if self.wm.ball is not None:
        #             self.wm.turn_neck_to_object(self.wm.ball)

        #             return

        # # attack!
        # else:
            # # find the ball
            # if self.wm.ball is None or self.wm.ball.direction is None:
            #     self.wm.ah.turn(30)

            #     return

            # # kick it at the enemy goal
            # if self.wm.is_ball_kickable():
            #     self.wm.kick_to(self.enemy_goal_pos, 1.0)
            #     return
            # else:
            #     # move towards ball
            #     if -7 <= self.wm.ball.direction <= 7:
            #         self.wm.ah.dash(65)
            #     else:
            #         # face ball
            #         self.wm.ah.turn(self.wm.ball.direction / 2)

            #         return

    # Heuristics begin

    # check if ball is close to self
    def ball_close(self):
        return self.wm.ball.distance < 10

    # check if enemy goalpost is close enough
    def goalpos_close(self):
        return self.wm.get_distance_to_point(self.enemy_goal_pos) < 20

    # check if path to target's coordinate is clear, by direction
    def is_clear(self, target_coords):
        q = self.wm.get_nearest_enemy()
        q_coords = self.wm.get_object_absolute_coords(q)
        qDir = self.wm.get_direction_to_point(q_coords)
        qDist = self.wm.get_distance_to_point(q_coords)

        tDir = self.wm.get_direction_to_point(target_coords)
        tDist = self.wm.get_distance_to_point(target_coords)

        # the closest teammate is closer, or angle is clear
        return tDist < qDist or abs(qDir - tDir) > 20

    # Action decisions start
    #
    # find the ball by rotating if ball not found
    def find_ball(self):
        # find the ball`
        if self.wm.ball is None or self.wm.ball.direction is None:
            self.wm.ah.turn(10)
            self.wm.align_neck_with_body()

    # condition for shooting to the goal
    def shall_shoot(self):
        return self.wm.is_ball_kickable() and self.goal_pos_close() and self.is_clear(self.enemy_goal_pos)

    # do shoot
    def shoot(self):
        return self.wm.kick_to(self.enemy_goal_pos, 1.0)

    # condition for passing to the closest teammate
    # if can kick ball, teammate is closer to goal, path clear
    def shall_pass(self):
        p = self.wm.get_nearest_teammate()
        p_coords = self.wm.get_object_absolute_coords(p)
        pDistToGoal = self.wm.euclidean_distance(p_coords, self.enemy_goal_pos)
        myDistToGoal = self.wm.get_distance_to_point(self.enemy_goal_pos)
        # kickable, pass closer to goal, path is clear
        return self.wm.is_ball_kickable() and pDistToGoal < myDistToGoal and self.is_clear(p_coords)

    # do passes
    def passes(self):
        p = self.wm.get_nearest_teammate()
        p_coords = self.wm.get_object_absolute_coords(p)
        dist = self.wm.get_distance_to_point(p_coords)
        power_ratio = 2*dist/55.0
        # kick to closest teammate, power is scaled
        return self.wm.kick_to(p_coords, power_ratio)

    # condition for dribbling, if can't shoot or pass
    def shall_dribble(self):
        return self.wm.is_ball_kickable()

    # dribble: turn body, kick, then run towards ball
    def dribble(self):
        self.wm.turn_body_to_point(self.enemy_goal_pos)
        self.wm.align_neck_with_body()
        self.wm.kick_to(self.enemy_goal_pos, 0.3)
        self.wm.ah.dash(50)
        return

    # if enemy has the ball, and not too far move towards it
    def shall_move_to_ball(self):
        while self.wm.ball is None or self.wm.ball.direction is None:
            self.find_ball()
        self.wm.align_neck_with_body()
        return self.wm.is_ball_owned_by_enemy() and self.wm.ball.distance < 30

    # move to ball, if enemy owns it
    def move_to_ball(self):
        self.wm.ah.dash(60)
        return

    # defensive, when ball isn't ours, and has entered our side of the field
    def shall_move_to_defend(self):
        if self.wm.ball is not None or self.wm.ball.direction is not None:
            b_coords = self.wm.get_object_absolute_coords(self.ball)
            return self.wm.is_ball_owned_by_enemy() and self.wm.euclidean_distance(self.own_goal_pos, b_coords) < 55.0
        return False

    # defend
    def move_to_defend(self):
        q = self.wm.get_nearest_enemy()
        q_coords = self.wm.get_object_absolute_coords(q)
        qDir = self.wm.get_direction_to_point(q_coords)
        qDistToOurGoal = self.wm.euclidean_distance(self.own_goal_pos, q_coords)
        # if close to the goal, aim at it
        if q.wm.is_ball_kickable() or qDistToOurGoal < 55:
            self.wm.turn_body_to_point(q_coords)
        # otherwise aim at own goalpos, run there to defend
        else:
            self.wm.turn_body_to_point(self.own_goal_pos)

        self.wm.align_neck_with_body()
        self.wm.ah.dash(80)
        return

    # when our team has ball, and self is not close enough to goalpos. advance to enemy goalpos
    def shall_move_to_enemy_goalpos(self):
        return self.wm.is_ball_owned_by_us() and not self.goalpos_close()

    # if our team has the ball n u r striker
    def move_to_enemy_goalpos(self):
        self.wm.turn_body_to_point(self.enemy_goal_pos)
        self.wm.align_neck_with_body()
        self.wm.ah.dash(70)
        return

    def decisionLoop(self):
        self.find_ball()
        # if should shoot, full power
        if self.shall_shoot():
            return self.shoot()
        # else shd pass to closest teammate
        elif self.shall_pass():
            return self.passes()
        # else shd dribble
        elif self.shall_dribble():
            return self.dribble()
        elif self.shall_move_to_ball():
            return self.move_to_ball()
        elif self.shall_move_to_defend():
            return move_to_defend()
        elif shall_move_to_enemy_goalpos():
            return move_to_enemy_goalpos()
        return

# by role: striker, defender
# do the same preconds, but def on role diff actions
# 1.
# shoot:
# close enuf to ball and to self.enemy_goal_pos
# if self.wm.ball.distance < 10 and self.get_distance_to_point(self.enemy_goal_pos) < 20 and self.is_ball_kickable():

# shoot
# pass
# move

# striker:
#

# strategy: ordered
# 1. close to ball: grab, carry toward goal, pass or shoot
# 2. ain't, move to enemy (if enemy has ball), goal (if we have ball n jersey num), ball (if enemy n closest, or jersey num)
# 3.

# conditions shd be:
# shoot: ball aint none, ball kickable, close to goalpos

# Enum fields
# self.get_distance_to_point(self.enemy_goal_pos)
# self.get_direction_to_point(self.enemy_goal_pos)
# self.wm.ball.distance
# self.wm.ball.direction
# p = self.get_nearest_teammate()
# p.distance
# p.direction
# q = self.get_neatest_enemy()
# q.distance
# q.direction
# self.is_ball_owned_by_us
# self.is_ball_owned_by_enemy
# self.is_ball_kickable

# actions and their triggers
# shoot
# pass
# move

# print dir(WorldModel(''))
# print dir(Agent())
<commit_msg>control by not b4 kickoff<commit_after>#!/usr/bin/env python

from soccerpy.agent import Agent as baseAgent
from soccerpy.world_model import WorldModel

# methods from actionHandler are
# CATCH = "catch"(rel_direction)
# CHANGE_VIEW = "change_view"
# DASH = "dash"(power)
# KICK = "kick"(power, rel_direction)
# MOVE = "move"(x,y) only pregame
# SAY = "say"(you_can_try_cursing)
# SENSE_BODY = "sense_body"
# TURN = "turn"(rel_degrees in 360)
# TURN_NECK = "turn_neck"(rel_direction)

# potentially useful from aima
# learning.py
# mdp
#

class Agent(baseAgent):
    """
    The extended Agent class with specific heuritics
    """

    def think(self):
        """
        Performs a single step of thinking for our agent.  Gets called on every
        iteration of our think loop.
        """

        # DEBUG:  tells us if a thread dies
        if not self.__think_thread.is_alive() or not self.__msg_thread.is_alive():
            raise Exception("A thread died.")

        # take places on the field by uniform number
        if not self.in_kick_off_formation:

            # used to flip x coords for other side
            side_mod = 1
            if self.wm.side == WorldModel.SIDE_R:
                side_mod = -1

            if self.wm.uniform_number == 1:
                self.wm.teleport_to_point((-5 * side_mod, 30))
            elif self.wm.uniform_number == 2:
                self.wm.teleport_to_point((-40 * side_mod, 15))
            elif self.wm.uniform_number == 3:
                self.wm.teleport_to_point((-40 * side_mod, 00))
            elif self.wm.uniform_number == 4:
                self.wm.teleport_to_point((-40 * side_mod, -15))
            elif self.wm.uniform_number == 5:
                self.wm.teleport_to_point((-5 * side_mod, -30))
            elif self.wm.uniform_number == 6:
                self.wm.teleport_to_point((-20 * side_mod, 20))
            elif self.wm.uniform_number == 7:
                self.wm.teleport_to_point((-20 * side_mod, 0))
            elif self.wm.uniform_number == 8:
                self.wm.teleport_to_point((-20 * side_mod, -20))
            elif self.wm.uniform_number == 9:
                self.wm.teleport_to_point((-10 * side_mod, 0))
            elif self.wm.uniform_number == 10:
                self.wm.teleport_to_point((-10 * side_mod, 20))
            elif self.wm.uniform_number == 11:
                self.wm.teleport_to_point((-10 * side_mod, -20))

            self.in_kick_off_formation = True

            return

        # determine the enemy goal position
        self.enemy_goal_pos = None
        self.own_goal_pos = None
        if self.wm.side == WorldModel.SIDE_R:
            self.enemy_goal_pos = (-55, 0)
            self.own_goal_pos = (55, 0)
        else:
            self.enemy_goal_pos = (55, 0)
            self.own_goal_pos = (-55, 0)

        if not self.is_before_kick_off()
            # The main decision loop
            return self.decisionLoop()

        # # kick off!
        # if self.wm.is_before_kick_off():
        #     # player 9 takes the kick off
        #     if self.wm.uniform_number == 9:
        #         if self.wm.is_ball_kickable():
        #             # kick with 100% extra effort at enemy goal
        #             self.wm.kick_to(self.enemy_goal_pos, 1.0)
        #         else:
        #             # move towards ball
        #             if self.wm.ball is not None:
        #                 if (self.wm.ball.direction is not None and
        #                     -7 <= self.wm.ball.direction <= 7):
        #                     self.wm.ah.dash(50)
        #             else:
        #                 self.wm.turn_body_to_point((0, 0))

        #         # turn to ball if we can see it, else face the enemy goal
        #         if self.wm.ball is not None:
        #             self.wm.turn_neck_to_object(self.wm.ball)

        #             return

        # # attack!
        # else:
            # # find the ball
            # if self.wm.ball is None or self.wm.ball.direction is None:
            #     self.wm.ah.turn(30)

            #     return

            # # kick it at the enemy goal
            # if self.wm.is_ball_kickable():
            #     self.wm.kick_to(self.enemy_goal_pos, 1.0)
            #     return
            # else:
            #     # move towards ball
            #     if -7 <= self.wm.ball.direction <= 7:
            #         self.wm.ah.dash(65)
            #     else:
            #         # face ball
            #         self.wm.ah.turn(self.wm.ball.direction / 2)

            #         return

    # Heuristics begin

    # check if ball is close to self
    def ball_close(self):
        return self.wm.ball.distance < 10

    # check if enemy goalpost is close enough
    def goalpos_close(self):
        return self.wm.get_distance_to_point(self.enemy_goal_pos) < 20

    # check if path to target's coordinate is clear, by direction
    def is_clear(self, target_coords):
        q = self.wm.get_nearest_enemy()
        q_coords = self.wm.get_object_absolute_coords(q)
        qDir = self.wm.get_direction_to_point(q_coords)
        qDist = self.wm.get_distance_to_point(q_coords)

        tDir = self.wm.get_direction_to_point(target_coords)
        tDist = self.wm.get_distance_to_point(target_coords)

        # the closest teammate is closer, or angle is clear
        return tDist < qDist or abs(qDir - tDir) > 20

    # Action decisions start
    #
    # find the ball by rotating if ball not found
    def find_ball(self):
        # find the ball`
        if self.wm.ball is None or self.wm.ball.direction is None:
            self.wm.ah.turn(10)
            self.wm.align_neck_with_body()

    # condition for shooting to the goal
    def shall_shoot(self):
        return self.wm.is_ball_kickable() and self.goal_pos_close() and self.is_clear(self.enemy_goal_pos)

    # do shoot
    def shoot(self):
        return self.wm.kick_to(self.enemy_goal_pos, 1.0)

    # condition for passing to the closest teammate
    # if can kick ball, teammate is closer to goal, path clear
    def shall_pass(self):
        p = self.wm.get_nearest_teammate()
        p_coords = self.wm.get_object_absolute_coords(p)
        pDistToGoal = self.wm.euclidean_distance(p_coords, self.enemy_goal_pos)
        myDistToGoal = self.wm.get_distance_to_point(self.enemy_goal_pos)
        # kickable, pass closer to goal, path is clear
        return self.wm.is_ball_kickable() and pDistToGoal < myDistToGoal and self.is_clear(p_coords)

    # do passes
    def passes(self):
        p = self.wm.get_nearest_teammate()
        p_coords = self.wm.get_object_absolute_coords(p)
        dist = self.wm.get_distance_to_point(p_coords)
        power_ratio = 2*dist/55.0
        # kick to closest teammate, power is scaled
        return self.wm.kick_to(p_coords, power_ratio)

    # condition for dribbling, if can't shoot or pass
    def shall_dribble(self):
        return self.wm.is_ball_kickable()

    # dribble: turn body, kick, then run towards ball
    def dribble(self):
        self.wm.turn_body_to_point(self.enemy_goal_pos)
        self.wm.align_neck_with_body()
        self.wm.kick_to(self.enemy_goal_pos, 0.3)
        self.wm.ah.dash(50)
        return

    # if enemy has the ball, and not too far move towards it
    def shall_move_to_ball(self):
        while self.wm.ball is None or self.wm.ball.direction is None:
            self.find_ball()
        self.wm.align_neck_with_body()
        return self.wm.is_ball_owned_by_enemy() and self.wm.ball.distance < 30

    # move to ball, if enemy owns it
    def move_to_ball(self):
        self.wm.ah.dash(60)
        return

    # defensive, when ball isn't ours, and has entered our side of the field
    def shall_move_to_defend(self):
        if self.wm.ball is not None or self.wm.ball.direction is not None:
            b_coords = self.wm.get_object_absolute_coords(self.ball)
            return self.wm.is_ball_owned_by_enemy() and self.wm.euclidean_distance(self.own_goal_pos, b_coords) < 55.0
        return False

    # defend
    def move_to_defend(self):
        q = self.wm.get_nearest_enemy()
        q_coords = self.wm.get_object_absolute_coords(q)
        qDir = self.wm.get_direction_to_point(q_coords)
        qDistToOurGoal = self.wm.euclidean_distance(self.own_goal_pos, q_coords)
        # if close to the goal, aim at it
        if q.wm.is_ball_kickable() or qDistToOurGoal < 55:
            self.wm.turn_body_to_point(q_coords)
        # otherwise aim at own goalpos, run there to defend
        else:
            self.wm.turn_body_to_point(self.own_goal_pos)

        self.wm.align_neck_with_body()
        self.wm.ah.dash(80)
        return

    # when our team has ball, and self is not close enough to goalpos. advance to enemy goalpos
    def shall_move_to_enemy_goalpos(self):
        return self.wm.is_ball_owned_by_us() and not self.goalpos_close()

    # if our team has the ball n u r striker
    def move_to_enemy_goalpos(self):
        self.wm.turn_body_to_point(self.enemy_goal_pos)
        self.wm.align_neck_with_body()
        self.wm.ah.dash(70)
        return

    def decisionLoop(self):
        self.find_ball()
        # if should shoot, full power
        if self.shall_shoot():
            return self.shoot()
        # else shd pass to closest teammate
        elif self.shall_pass():
            return self.passes()
        # else shd dribble
        elif self.shall_dribble():
            return self.dribble()
        elif self.shall_move_to_ball():
            return self.move_to_ball()
        elif self.shall_move_to_defend():
            return move_to_defend()
        elif shall_move_to_enemy_goalpos():
            return move_to_enemy_goalpos()
        return

# by role: striker, defender
# do the same preconds, but def on role diff actions
# 1.
# shoot:
# close enuf to ball and to self.enemy_goal_pos
# if self.wm.ball.distance < 10 and self.get_distance_to_point(self.enemy_goal_pos) < 20 and self.is_ball_kickable():

# shoot
# pass
# move

# striker:
#

# strategy: ordered
# 1. close to ball: grab, carry toward goal, pass or shoot
# 2. ain't, move to enemy (if enemy has ball), goal (if we have ball n jersey num), ball (if enemy n closest, or jersey num)
# 3.

# conditions shd be:
# shoot: ball aint none, ball kickable, close to goalpos

# Enum fields
# self.get_distance_to_point(self.enemy_goal_pos)
# self.get_direction_to_point(self.enemy_goal_pos)
# self.wm.ball.distance
# self.wm.ball.direction
# p = self.get_nearest_teammate()
# p.distance
# p.direction
# q = self.get_neatest_enemy()
# q.distance
# q.direction
# self.is_ball_owned_by_us
# self.is_ball_owned_by_enemy
# self.is_ball_kickable

# actions and their triggers
# shoot
# pass
# move

# print dir(WorldModel(''))
# print dir(Agent())
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
"""
    longboxed.manage.comics
    ~~~~~~~~~~~~~~~~~~~~~~~

    comic management commands
"""
import csv
from datetime import datetime
from StringIO import StringIO
from gzip import GzipFile
from csv import DictReader
from copy import deepcopy

import requests

from flask import current_app
from flask.ext.script import Command, Option, prompt, prompt_bool

from ..helpers import mail_content
from ..importer import DailyDownloadImporter, DailyDownloadRecord, WeeklyReleasesImporter, WeeklyReleaseRecord
from ..services import comics
from ..models import Creator, Issue, Title, Publisher

class TestCommand(Command):
    def run(self):
        base_url = 'http://www.tfaw.com/intranet/download-8908-daily.php'
        payload = {
            'aid': current_app.config['AFFILIATE_ID'],
            't': '',
            'z': 'gz'
        }
        r = requests.get(base_url, params=payload)

        fieldnames = [x[2] for x in current_app.config['CSV_RULES']]
        with GzipFile(fileobj=StringIO(r.content)) as f:
            reader = DictReader(f, fieldnames=fieldnames, delimiter='|')
            data = [row for row in reader]

        try:
            for record in data:
                if Issue.check_record_relevancy(record, current_app.config['SUPPORTED_PUBS'], 7):
                    r1 = deepcopy(record)
                    r2 = deepcopy(record)
                    r3 = deepcopy(record)
                    r4 = deepcopy(record)

                    publisher = Publisher.from_raw(r1)
                    title = Title.from_raw(r2)
                    issue = Issue.from_raw(r3)
                    creators = Creator.from_raw(r4)

                    if title and publisher:
                        title.publisher = publisher
                        title.save()

                    if issue and title:
                        issue.title = title
                    if issue and publisher:
                        issue.publisher = publisher
                    if issue and creators:
                        issue.creators = creators
                    issue.save()
        except:
            print record
                    # Issue.check_parent_status(issue.title, issue.issue_number)

                    # break

        return None

class ScheduleReleasesCommand(Command):
    def get_options(self):
        return [
            Option('-w', '--week', dest='week', required=True, choices=['thisweek', 'nextweek', 'twoweeks']),
        ]

    def run(self, week):
        release_instance = WeeklyReleasesImporter(
            week=week,
            affiliate_id=current_app.config['AFFILIATE_ID'],
            supported_publishers=current_app.config['SUPPORTED_DIAMOND_PUBS'],
            csv_rules=current_app.config['RELEASE_CSV_RULES'],
            record=WeeklyReleaseRecord
        )
        scheduled_releases = release_instance.run()
        return

class ImportDatabase(Command):
    def get_options(self):
        return [
            Option('--days', '-d', dest='days', default=21, type=int)
        ]

    def run(self, days):
        print 'Importing the next %d days worth of comic books...' % days
        import_instance = DailyDownloadImporter(
            days=days,
            affiliate_id=current_app.config['AFFILIATE_ID'],
            supported_publishers=current_app.config['SUPPORTED_PUBS'],
            csv_rules=current_app.config['CSV_RULES'],
            record=DailyDownloadRecord
        )
        imported_issues = import_instance.run()
        return

class SetCoverImageCommand(Command):
    """
    Sets the cover image of an issue. The issues is found in the
    database with a diamond id. If the issue already has an image
    attached, you can optionally choose to replace it.
    """
    def run(self):
        diamond_id = prompt('Issue Diamond id')
        # issue = comics.issues.first(diamond_id=diamond_id)
        issue = Issue.query.filter_by(diamond_id=diamond_id).first()
        if issue:
            url = prompt('Url of jpg image for cover image')
            overwrite = False
            if issue.cover_image.original:
                print 'Issue object already has a cover image set.'
                overwrite = prompt_bool('Overwrite existing picture?')
            # success = comics.issues.set_cover_image_from_url(issue, url, overwrite)
            success = issue.set_cover_image_from_url(url, overwrite=overwrite)
            if success:
                print 'Successfully set cover image'
            return
        print 'No issue found!'
        return

class CrossCheckCommand(Command):
    """
    Cross checks releases with items in database and mails missing
    issues to a provided email address
    """

    def get_options(self):
        return [
            Option('-w', '--week', dest='week', required=True, choices=['thisweek', 'nextweek', 'twoweeks']),
            Option('-e', '--email', dest='email', default='timbueno@gmail.com')
        ]

    def run(self, email, week):
        if week == 'twoweeks':
            raise NotImplementedError
        content = comics.get_shipping_from_TFAW(week)
        shipping = comics.get_issue_dict_shipping(content)
        not_in_db = [i for i in shipping if not comics.issues.first(diamond_id=i['ITEMCODE'])]
        not_in_db = sorted(not_in_db, key=lambda x: x['Vendor'])
        f = StringIO()
        ordered_fieldnames = ['ITEMCODE', 'DiscountCode', 'TITLE', 'Vendor', 'PRICE']
        outcsv = csv.DictWriter(f, fieldnames=ordered_fieldnames, delimiter='\t')
        for i in not_in_db:
            outcsv.writerow(i)
        mail_content([email], 'checker@longboxed.com', 'Testing', 'Attached is your checks', f.getvalue())
        f.close()
        return

class UpdateDatabaseCommand(Command):
    """Updates database with TFAW Daily Download"""

    def get_options(self):
        return [
            Option('-d','--days', dest='days', required=True)
        ]

    def run(self, days):
        print 'Starting update'
        days = int(days)
        comics.add_new_issues_to_database(days=days)
        print 'Done Adding to DB'<commit_msg>parent status was added to importer check<commit_after># -*- coding: utf-8 -*-
"""
    longboxed.manage.comics
    ~~~~~~~~~~~~~~~~~~~~~~~

    comic management commands
"""
import csv
from datetime import datetime
from StringIO import StringIO
from gzip import GzipFile
from csv import DictReader
from copy import deepcopy

import requests

from flask import current_app
from flask.ext.script import Command, Option, prompt, prompt_bool

from ..helpers import mail_content
from ..importer import DailyDownloadImporter, DailyDownloadRecord, WeeklyReleasesImporter, WeeklyReleaseRecord
from ..services import comics
from ..models import Creator, Issue, Title, Publisher

class TestCommand(Command):
    def run(self):
        base_url = 'http://www.tfaw.com/intranet/download-8908-daily.php'
        payload = {
            'aid': current_app.config['AFFILIATE_ID'],
            't': '',
            'z': 'gz'
        }
        r = requests.get(base_url, params=payload)

        fieldnames = [x[2] for x in current_app.config['CSV_RULES']]
        with GzipFile(fileobj=StringIO(r.content)) as f:
            reader = DictReader(f, fieldnames=fieldnames, delimiter='|')
            data = [row for row in reader]

        try:
            for record in data:
                if Issue.check_record_relevancy(record, current_app.config['SUPPORTED_PUBS'], 7):
                    r1 = deepcopy(record)
                    r2 = deepcopy(record)
                    r3 = deepcopy(record)
                    r4 = deepcopy(record)

                    publisher = Publisher.from_raw(r1)
                    title = Title.from_raw(r2)
                    issue = Issue.from_raw(r3)
                    creators = Creator.from_raw(r4)

                    if title and publisher:
                        title.publisher = publisher
                        title.save()

                    if issue and title:
                        issue.title = title
                    if issue and publisher:
                        issue.publisher = publisher
                    if issue and creators:
                        issue.creators = creators
                    issue.save()

                    Issue.check_parent_status(issue.title, issue.issue_number)
        except:
            print record

        return None

class ScheduleReleasesCommand(Command):
    def get_options(self):
        return [
            Option('-w', '--week', dest='week', required=True, choices=['thisweek', 'nextweek', 'twoweeks']),
        ]

    def run(self, week):
        release_instance = WeeklyReleasesImporter(
            week=week,
            affiliate_id=current_app.config['AFFILIATE_ID'],
            supported_publishers=current_app.config['SUPPORTED_DIAMOND_PUBS'],
            csv_rules=current_app.config['RELEASE_CSV_RULES'],
            record=WeeklyReleaseRecord
        )
        scheduled_releases = release_instance.run()
        return

class ImportDatabase(Command):
    def get_options(self):
        return [
            Option('--days', '-d', dest='days', default=21, type=int)
        ]

    def run(self, days):
        print 'Importing the next %d days worth of comic books...' % days
        import_instance = DailyDownloadImporter(
            days=days,
            affiliate_id=current_app.config['AFFILIATE_ID'],
            supported_publishers=current_app.config['SUPPORTED_PUBS'],
            csv_rules=current_app.config['CSV_RULES'],
            record=DailyDownloadRecord
        )
        imported_issues = import_instance.run()
        return

class SetCoverImageCommand(Command):
    """
    Sets the cover image of an issue. The issues is found in the
    database with a diamond id. If the issue already has an image
    attached, you can optionally choose to replace it.
    """
    def run(self):
        diamond_id = prompt('Issue Diamond id')
        # issue = comics.issues.first(diamond_id=diamond_id)
        issue = Issue.query.filter_by(diamond_id=diamond_id).first()
        if issue:
            url = prompt('Url of jpg image for cover image')
            overwrite = False
            if issue.cover_image.original:
                print 'Issue object already has a cover image set.'
                overwrite = prompt_bool('Overwrite existing picture?')
            # success = comics.issues.set_cover_image_from_url(issue, url, overwrite)
            success = issue.set_cover_image_from_url(url, overwrite=overwrite)
            if success:
                print 'Successfully set cover image'
            return
        print 'No issue found!'
        return

class CrossCheckCommand(Command):
    """
    Cross checks releases with items in database and mails missing
    issues to a provided email address
    """

    def get_options(self):
        return [
            Option('-w', '--week', dest='week', required=True, choices=['thisweek', 'nextweek', 'twoweeks']),
            Option('-e', '--email', dest='email', default='timbueno@gmail.com')
        ]

    def run(self, email, week):
        if week == 'twoweeks':
            raise NotImplementedError
        content = comics.get_shipping_from_TFAW(week)
        shipping = comics.get_issue_dict_shipping(content)
        not_in_db = [i for i in shipping if not comics.issues.first(diamond_id=i['ITEMCODE'])]
        not_in_db = sorted(not_in_db, key=lambda x: x['Vendor'])
        f = StringIO()
        ordered_fieldnames = ['ITEMCODE', 'DiscountCode', 'TITLE', 'Vendor', 'PRICE']
        outcsv = csv.DictWriter(f, fieldnames=ordered_fieldnames, delimiter='\t')
        for i in not_in_db:
            outcsv.writerow(i)
        mail_content([email], 'checker@longboxed.com', 'Testing', 'Attached is your checks', f.getvalue())
        f.close()
        return

class UpdateDatabaseCommand(Command):
    """Updates database with TFAW Daily Download"""

    def get_options(self):
        return [
            Option('-d','--days', dest='days', required=True)
        ]

    def run(self, days):
        print 'Starting update'
        days = int(days)
        comics.add_new_issues_to_database(days=days)
        print 'Done Adding to DB'<|endoftext|>


<commit_before># This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
"""python < 2.5 compiler package compatibility module [1]

 [1] http://docs.python.org/lib/module-compiler.ast.html

:author:    Sylvain Thenault
:copyright: 2003-2008 LOGILAB S.A. (Paris, FRANCE)
:contact:   http://www.logilab.fr/ -- mailto:python-projects@logilab.org
:copyright: 2003-2008 Sylvain Thenault
:contact:   mailto:thenault@gmail.com
"""
from __future__ import generators

__docformat__ = "restructuredtext en"

import sys
from compiler.ast import AssAttr, AssList, AssName, \
     AssTuple, Assert, Assign, AugAssign, \
     Backquote, Break, CallFunc, Class, \
     Compare, Const, Continue, Dict, Discard, \
     Ellipsis, EmptyNode, Exec, \
     For, From, Function, Getattr, Global, \
     If, Import, Invert, Keyword, Lambda, \
     List, ListComp, ListCompFor, ListCompIf, Module, Name, Node, \
     Pass, Print, Raise, Return, Slice, \
     Sliceobj, Stmt, Subscript, TryExcept, TryFinally, Tuple, \
     While, Yield

try:
    # introduced in python 2.4
    from compiler.ast import GenExpr, GenExprFor, GenExprIf, GenExprInner
except:
    class GenExpr:
        """dummy GenExpr node, shouldn't be used with py < 2.4"""
    class GenExprFor:
        """dummy GenExprFor node, shouldn't be used with py < 2.4"""
    class GenExprIf:
        """dummy GenExprIf node, shouldn't be used with py < 2.4"""
    class GenExprInner:
        """dummy GenExprInner node, shouldn't be used with py < 2.4"""
try:
    # introduced in python 2.4
    from compiler.ast import Decorators
except:
    class Decorators:
        """dummy Decorators node, shouldn't be used with py < 2.4"""

try:
    # introduced in python 2.5
    from compiler.ast import With
except:
    class With:
        """dummy With node, shouldn't be used since py < 2.5"""

# additional nodes

class ExceptHandler(Node):
    def __init__(self, type, name, body, lineno):
        self.type = type
        self.name = name
        self.body = body
        self.lineno = lineno

class BinOp(Node):
    """replace Add, Div, FloorDiv, Mod, Mul, Power, Sub nodes"""
    from compiler.ast import Add, Div, FloorDiv, Mod, Mul, Power, Sub
    from compiler.ast import Bitand, Bitor, Bitxor, LeftShift, RightShift
    OP_CLASSES = {Add: '+',
                  Div: '/',
                  FloorDiv: '//',
                  Mod: '%',
                  Mul: '*',
                  Power: '**',
                  Sub: '-',
                  Bitand: '&',
                  Bitor: '|',
                  Bitxor: '^',
                  LeftShift: '<<',
                  RightShift: '>>'}

class BoolOp(Node):
    """replace And, Or"""
    from compiler.ast import And, Or
    OP_CLASSES = {And: 'and',
                  Or: 'or'}

class UnaryOp(Node):
    """replace UnaryAdd, UnarySub, Not"""
    from compiler.ast import UnaryAdd, UnarySub, Not
    OP_CLASSES = {UnaryAdd: '+',
                  UnarySub: '-',
                  Not: 'not'}

class Delete(Node):
    """represent del statements"""

###############################################################################

COMPREHENSIONS_SCOPES = (GenExprFor, ListCompFor)

def assattr_as_string(node):
    """return an ast.AssAttr node as string"""
    if node.flags == 'OP_DELETE':
        return 'del %s.%s' % (node.expr.as_string(), node.attrname)
    return '%s.%s' % (node.expr.as_string(), node.attrname)
AssAttr.as_string = assattr_as_string

def asslist_as_string(node):
    """return an ast.AssList node as string"""
    string = ', '.join([n.as_string() for n in node.nodes])
    return '[%s]' % string
AssList.as_string = asslist_as_string

def assname_as_string(node):
    """return an ast.AssName node as string"""
    if node.flags == 'OP_DELETE':
        return 'del %s' % node.name
    return node.name
AssName.as_string = assname_as_string

def asstuple_as_string(node):
    """return an ast.AssTuple node as string"""
    string = ', '.join([n.as_string() for n in node.nodes])
    # fix for del statement
    return string.replace(', del ', ', ')
AssTuple.as_string = asstuple_as_string

Const.eq = lambda self, value: self.value == value

def const_as_string(node):
    """return an ast.Const node as string"""
    return repr(node.value)
Const.as_string = const_as_string

def decorators_scope(self):
    # skip the function node to go directly to the upper level scope
    return self.parent.parent.scope()
Decorators.scope = decorators_scope

def empty_as_string(node):
    return ''
EmptyNode.as_string = empty_as_string

EmptyNode.getChildNodes = lambda self: ()

# introduced in python 2.5
From.level = 0 # will be overiden by instance attribute with py>=2.5

def genexprinner_as_string(node):
    """return an ast.GenExpr node as string"""
    return '%s %s' % (node.expr.as_string(), ' '.join([n.as_string()
                                                       for n in node.quals]))
GenExprInner.as_string = genexprinner_as_string

def genexprfor_as_string(node):
    """return an ast.GenExprFor node as string"""
    return 'for %s in %s %s' % (node.assign.as_string(),
                                node.iter.as_string(),
                                ' '.join([n.as_string() for n in node.ifs]))
GenExprFor.as_string = genexprfor_as_string

def genexprif_as_string(node):
    """return an ast.GenExprIf node as string"""
    return 'if %s' % node.test.as_string()
GenExprIf.as_string = genexprif_as_string

def keyword_as_string(node):
    """return an ast.Keyword node as string"""
    return '%s=%s' % (node.name, node.expr.as_string())
Keyword.as_string = keyword_as_string

def listcompfor_as_string(node):
    """return an ast.ListCompFor node as string"""
    return 'for %s in %s %s' % (node.assign.as_string(),
                                node.list.as_string(),
                                ' '.join([n.as_string() for n in node.ifs]))
ListCompFor.as_string = listcompfor_as_string

def listcompif_as_string(node):
    """return an ast.ListCompIf node as string"""
    return 'if %s' % node.test.as_string()
ListCompIf.as_string = listcompif_as_string

def sliceobj_as_string(node):
    """return an ast.Sliceobj node as string"""
    return ':'.join([n.as_string() for n in node.nodes])
Sliceobj.as_string = sliceobj_as_string

# scoped nodes ################################################################

def init_function(node):
    # remove Stmt node
    node.body = node.code.nodes
    del node.code
    node.argnames = list(node.argnames)

def init_lambda(node):
     node.body = node.code
     node.argnames = list(node.argnames)
     del node.code

def init_class(node):
    # remove Stmt node
    node.body = node.code.nodes
    del node.code

def init_assname(node):
    if node.flags == 'OP_DELETE':
        node.targets = [Name(node.name)]
        node.__class__ = Delete
    elif node.flags == 'OP_ASSIGN':
        node.__class__ = Name
    elif node.flags not in ('OP_DELETE', 'OP_ASSIGN'):
        print "AssName flags:", node.flags
        raise
    del node.flags

def init_asstuple(node):
    if node.nodes[0].flags  == 'OP_DELETE':
        node.__class__ = Delete
        node.targets = [Name(item.name) for item in node.nodes]
        del node.nodes
    else:
        print "Uncatched AssTuple", node
        raise

# validated

def init_assign(node):
    node.value = node.expr
    del node.expr
    node.targets = node.nodes
    for target in node.targets:
        assert target.__class__.__name__ in ("AssName", "AssTuple")
        if isinstance(target, AssName):
            target.__class__ = Name
            del target.flags
        if isinstance(target, AssTuple):
            target.__class__ = Tuple
    del node.nodes

def init_augassign(node):
    node.value = node.expr
    del node.expr
    node.target = node.node
    del node.node

def init_binop(node):
    node.op = BinOp.OP_CLASSES[node.__class__]
    node.__class__ = BinOp

def init_boolop(node):
    node.op = BoolOp.OP_CLASSES[node.__class__]
    node.__class__ = BoolOp
    node.values = node.nodes
    del node.nodes

def init_callfunc(node):
    node.func = node.node
    node.starargs = node.star_args
    node.kwargs = node.dstar_args
    del node.node, node.star_args, node.dstar_args

def init_compare(node):
    node.left = node.expr
    del node.expr

def init_dict(node):
    pass

def init_discard(node):
    node.value = node.expr
    del node.expr

def init_exec(node):
    pass

def init_for(node):
    node.target = node.assign
    del node.assign
    node.iter = node.list
    del node.list
    node.body = node.body.nodes
    node.orelse = node.else_
    del node.else_

def init_getattr(node):
    pass

def init_import(node):
    pass

def init_import_from(node):
    pass

def init_list(node):
    node.elts = list(node.nodes) # tuple if empty list
    del node.nodes

def init_listcomp(node):
    node.elt = node.expr
    node.generators = node.qual
    del node.expr, node.quals

def init_listcompfor(node):
    node.iter = node.list
    del node.list
    node.target = node.assign
    node.target.__class__ = Name
    del node.assign, node.list

def init_module(node):
    # remove Stmt node
    node.body = node.node.nodes
    del node.node

def init_name(node):
    pass

def init_num(node):
    pass

def init_str(node):
    pass

def init_print(node, nl=False):
    node.values = node.nodes
    del node.nodes
    node.nl = nl

def init_printnl(node):
    node.__class__ = Print
    init_print(node, True)

def init_raise(node):
    node.type = node.expr1
    node.inst = node.expr2
    node.tback = node.expr3
    del node.expr1, node.expr2, node.expr3

def init_subscript(node):
    pass

def init_try_except(node):
    node.body = node.body.nodes
    # remove Stmt node
    node.handlers = [ExceptHandler(exctype, excobj, body.nodes, node.lineno)
                     for exctype, excobj, body in node.handlers]
    if node.else_:
        node.orelse = node.else_.nodes
        del node.else_
    else:
        node.orelse = []

def init_try_finally(node):
    node.body = node.body.nodes
    node.finalbody = node.final
    del node.final

init_tuple = init_list

def init_unaryop(node):
    node.op = UnaryOp.OP_CLASSES[node.__class__]
    node.__class__ = UnaryOp
    node.operand = node.expr
    del node.expr

def init_while(node):
    node.body = node.body.nodes
    del node.body
    node.orelse = node.else_
    del node.else_

# raw building ################################################################

def module_factory(doc):
    node = Module(doc, None)
    del node.node
    node.body = []
    return node

def dict_factory():
    return Dict([])

if sys.version_info < (2, 5):
    def import_from_factory(modname, membername):
        return From(modname, ( (membername, None), ) )
else:
    def import_from_factory(modname, membername):
        return From(modname, ( (membername, None), ), 0)

def _const_factory(value):
    return Const(value)

# introduction of decorators has changed the Function initializer arguments
if sys.version_info >= (2, 4):
    def function_factory(name, args, defaults, flag=0, doc=None):
        """create and initialize a astng Function node"""
        # first argument is now a list of decorators
        func = Function(Decorators([]), name, args, defaults, flag, doc, None)
        del func.code
        func.body = []
        return func

else:
    def function_factory(name, args, defaults, flag=0, doc=None):
        """create and initialize a astng Function node"""
        func = Function(name, args, defaults, flag, doc, None)
        del func.code
        func.body = []
        return func

def class_factory(name, basenames=None, doc=None):
    """create and initialize a astng Class node"""
    node = Class(name, [], doc, None)
    del node.code
    node.body = []
    bases = [Name(base) for base in basenames]
    for base in bases:
        base.parent = node
    node.bases = bases
    return node

class Proxy_: pass

def native_repr_tree(node, indent='', _done=None):
    """enhanced compiler.ast tree representation"""
    if _done is None:
        _done = set()
    if node in _done:
        print ('loop in tree: %r (%s)' % (node, getattr(node, 'lineno', None)))
        return
    _done.add(node)
    print indent + "<%s>" % node.__class__
    indent += '    '
    if not hasattr(node, "__dict__"): # XXX
        return
    for field, attr in node.__dict__.items():
        if attr is None or field == "_proxied":
            continue
        if type(attr) is list:
            if not attr: continue
            print indent + field + ' ['
            for elt in attr:
                if type(elt) is tuple:
                    for val in elt:
                        native_repr_tree(val, indent, _done)
                else:
                    native_repr_tree(elt, indent, _done)
            print indent + ']'
            continue
        if isinstance(attr, Node):
            print indent + field
            native_repr_tree(attr, indent, _done)
        else:
            print indent + field,  repr(attr)
<commit_msg>some small corrections : * Dict : empty node.items should be a list * AssAttr catched in init_assign<commit_after># This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
"""python < 2.5 compiler package compatibility module [1]

 [1] http://docs.python.org/lib/module-compiler.ast.html

:author:    Sylvain Thenault
:copyright: 2003-2008 LOGILAB S.A. (Paris, FRANCE)
:contact:   http://www.logilab.fr/ -- mailto:python-projects@logilab.org
:copyright: 2003-2008 Sylvain Thenault
:contact:   mailto:thenault@gmail.com
"""
from __future__ import generators

__docformat__ = "restructuredtext en"

import sys
from compiler.ast import AssAttr, AssList, AssName, \
     AssTuple, Assert, Assign, AugAssign, \
     Backquote, Break, CallFunc, Class, \
     Compare, Const, Continue, Dict, Discard, \
     Ellipsis, EmptyNode, Exec, \
     For, From, Function, Getattr, Global, \
     If, Import, Invert, Keyword, Lambda, \
     List, ListComp, ListCompFor, ListCompIf, Module, Name, Node, \
     Pass, Print, Raise, Return, Slice, \
     Sliceobj, Stmt, Subscript, TryExcept, TryFinally, Tuple, \
     While, Yield

try:
    # introduced in python 2.4
    from compiler.ast import GenExpr, GenExprFor, GenExprIf, GenExprInner
except:
    class GenExpr:
        """dummy GenExpr node, shouldn't be used with py < 2.4"""
    class GenExprFor:
        """dummy GenExprFor node, shouldn't be used with py < 2.4"""
    class GenExprIf:
        """dummy GenExprIf node, shouldn't be used with py < 2.4"""
    class GenExprInner:
        """dummy GenExprInner node, shouldn't be used with py < 2.4"""
try:
    # introduced in python 2.4
    from compiler.ast import Decorators
except:
    class Decorators:
        """dummy Decorators node, shouldn't be used with py < 2.4"""

try:
    # introduced in python 2.5
    from compiler.ast import With
except:
    class With:
        """dummy With node, shouldn't be used since py < 2.5"""

# additional nodes

class ExceptHandler(Node):
    def __init__(self, type, name, body, lineno):
        self.type = type
        self.name = name
        self.body = body
        self.lineno = lineno

class BinOp(Node):
    """replace Add, Div, FloorDiv, Mod, Mul, Power, Sub nodes"""
    from compiler.ast import Add, Div, FloorDiv, Mod, Mul, Power, Sub
    from compiler.ast import Bitand, Bitor, Bitxor, LeftShift, RightShift
    OP_CLASSES = {Add: '+',
                  Div: '/',
                  FloorDiv: '//',
                  Mod: '%',
                  Mul: '*',
                  Power: '**',
                  Sub: '-',
                  Bitand: '&',
                  Bitor: '|',
                  Bitxor: '^',
                  LeftShift: '<<',
                  RightShift: '>>'}

class BoolOp(Node):
    """replace And, Or"""
    from compiler.ast import And, Or
    OP_CLASSES = {And: 'and',
                  Or: 'or'}

class UnaryOp(Node):
    """replace UnaryAdd, UnarySub, Not"""
    from compiler.ast import UnaryAdd, UnarySub, Not
    OP_CLASSES = {UnaryAdd: '+',
                  UnarySub: '-',
                  Not: 'not'}

class Delete(Node):
    """represent del statements"""

###############################################################################

COMPREHENSIONS_SCOPES = (GenExprFor, ListCompFor)

def assattr_as_string(node):
    """return an ast.AssAttr node as string"""
    if node.flags == 'OP_DELETE':
        return 'del %s.%s' % (node.expr.as_string(), node.attrname)
    return '%s.%s' % (node.expr.as_string(), node.attrname)
AssAttr.as_string = assattr_as_string

def asslist_as_string(node):
    """return an ast.AssList node as string"""
    string = ', '.join([n.as_string() for n in node.nodes])
    return '[%s]' % string
AssList.as_string = asslist_as_string

def assname_as_string(node):
    """return an ast.AssName node as string"""
    if node.flags == 'OP_DELETE':
        return 'del %s' % node.name
    return node.name
AssName.as_string = assname_as_string

def asstuple_as_string(node):
    """return an ast.AssTuple node as string"""
    string = ', '.join([n.as_string() for n in node.nodes])
    # fix for del statement
    return string.replace(', del ', ', ')
AssTuple.as_string = asstuple_as_string

Const.eq = lambda self, value: self.value == value

def const_as_string(node):
    """return an ast.Const node as string"""
    return repr(node.value)
Const.as_string = const_as_string

def decorators_scope(self):
    # skip the function node to go directly to the upper level scope
    return self.parent.parent.scope()
Decorators.scope = decorators_scope

def empty_as_string(node):
    return ''
EmptyNode.as_string = empty_as_string

EmptyNode.getChildNodes = lambda self: ()

# introduced in python 2.5
From.level = 0 # will be overiden by instance attribute with py>=2.5

def genexprinner_as_string(node):
    """return an ast.GenExpr node as string"""
    return '%s %s' % (node.expr.as_string(), ' '.join([n.as_string()
                                                       for n in node.quals]))
GenExprInner.as_string = genexprinner_as_string

def genexprfor_as_string(node):
    """return an ast.GenExprFor node as string"""
    return 'for %s in %s %s' % (node.assign.as_string(),
                                node.iter.as_string(),
                                ' '.join([n.as_string() for n in node.ifs]))
GenExprFor.as_string = genexprfor_as_string

def genexprif_as_string(node):
    """return an ast.GenExprIf node as string"""
    return 'if %s' % node.test.as_string()
GenExprIf.as_string = genexprif_as_string

def keyword_as_string(node):
    """return an ast.Keyword node as string"""
    return '%s=%s' % (node.name, node.expr.as_string())
Keyword.as_string = keyword_as_string

def listcompfor_as_string(node):
    """return an ast.ListCompFor node as string"""
    return 'for %s in %s %s' % (node.assign.as_string(),
                                node.list.as_string(),
                                ' '.join([n.as_string() for n in node.ifs]))
ListCompFor.as_string = listcompfor_as_string

def listcompif_as_string(node):
    """return an ast.ListCompIf node as string"""
    return 'if %s' % node.test.as_string()
ListCompIf.as_string = listcompif_as_string

def sliceobj_as_string(node):
    """return an ast.Sliceobj node as string"""
    return ':'.join([n.as_string() for n in node.nodes])
Sliceobj.as_string = sliceobj_as_string

# scoped nodes ################################################################

def init_function(node):
    # remove Stmt node
    node.body = node.code.nodes
    del node.code
    node.argnames = list(node.argnames)

def init_lambda(node):
     node.body = node.code
     node.argnames = list(node.argnames)
     del node.code

def init_class(node):
    # remove Stmt node
    node.body = node.code.nodes
    del node.code

def init_assname(node):
    if node.flags == 'OP_DELETE':
        node.targets = [Name(node.name)]
        node.__class__ = Delete
    elif node.flags == 'OP_ASSIGN':
        node.__class__ = Name
    elif node.flags not in ('OP_DELETE', 'OP_ASSIGN'):
        print "AssName flags:", node.flags
        raise
    del node.flags

def init_asstuple(node):
    if node.nodes[0].flags  == 'OP_DELETE':
        node.__class__ = Delete
        node.targets = [Name(item.name) for item in node.nodes]
        del node.nodes
    else:
        print "Uncatched AssTuple", node
        raise

# validated

def init_assign(node):
    node.value = node.expr
    del node.expr
    node.targets = node.nodes
    for target in node.targets:
        if isinstance(target, AssName):
            target.__class__ = Name
            del target.flags
        elif isinstance(target, AssTuple):
            target.__class__ = Tuple
        elif isinstance(target, AssAttr):
            target.__class__ = Getattr
    del node.nodes

def init_augassign(node):
    node.value = node.expr
    del node.expr
    node.target = node.node
    del node.node

def init_binop(node):
    node.op = BinOp.OP_CLASSES[node.__class__]
    node.__class__ = BinOp

def init_boolop(node):
    node.op = BoolOp.OP_CLASSES[node.__class__]
    node.__class__ = BoolOp
    node.values = node.nodes
    del node.nodes

def init_callfunc(node):
    node.func = node.node
    node.starargs = node.star_args
    node.kwargs = node.dstar_args
    del node.node, node.star_args, node.dstar_args

def init_compare(node):
    node.left = node.expr
    del node.expr

def init_dict(node):
    node.items = list(node.items)

def init_discard(node):
    node.value = node.expr
    del node.expr

def init_exec(node):
    pass

def init_for(node):
    node.target = node.assign
    del node.assign
    node.iter = node.list
    del node.list
    node.body = node.body.nodes
    node.orelse = node.else_
    del node.else_

def init_getattr(node):
    pass

def init_import(node):
    pass

def init_import_from(node):
    pass

def init_list(node):
    node.elts = list(node.nodes) # tuple if empty list
    del node.nodes

def init_listcomp(node):
    node.elt = node.expr
    node.generators = node.qual
    del node.expr, node.quals

def init_listcompfor(node):
    node.iter = node.list
    del node.list
    node.target = node.assign
    node.target.__class__ = Name
    del node.assign, node.list

def init_module(node):
    # remove Stmt node
    node.body = node.node.nodes
    del node.node

def init_name(node):
    pass

def init_num(node):
    pass

def init_str(node):
    pass

def init_print(node, nl=False):
    node.values = node.nodes
    del node.nodes
    node.nl = nl

def init_printnl(node):
    node.__class__ = Print
    init_print(node, True)

def init_raise(node):
    node.type = node.expr1
    node.inst = node.expr2
    node.tback = node.expr3
    del node.expr1, node.expr2, node.expr3

def init_subscript(node):
    pass

def init_try_except(node):
    node.body = node.body.nodes
    # remove Stmt node
    node.handlers = [ExceptHandler(exctype, excobj, body.nodes, node.lineno)
                     for exctype, excobj, body in node.handlers]
    if node.else_:
        node.orelse = node.else_.nodes
        del node.else_
    else:
        node.orelse = []

def init_try_finally(node):
    node.body = node.body.nodes
    node.finalbody = node.final
    del node.final

init_tuple = init_list

def init_unaryop(node):
    node.op = UnaryOp.OP_CLASSES[node.__class__]
    node.__class__ = UnaryOp
    node.operand = node.expr
    del node.expr

def init_while(node):
    node.body = node.body.nodes
    del node.body
    node.orelse = node.else_
    del node.else_

# raw building ################################################################

def module_factory(doc):
    node = Module(doc, None)
    del node.node
    node.body = []
    return node

def dict_factory():
    return Dict([])

if sys.version_info < (2, 5):
    def import_from_factory(modname, membername):
        return From(modname, ( (membername, None), ) )
else:
    def import_from_factory(modname, membername):
        return From(modname, ( (membername, None), ), 0)

def _const_factory(value):
    return Const(value)

# introduction of decorators has changed the Function initializer arguments
if sys.version_info >= (2, 4):
    def function_factory(name, args, defaults, flag=0, doc=None):
        """create and initialize a astng Function node"""
        # first argument is now a list of decorators
        func = Function(Decorators([]), name, args, defaults, flag, doc, None)
        del func.code
        func.body = []
        return func

else:
    def function_factory(name, args, defaults, flag=0, doc=None):
        """create and initialize a astng Function node"""
        func = Function(name, args, defaults, flag, doc, None)
        del func.code
        func.body = []
        return func

def class_factory(name, basenames=None, doc=None):
    """create and initialize a astng Class node"""
    node = Class(name, [], doc, None)
    del node.code
    node.body = []
    bases = [Name(base) for base in basenames]
    for base in bases:
        base.parent = node
    node.bases = bases
    return node

class Proxy_: pass

def native_repr_tree(node, indent='', _done=None):
    """enhanced compiler.ast tree representation"""
    if _done is None:
        _done = set()
    if node in _done:
        print ('loop in tree: %r (%s)' % (node, getattr(node, 'lineno', None)))
        return
    _done.add(node)
    print indent + "<%s>" % node.__class__
    indent += '    '
    if not hasattr(node, "__dict__"): # XXX
        return
    for field, attr in node.__dict__.items():
        if attr is None or field == "_proxied":
            continue
        if type(attr) is list:
            if not attr: continue
            print indent + field + ' ['
            for elt in attr:
                if type(elt) is tuple:
                    for val in elt:
                        native_repr_tree(val, indent, _done)
                else:
                    native_repr_tree(elt, indent, _done)
            print indent + ']'
            continue
        if isinstance(attr, Node):
            print indent + field
            native_repr_tree(attr, indent, _done)
        else:
            print indent + field,  repr(attr)
<|endoftext|>