<commit_before>#!/usr/bin/env python
#
# %%README%%
# %%LICENSE%%
# --------------------------------------------------------------------------------
# Globals
#
version = "%%VERSION%%"

# --------------------------------------------------------------------------------
# Imports
#
import sys
import os
import re
import argparse
import subprocess

# --------------------------------------------------------------------------------
# Helper Functions
#
def get_program_path():
    return os.path.realpath(__file__)

def show_version():
    if args.quiet:
        return
    print """dep version {}
Copyright (c) 2015 Harvey John Thompson
See {} for LICENSE.""".format(version, get_program_path())

def error(fmt, *a):
    sys.stderr.write("dep: ")
    sys.stderr.write(fmt.format(*a))
    sys.stderr.write("\n")
    exit(1)

def debug(fmt, *a):
    if not args.debug or args.quiet:
        return
    sys.stderr.write(fmt.format(*a))
    sys.stderr.write("\n")

def status(fmt, *a):
    if args.quiet:
        return
    sys.stderr.write(fmt.format(*a))
    sys.stderr.write("\n")

def verbose(fmt, *a):
    if not args.verbose or args.quiet:
        return
    sys.stderr.write(fmt.format(*a))
    sys.stderr.write("\n")

def validate_file_exists(file):
    if not os.path.isfile(file):
        error("File '{}' does not exist", file)

def validate_file_notexists(file):
    if os.path.exists(file):
        error("File '{}' already exists", file)

def validate_dir_exists(dir):
    if not os.path.isdir(dir):
        error("Directory '{}' does not exist", dir)

def validate_dir_notexists(dir):
    if os.path.exists(dir):
        error("Directory '{}' already exists", dir)

def run(*cmd, **kw):
    status = 0
    cmd = filter(None, cmd)
    cmd_text = ' '.join(cmd)
    cwd = kw.get('cwd')
    query = kw.get('query')
    if not query:
        if cwd:
            verbose("-> pushd {}", cwd)
        verbose("-> {}", cmd_text)
        if cwd:
            verbose("-> popd")
    if args.dry_run and not query:
        return
    try:
        if query:
            return subprocess.check_output(cmd, stderr=subprocess.STDOUT)
        elif args.quiet:
            with open(os.devnull, "wb") as dev_null:
                status = subprocess.call(cmd, stdout=dev_null)
        else:
            status = subprocess.call(cmd)
        if status != 0:
            error("Execution of '{}' returned exit status {}", cmd_text, status)
    except OSError, e:
        error("Cannot execute '{}': {}'", cmd_text, e)
    except Exception, e:
        error("{}", e)

def run_query(*cmd, **kw):
    return run(*cmd, query=True, **kw)

# --------------------------------------------------------------------------------
# Configuration
#
class Config:
    def __init__(self, path):
        self.path = path
        self.sections = []

    def __str__(self):
        return "Config '{}'".format(self.path)

    def read(self):
        status("Reading {}", self)
        try:
            section = None
            with open(self.path, 'r') as handle:
                for lineno, line in enumerate(handle, start=1):
                    line = line.rstrip('\r\n')
                    # TODO: Handle comments
                    # TODO: Handle escapes here? Would make parsing "\"" harder.
                    # TODO: Handle line continuation
                    if re.match(r"^\s*$", line):
                        continue
                    s = ConfigSection.parse(self, line)
                    if s:
                        section = s
                        continue
                    v = ConfigVar.parse(section, line)
                    if v:
                        continue
                    error("{}, line {} cannot be parsed:\n>>> {}", self, lineno, line)
        except IOError, e:
            error("Cannot open {} for reading: {}'", self, e)

    def write(self):
        status("Writing {}", self)
        if args.dry_run:
            return
        try:
            with open(self.path, 'w') as handle:
                for b in self.sections:
                    b.write(handle)
        except IOError, e:
            error("Cannot open {} for writing: {}'", self, e)

    def __getitem__(self, key):
        for s in self.sections:
            if s.fullname == key:
                return s
        raise KeyError("Unknown section '{}' in {}".format(key, self))

class ConfigSection:
    def __init__(self, config, name, subname=None):
        self.config = config
        self.name = name
        self.subname = subname
        if subname:
            self.fullname = "{}.{}".format(name, subname)
        else:
            self.fullname = name
        self.vars = []
        config.sections.append(self)

    def __str__(self):
        return self.fullname

    @staticmethod
    def parse(config, line):
        if not config:
            return None
        m = re.match(r'^\s*\[\s*([-a-zA-Z0-9]*)\s*("([^"]*)")?\s*\]\s*$', line)
        if not m:
            return None
        section = ConfigSection(config, m.group(1), m.group(3))
        return section

    def write(self, handle):
        if handle.tell() != 0:
            handle.write('\n')
        if self.subname:
            handle.write('[{} "{}"]\n'.format(self.name, self.subname))
        else:
            handle.write('[{}]\n'.format(self.name))
        for v in self.vars:
            v.write(handle)

    def __getitem__(self, key):
        for v in self.vars:
            if v.name == key:
                return v.value
        raise KeyError("Unknown variable '{}.{}' in {}".format(self.fullname, key, self.config))

class ConfigVar:
    def __init__(self, section, name, value):
        self.section = section
        self.fullname = "{}.{}".format(section.fullname, name)
        self.name = name
        self.value = value
        section.vars.append(self)

    def __str__(self):
        return self.value

    @staticmethod
    def parse(section, line):
        if not section:
            return None
        m = re.match(r'^\s*([-a-zA-Z0-9]*)\s*=\s*(.*?)\s*$', line)
        if not m:
            return None
        var = ConfigVar(section, m.group(1), m.group(2))
        return var

    def write(self, handle):
        # TODO: Handle escapes, quoting, whitespacing
        handle.write('\t{} = {}\n'.format(self.name, self.value))

# --------------------------------------------------------------------------------
# Repository
#
class Repository:
    def __init__(self, local_dir, url, vcs, name):
        self.local_dir = local_dir
        self.url = url
        self.vcs = vcs
        self.name = name

    def __str__(self):
        return "{} '{}'".format(self.__class__.__name__, self.local_dir)

    def add_to_config_section(self, section):
        ConfigVar(section, "url", self.url)
        ConfigVar(section, "vcs", self.vcs)

    @staticmethod
    def determine_vcs_from_url(url):
        # TODO: Hard coded for now
        return "git"

    @staticmethod
    def create_from_url(url):
        vcs = Repository.determine_vcs_from_url(url)
        # TODO: Support more VCS
        if vcs == "git":
            return GitRepository(url)
        else:
            error("Cannot determine VCS from repository URL '{}'", url)

class FileRepository(Repository):
    def __init__(self, local_dir):
        name = FileRepository.determine_name_from_path(local_dir)
        # TODO: Is this correct?
        url = "file://{}".format(local_dir)
        Repository.__init__(self, local_dir, url, "file", name)

    @staticmethod
    def determine_name_from_path(path):
        name = os.path.basename(path)
        return name

class GitRepository(Repository):
    def __init__(self, url):
        # TODO: What is local_dir really?
        local_dir = os.getcwd()
        # TODO: Better way to find name of repository?
        name = GitRepository.determine_name_from_url(url)
        Repository.__init__(self, local_dir, url, "git", name)

    @staticmethod
    def determine_name_from_url(url):
        m = re.search(r"([^/]*)/*$", url)
        if m:
            name = m.group(1)
            name = re.sub(r"\.git$", "", name)
            return name
        return None

# --------------------------------------------------------------------------------
# Component
#
class Component:
    def __init__(self, parent=None, url=None):
        self.parent = parent
        self.children = []
        self.root = parent.root if parent else self
        if parent:
            parent.children.append(self)
        # TODO: Get correct config location/directory how?
        local_dir = os.getcwd()
        self.config = Config(os.path.join(local_dir, ".depconfig"))
        if url:
            self.repository = Repository.create_from_url(url)
        else:
            self.repository = FileRepository(local_dir)
        self.name = self.repository.name
        # TODO: Override by default?
        dep_dir = parent.config["core"]["default-dep-dir"] if parent else "dep"
        self.path = os.path.join(dep_dir, self.name)

    def __str__(self):
        return "Component '{}'".format(self.name)

    def init(self):
        verbose("Initializing {}", self)
        validate_file_notexists(self.config.path)
        core = ConfigSection(self.config, "core")
        ConfigVar(core, "default-dep-dir", "dep")
        self.config.write()

    def add_to_config(self, config):
        section = ConfigSection(config, "dep", self.name)
        ConfigVar(section, "path", self.path)
        self.repository.add_to_config_section(section)

    def add_child(self, url):
        self.config.read()
        child = Component(self, url)
        child.add_to_config(self.config)
        self.config.write()

# --------------------------------------------------------------------------------
# Command: help
#
def command_help(args):
    if args.command:
        parser.parse_args([args.command, "--help"])
    else:
        parser.print_help()

# --------------------------------------------------------------------------------
# Command: init
#
def command_init(args):
    root = Component()
    root.init()

# --------------------------------------------------------------------------------
# Command: add
#
def command_add(args):
    root = Component()
    root.add_child(args.url)

# --------------------------------------------------------------------------------
# Main
#
parser = argparse.ArgumentParser(description="Manages component based dependencies using version control systems (VCS).")

subparsers = parser.add_subparsers(title="command arguments")

parser.add_argument("--version", action="store_true",
                    help="Show version and exit")
parser.add_argument("-D", "--debug", action="store_true",
                    help="Show debugging information on stderr")
parser.add_argument("-q", "--quiet", action="store_true",
                    help="Only print error messages")
parser.add_argument("-v", "--verbose", action="store_true",
                    help="Show more verbose information, including commands executed")
parser.add_argument("--dry-run", action="store_true",
                    help="Only show what actions and commands would be executed, make no changes")

parser_help = subparsers.add_parser("help",
                                    help="Show general or specific command help",
                                    description="Without any arguments display short help for all commands. With a specified 'command' argument show more specific help for the given command.")
parser_help.add_argument("command", nargs="?")
parser_help.set_defaults(func=command_help)

parser_init = subparsers.add_parser("init",
                                    help="Initialise dependency system for this component",
                                    description="Initialise dependency system for this component.")
parser_init.set_defaults(func=command_init)

parser_add = subparsers.add_parser("add",
                                   help="Add a new dependency to this component",
                                   description="Add a new dependency to this component.")
parser_add.add_argument("url",
                        help="The URL of the dependant component's VCS repository")
parser_add.set_defaults(func=command_add)

if len(sys.argv) == 1:
    parser.print_help()
    exit(0)

args = parser.parse_args()
if args.version:
    show_version()
    exit(0)

args.func(args)
exit(0)
<commit_msg>Added debug support.<commit_after>#!/usr/bin/env python
#
# %%README%%
# %%LICENSE%%
# --------------------------------------------------------------------------------
# Globals
#
version = "%%VERSION%%"

# --------------------------------------------------------------------------------
# Imports
#
import sys
import os
import re
import argparse
import subprocess

# --------------------------------------------------------------------------------
# Helper Functions
#
def get_program_path():
    return os.path.realpath(__file__)

def show_version():
    if args.quiet:
        return
    print """dep version {}
Copyright (c) 2015 Harvey John Thompson
See {} for LICENSE.""".format(version, get_program_path())

def error(fmt, *a):
    sys.stderr.write("dep: ")
    sys.stderr.write(fmt.format(*a))
    sys.stderr.write("\n")
    exit(1)

def debug(fmt, *a):
    if not args.debug or args.quiet:
        return
    sys.stderr.write(fmt.format(*a))
    sys.stderr.write("\n")

def status(fmt, *a):
    if args.quiet:
        return
    sys.stderr.write(fmt.format(*a))
    sys.stderr.write("\n")

def verbose(fmt, *a):
    if not args.verbose or args.quiet:
        return
    sys.stderr.write(fmt.format(*a))
    sys.stderr.write("\n")

def validate_file_exists(file):
    if not os.path.isfile(file):
        error("File '{}' does not exist", file)

def validate_file_notexists(file):
    if os.path.exists(file):
        error("File '{}' already exists", file)

def validate_dir_exists(dir):
    if not os.path.isdir(dir):
        error("Directory '{}' does not exist", dir)

def validate_dir_notexists(dir):
    if os.path.exists(dir):
        error("Directory '{}' already exists", dir)

def run(*cmd, **kw):
    status = 0
    cmd = filter(None, cmd)
    cmd_text = ' '.join(cmd)
    cwd = kw.get('cwd')
    query = kw.get('query')
    if not query:
        if cwd:
            verbose("-> pushd {}", cwd)
        verbose("-> {}", cmd_text)
        if cwd:
            verbose("-> popd")
    if args.dry_run and not query:
        return
    try:
        if query:
            return subprocess.check_output(cmd, stderr=subprocess.STDOUT)
        elif args.quiet:
            with open(os.devnull, "wb") as dev_null:
                status = subprocess.call(cmd, stdout=dev_null)
        else:
            status = subprocess.call(cmd)
        if status != 0:
            error("Execution of '{}' returned exit status {}", cmd_text, status)
    except OSError, e:
        error("Cannot execute '{}': {}'", cmd_text, e)
    except Exception, e:
        error("{}", e)

def run_query(*cmd, **kw):
    return run(*cmd, query=True, **kw)

# --------------------------------------------------------------------------------
# Configuration
#
class Config:
    def __init__(self, path):
        self.path = path
        self.sections = []

    def __str__(self):
        return "Config '{}'".format(self.path)

    def read(self):
        status("Reading {}", self)
        try:
            section = None
            with open(self.path, 'r') as handle:
                for lineno, line in enumerate(handle, start=1):
                    line = line.rstrip('\r\n')
                    # TODO: Handle comments
                    # TODO: Handle escapes here? Would make parsing "\"" harder.
                    # TODO: Handle line continuation
                    if re.match(r"^\s*$", line):
                        continue
                    s = ConfigSection.parse(self, line)
                    if s:
                        section = s
                        continue
                    v = ConfigVar.parse(section, line)
                    if v:
                        continue
                    error("{}, line {} cannot be parsed:\n>>> {}", self, lineno, line)
        except IOError, e:
            error("Cannot open {} for reading: {}'", self, e)

    def write(self):
        status("Writing {}", self)
        if args.dry_run:
            return
        try:
            with open(self.path, 'w') as handle:
                for b in self.sections:
                    b.write(handle)
        except IOError, e:
            error("Cannot open {} for writing: {}'", self, e)

    def __getitem__(self, key):
        for s in self.sections:
            if s.fullname == key:
                return s
        raise KeyError("Unknown section '{}' in {}".format(key, self))

    def debug_dump(self, prefix=""):
        debug("{}--- {} ---", prefix, self)
        for s in self.sections:
            s.debug_dump(prefix)

class ConfigSection:
    def __init__(self, config, name, subname=None):
        self.config = config
        self.name = name
        self.subname = subname
        if subname:
            self.fullname = "{}.{}".format(name, subname)
        else:
            self.fullname = name
        self.vars = []
        config.sections.append(self)

    def __str__(self):
        return self.fullname

    @staticmethod
    def parse(config, line):
        if not config:
            return None
        m = re.match(r'^\s*\[\s*([-a-zA-Z0-9]*)\s*("([^"]*)")?\s*\]\s*$', line)
        if not m:
            return None
        section = ConfigSection(config, m.group(1), m.group(3))
        return section

    def write(self, handle):
        if handle.tell() != 0:
            handle.write('\n')
        if self.subname:
            handle.write('[{} "{}"]\n'.format(self.name, self.subname))
        else:
            handle.write('[{}]\n'.format(self.name))
        for v in self.vars:
            v.write(handle)

    def __getitem__(self, key):
        for v in self.vars:
            if v.name == key:
                return v.value
        raise KeyError("Unknown variable '{}.{}' in {}".format(self.fullname, key, self.config))

    def debug_dump(self, prefix=""):
        prefix = "{}{}.".format(prefix, self.fullname)
        for v in self.vars:
            v.debug_dump(prefix)

class ConfigVar:
    def __init__(self, section, name, value):
        self.section = section
        self.fullname = "{}.{}".format(section.fullname, name)
        self.name = name
        self.value = value
        section.vars.append(self)

    def __str__(self):
        return self.value

    @staticmethod
    def parse(section, line):
        if not section:
            return None
        m = re.match(r'^\s*([-a-zA-Z0-9]*)\s*=\s*(.*?)\s*$', line)
        if not m:
            return None
        var = ConfigVar(section, m.group(1), m.group(2))
        return var

    def write(self, handle):
        # TODO: Handle escapes, quoting, whitespacing
        handle.write('\t{} = {}\n'.format(self.name, self.value))

    def debug_dump(self, prefix=""):
        debug("{}{} = {}", prefix, self.name, self.value)

# --------------------------------------------------------------------------------
# Repository
#
class Repository:
    def __init__(self, local_dir, url, vcs, name):
        self.local_dir = local_dir
        self.url = url
        self.vcs = vcs
        self.name = name

    def __str__(self):
        return "{} '{}'".format(self.__class__.__name__, self.local_dir)

    def add_to_config_section(self, section):
        ConfigVar(section, "url", self.url)
        ConfigVar(section, "vcs", self.vcs)

    @staticmethod
    def determine_vcs_from_url(url):
        # TODO: Hard coded for now
        return "git"

    @staticmethod
    def create_from_url(url):
        vcs = Repository.determine_vcs_from_url(url)
        # TODO: Support more VCS
        if vcs == "git":
            return GitRepository(url)
        else:
            error("Cannot determine VCS from repository URL '{}'", url)

    def debug_dump(self, prefix=""):
        debug("{}--- {} ---", prefix, self)
        debug("{}local_dir = {}", prefix, self.local_dir)
        debug("{}url = {}", prefix, self.url)
        debug("{}vcs = {}", prefix, self.vcs)
        debug("{}name = {}", prefix, self.name)

class FileRepository(Repository):
    def __init__(self, local_dir):
        name = FileRepository.determine_name_from_path(local_dir)
        # TODO: Is this correct?
        url = "file://{}".format(local_dir)
        Repository.__init__(self, local_dir, url, "file", name)

    @staticmethod
    def determine_name_from_path(path):
        name = os.path.basename(path)
        return name

class GitRepository(Repository):
    def __init__(self, url):
        # TODO: What is local_dir really?
        local_dir = os.getcwd()
        # TODO: Better way to find name of repository?
        name = GitRepository.determine_name_from_url(url)
        Repository.__init__(self, local_dir, url, "git", name)

    @staticmethod
    def determine_name_from_url(url):
        m = re.search(r"([^/]*)/*$", url)
        if m:
            name = m.group(1)
            name = re.sub(r"\.git$", "", name)
            return name
        return None

# --------------------------------------------------------------------------------
# Component
#
class Component:
    def __init__(self, parent=None, url=None):
        self.parent = parent
        self.children = []
        self.root = parent.root if parent else self
        if parent:
            parent.children.append(self)
        # TODO: Get correct config location/directory how?
        local_dir = os.getcwd()
        self.config = Config(os.path.join(local_dir, ".depconfig"))
        if url:
            self.repository = Repository.create_from_url(url)
        else:
            self.repository = FileRepository(local_dir)
        self.name = self.repository.name
        # TODO: Override by default?
        dep_dir = parent.config["core"]["default-dep-dir"] if parent else "dep"
        self.path = os.path.join(dep_dir, self.name)

    def __str__(self):
        return "Component '{}'".format(self.name)

    def init(self):
        verbose("Initializing {}", self)
        validate_file_notexists(self.config.path)
        core = ConfigSection(self.config, "core")
        ConfigVar(core, "default-dep-dir", "dep")
        self.config.write()
        self.debug_dump("post: ")

    def add_to_config(self, config):
        section = ConfigSection(config, "dep", self.name)
        ConfigVar(section, "path", self.path)
        self.repository.add_to_config_section(section)

    def add_child(self, url):
        self.config.read()
        self.debug_dump("pre: ")
        child = Component(self, url)
        child.add_to_config(self.config)
        self.config.write()
        self.debug_dump("post: ")

    def debug_dump(self, prefix=""):
        debug("{}--- {} ---", prefix, self)
        debug("{}name = {}", prefix, self.name)
        debug("{}path = {}", prefix, self.path)
        debug("{}parent = {}", prefix, self.parent)
        self.config.debug_dump(prefix)
        self.repository.debug_dump(prefix)
        debug("{}children[] = {{", prefix)
        for i, c in enumerate(self.children):
            if i > 0:
                debug("{},".format(prefix))
            c.debug_dump("{}[{}] ".format(prefix, i))
        debug("{}}}", prefix)

# --------------------------------------------------------------------------------
# Command: help
#
def command_help(args):
    if args.command:
        parser.parse_args([args.command, "--help"])
    else:
        parser.print_help()

# --------------------------------------------------------------------------------
# Command: init
#
def command_init(args):
    root = Component()
    root.init()

# --------------------------------------------------------------------------------
# Command: add
#
def command_add(args):
    root = Component()
    root.add_child(args.url)

# --------------------------------------------------------------------------------
# Main
#
parser = argparse.ArgumentParser(description="Manages component based dependencies using version control systems (VCS).")

subparsers = parser.add_subparsers(title="command arguments")

parser.add_argument("--version", action="store_true",
                    help="Show version and exit")
parser.add_argument("-D", "--debug", action="store_true",
                    help="Show debugging information on stderr")
parser.add_argument("-q", "--quiet", action="store_true",
                    help="Only print error messages")
parser.add_argument("-v", "--verbose", action="store_true",
                    help="Show more verbose information, including commands executed")
parser.add_argument("--dry-run", action="store_true",
                    help="Only show what actions and commands would be executed, make no changes")

parser_help = subparsers.add_parser("help",
                                    help="Show general or specific command help",
                                    description="Without any arguments display short help for all commands. With a specified 'command' argument show more specific help for the given command.")
parser_help.add_argument("command", nargs="?")
parser_help.set_defaults(func=command_help)

parser_init = subparsers.add_parser("init",
                                    help="Initialise dependency system for this component",
                                    description="Initialise dependency system for this component.")
parser_init.set_defaults(func=command_init)

parser_add = subparsers.add_parser("add",
                                   help="Add a new dependency to this component",
                                   description="Add a new dependency to this component.")
parser_add.add_argument("url",
                        help="The URL of the dependant component's VCS repository")
parser_add.set_defaults(func=command_add)

if len(sys.argv) == 1:
    parser.print_help()
    exit(0)

args = parser.parse_args()
if args.version:
    show_version()
    exit(0)

args.func(args)
exit(0)
<|endoftext|>


<commit_before># The MIT License (MIT)
#
# Copyright (c) 2016 James Slagle <james.slagle@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

import argparse
from datetime import datetime
from pprint import pprint
import requests

class Trello(object):

    def __init__(self, api_key, api_token):
        self.url = "https://api.trello.com/1/%s"
        self.api_key = api_key
        self.api_token = api_token
        self.payload = dict(key=self.api_key, token=self.api_token)

    def get(self, path):
        r = requests.get(self.url % path, params=self.payload)
        return r.json()

parser = argparse.ArgumentParser()
parser.add_argument("--api-key",
                    required=True,
                    help="Trello API key")
parser.add_argument("--api-token",
                    required=True,
                    help="Trello API token")
parser.add_argument("--board-name",
                    required=True,
                    help="Board name on which to report")
args = parser.parse_args()

trello = Trello(args.api_key, args.api_token)
board = [b for b in trello.get("/member/me/boards") \
            if b["name"] == args.board_name][0]
board_id = board["id"]
lists = trello.get("/boards/%s/lists" % board_id)

next_list = [l for l in lists if l["name"] == "Next"][0]
next_list_id = next_list["id"]
next_cards = trello.get("/lists/%s/cards" % next_list_id)

in_progress_list = [l for l in lists if l["name"] == "In Progress"][0]
in_progress_list_id = in_progress_list["id"]
in_progress_list_cards = trello.get("/lists/%s/cards" % in_progress_list_id)

dev_complete_list = [l for l in lists if l["name"] == "Dev Complete"][0]
dev_complete_list_id = dev_complete_list["id"]
dev_complete_list_cards = trello.get("/lists/%s/cards" % dev_complete_list_id)

qe_accepted_list = [l for l in lists if l["name"] == "QE Accepted (Done)"][0]
qe_accepted_list_id = qe_accepted_list["id"]
qe_accepted_list_cards = trello.get("/lists/%s/cards" % qe_accepted_list_id)

all_cards = trello.get("/boards/%s/cards" % board_id)

def print_card(card):
    due = card["due"]
    if due is not None:
        due = datetime.strptime(card["due"],
                "%Y-%m-%dT%H:%M:%S.%fZ")
        due = due.strftime("%B %d, %Y")
    print("# - %s" % card["name"])
    print("#   Due: %s" % due)
    print("#   Link: %s" % card["shortUrl"])
    members = [str(trello.get("/members/%s/fullName" % id)["_value"]) for
               id in card["idMembers"]]
    members = ', '.join(members)
    if not members:
        members = "None"
    print ("#   Members: %s" % members)

print("This report provides a daily summary of Trello status.")
print

print("####################################################################")
print("# Blocked Epics:")
print("#")
blocked = 0
for card in next_cards:
    label_names = [n["name"] for n in card["labels"]]
    if "Blocked" in label_names and "EPIC" in label_names:
        print_card(card)
        blocked += 1
print("#")
print("# Summary: %d epics are blocked" % blocked)
print("####################################################################")
print
print

print("####################################################################")
print("# Epics requiring PM input:")
print("#")
pm_input = 0
for card in all_cards:
    label_names = [n["name"] for n in card["labels"]]
    if "PM Input needed" in label_names and "EPIC" in label_names:
        print_card(card)
        pm_input += 1
print("#")
print("# Summary: %d epics require PM input" % pm_input)
print("####################################################################")
print
print

print("####################################################################")
print("# Epics off track due to lack of owner:")
print("#")
no_owner = 0
for card in next_cards:
    label_names = [n["name"] for n in card["labels"]]
    if card["idMembers"] == [] and "EPIC" in label_names:
        print_card(card)
        no_owner += 1
print("#")
print("# Summary: %d epics are off track due to lack of owner" %
      no_owner)
print("####################################################################")
print
print

print("####################################################################")
print("# Epics off track with an owner but not in progress:")
print("#")
not_in_progress = 0
for card in next_cards:
    label_names = [n["name"] for n in card["labels"]]
    if card["idMembers"] and "EPIC" in label_names:
        print_card(card)
        not_in_progress += 1
print("#")
print("# Summary: %d epics are off track due to not in progress" %
      not_in_progress)
print("####################################################################")
print
print

print("####################################################################")
print("# Epics otherwise off track:")
print("#")
off_track = 0
for card in in_progress_list_cards:
    label_names = [n["name"] for n in card["labels"]]
    if "Off Track" in label_names and "EPIC" in label_names:
        print_card(card)
        off_track += 1
print("#")
print("# Summary: %d epics are otherwise off track" %
      off_track)
print("####################################################################")
print
print

print("####################################################################")
print("# Epics in progress: ")
print("#")
in_progress = 0
for card in in_progress_list_cards:
    label_names = [n["name"] for n in card["labels"]]
    if "Off Track" not in label_names and "EPIC" in label_names:
        print_card(card)
        in_progress += 1
print("#")
print("# Summary: %d epics are in progress" %
      in_progress)
print("####################################################################")
print
print

print("####################################################################")
print("# Epics dev complete:")
print("#")
dev_complete = 0
for card in dev_complete_list_cards:
    label_names = [n["name"] for n in card["labels"]]
    if "EPIC" in label_names:
        print_card(card)
        dev_complete += 1
print("#")
print("# Summary: %d epics are dev complete" % dev_complete)
print("####################################################################")
print
print

print("####################################################################")
print("# Epics qe accepted:")
print("#")
qe_accepted = 0
for card in qe_accepted_list_cards:
    label_names = [n["name"] for n in card["labels"]]
    if "EPIC" in label_names:
        print_card(card)
        qe_accepted += 1
print("#")
print("# Summary: %d epics are qe accepted" % qe_accepted)
print("####################################################################")
print
print

print("This report generated with trud: https://github.com/slagle/trud")
<commit_msg>We're not quite sure what CONFUSION is, but we're pretty sure it means "Corn Fusion": the process by which Corn atoms collide at a high rate of speed. The corn atoms fuse to create an entirely new molecule, Cornium.<commit_after># The MIT License (MIT)
#
# Copyright (c) 2016 James Slagle <james.slagle@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

import argparse
from datetime import datetime
from pprint import pprint
import requests

class Trello(object):

    def __init__(self, api_key, api_token):
        self.url = "https://api.trello.com/1/%s"
        self.api_key = api_key
        self.api_token = api_token
        self.payload = dict(key=self.api_key, token=self.api_token)

    def get(self, path):
        r = requests.get(self.url % path, params=self.payload)
        return r.json()

parser = argparse.ArgumentParser()
parser.add_argument("--api-key",
                    required=True,
                    help="Trello API key")
parser.add_argument("--api-token",
                    required=True,
                    help="Trello API token")
parser.add_argument("--board-name",
                    required=True,
                    help="Board name on which to report")
args = parser.parse_args()

trello = Trello(args.api_key, args.api_token)
board = [b for b in trello.get("/member/me/boards") \
            if b["name"] == args.board_name][0]
board_id = board["id"]
lists = trello.get("/boards/%s/lists" % board_id)

next_list = [l for l in lists if l["name"] == "Next"][0]
next_list_id = next_list["id"]
next_cards = trello.get("/lists/%s/cards" % next_list_id)

in_progress_list = [l for l in lists if l["name"] == "In Progress"][0]
in_progress_list_id = in_progress_list["id"]
in_progress_list_cards = trello.get("/lists/%s/cards" % in_progress_list_id)

dev_complete_list = [l for l in lists if l["name"] == "Dev Complete"][0]
dev_complete_list_id = dev_complete_list["id"]
dev_complete_list_cards = trello.get("/lists/%s/cards" % dev_complete_list_id)

qe_accepted_list = [l for l in lists if l["name"] == "QE Accepted (Done)"][0]
qe_accepted_list_id = qe_accepted_list["id"]
qe_accepted_list_cards = trello.get("/lists/%s/cards" % qe_accepted_list_id)

all_cards = trello.get("/boards/%s/cards" % board_id)

def print_card(card):
    due = card["due"]
    if due is not None:
        due = datetime.strptime(card["due"],
                "%Y-%m-%dT%H:%M:%S.%fZ")
        due = due.strftime("%B %d, %Y")
    print("# - %s" % card["name"])
    print("#   Due: %s" % due)
    print("#   Link: %s" % card["shortUrl"])
    members = [str(trello.get("/members/%s/fullName" % id)["_value"]) for
               id in card["idMembers"]]
    members = ', '.join(members)
    if not members:
        members = "None"
    print ("#   Members: %s" % members)

print("This report provides a daily summary of Trello status.")
print

print("####################################################################")
print("# Blocked Epics:")
print("#")
blocked = 0
for card in next_cards:
    label_names = [n["name"] for n in card["labels"]]
    if "Blocked" in label_names and "EPIC" in label_names:
        print_card(card)
        blocked += 1
print("#")
print("# Summary: %d epics are blocked" % blocked)
print("####################################################################")
print
print

print("####################################################################")
print("# Epics requiring PM input:")
print("#")
pm_input = 0
for card in all_cards:
    label_names = [n["name"] for n in card["labels"]]
    if "PM Input needed" in label_names and "EPIC" in label_names:
        print_card(card)
        pm_input += 1
print("#")
print("# Summary: %d epics require PM input" % pm_input)
print("####################################################################")
print
print

print("####################################################################")
print("# Epics off track due to lack of owner:")
print("#")
no_owner = 0
for card in next_cards:
    label_names = [n["name"] for n in card["labels"]]
    if card["idMembers"] == [] and "EPIC" in label_names:
        print_card(card)
        no_owner += 1
print("#")
print("# Summary: %d epics are off track due to lack of owner" %
      no_owner)
print("####################################################################")
print
print

print("####################################################################")
print("# Epics off track with an owner but not in progress:")
print("#")
not_in_progress = 0
for card in next_cards:
    label_names = [n["name"] for n in card["labels"]]
    if card["idMembers"] and "EPIC" in label_names:
        print_card(card)
        not_in_progress += 1
print("#")
print("# Summary: %d epics are off track due to not in progress" %
      not_in_progress)
print("####################################################################")
print
print

print("####################################################################")
print("# Epics otherwise off track:")
print("#")
off_track = 0
for card in in_progress_list_cards:
    label_names = [n["name"] for n in card["labels"]]
    if "Off Track" in label_names and "EPIC" in label_names:
        print_card(card)
        off_track += 1
print("#")
print("# Summary: %d epics are otherwise off track" %
      off_track)
print("####################################################################")
print
print

print("####################################################################")
print("# Epics in progress: ")
print("#")
in_progress = 0
for card in in_progress_list_cards:
    label_names = [n["name"] for n in card["labels"]]
    if "Off Track" not in label_names and "EPIC" in label_names:
        print_card(card)
        in_progress += 1
print("#")
print("# Summary: %d epics are in progress" %
      in_progress)
print("####################################################################")
print
print

print("####################################################################")
print("# Epics dev complete:")
print("#")
dev_complete = 0
for card in dev_complete_list_cards:
    label_names = [n["name"] for n in card["labels"]]
    if "EPIC" in label_names:
        print_card(card)
        dev_complete += 1
print("#")
print("# Summary: %d epics are dev complete" % dev_complete)
print("####################################################################")
print
print

print("####################################################################")
print("# Epics qe accepted:")
print("#")
qe_accepted = 0
for card in qe_accepted_list_cards:
    label_names = [n["name"] for n in card["labels"]]
    if "EPIC" in label_names:
        print_card(card)
        qe_accepted += 1
print("#")
print("# Summary: %d epics are qe accepted" % qe_accepted)
print("####################################################################")
print
print

print("This report generated with trud: https://github.com/slagle/trud")
print
<|endoftext|>


<commit_before>import re, sys
from itertools import tee

class Symbol:
    eof = "EOF"
    identifier = 'IDENT'
    integer = 'INT'
    float = 'FLOAT'
    string = 'STRING'
    keyword = 'KEYWORD'
    oparen = 'OPAREN'
    cparen = 'CPAREN'
    equal = 'EQUAL'
    scolon = 'SCOLON'

class Lexer:
    textmap = open("textmap.lmp").read()
    textpos = 0

    re_identifier = re.compile(r'[A-Za-z_]+[A-Za-z0-9_]*')
    re_integer = re.compile(r'[+-]?[0-9]+[0-9]*|0[0-9]+|0x[0-9A-Fa-f]+')
    re_float = re.compile(r'[+-]?[0-9]+\.[0-9]*([eE][+-]?[0-9]+)?')
    re_string = re.compile('"((?:[^"\\\\]|\\\\.)*)"')

    def scan(self):
        token = ''

        while True:
            self.consume(token)

            if self.textpos > len(self.textmap):
                raise Exception("textpos off the end of the string")

            if self.textpos == len(self.textmap):
                break # Done

            # Check for literals
            token = self.literal('{')
            if token != False:
                yield (Symbol.oparen,)
                continue

            token = self.literal('}')
            if token != False:
                yield (Symbol.cparen,)
                continue

            token = self.literal('=')
            if token != False:
                yield (Symbol.equal,)
                continue

            token = self.literal(';')
            if token != False:
                yield (Symbol.scolon,)
                continue

            # Check for complex terminals

            # A number can be a float or an integer, so check for
            # floats first because doing things the opposite way can
            # result in a truncated float as an integer.
            token, value = self.float()
            if token != False:
                yield (Symbol.float, value)
                continue

            token, value = self.integer()
            if token != False:
                yield (Symbol.integer, value)
                continue

            # Quoted strings
            token, value = self.string()
            if token != False:
                yield (Symbol.string, value)
                continue

            # Keywords
            token = self.keyword("true")
            if token != False:
                yield (Symbol.keyword, True)
                continue

            token = self.keyword("false")
            if token != False:
                yield (Symbol.keyword, False)
                continue

            # Idenfitiers
            token = self.identifier()
            if token != False:
                yield (Symbol.identifier, token)
                continue

            raise Exception("invalid syntax")

        yield (Symbol.eof,)

    # Consume the string and skip ahead to the next symbol, ignoring
    # all whitespace and comments.
    def consume(self, string):
        self.textpos += len(string)
        while True:
            char = self.textmap[self.textpos:self.textpos + 1]

            # Skip whitespace.
            if char == ' ' or char == '\r' or char == '\n':
                self.textpos += 1
                continue

            # Skip comments
            if char == '/':
                nextchar = self.textmap[self.textpos + 1:self.textpos + 2]
                if nextchar == '/':
                    found = self.textmap.find('\n', self.textpos)
                    self.textpos += found - self.textpos + 1
                    continue
                elif nextchar == '*':
                    found = self.textmap.find('*/', self.textpos)
                    self.textpos += found - self.textpos + 1
                    continue

            # We're at our next symbol.
            break

    ## Terminal Symbols ##

    def literal(self, char):
        if self.textmap[self.textpos:self.textpos + 1] == char:
            return char
        else:
            return False

    def keyword(self, string):
        if self.textmap[self.textpos:self.textpos + len(string)] == string:
            return string
        else:
            return False

    def identifier(self):
        match = self.re_identifier.match(self.textmap[self.textpos:])
        if match:
            return match.group(0)
        else:
            return False

    def integer(self):
        match = self.re_integer.match(self.textmap[self.textpos:])
        if match:
            return (match.group(0), int(match.group(0)))
        else:
            return (False, False)

    def float(self):
        match = self.re_float.match(self.textmap[self.textpos:])
        if match:
            return (match.group(0), float(match.group(0)))
        else:
            return (False, False)

    def string(self):
        match = self.re_string.match(self.textmap[self.textpos:])
        if match:
            return (match.group(0), match.group(1).replace('\\"', '"'))
        else:
            return (False, False)

class Parser:
    # Token generator
    tokens = None

    # Current token
    token = None

    def consume(self):
        self.token = next(self.tokens)

    ## Non-terminals ##

    def parse(self, tokens):
        self.tokens = tokens
        self.consume()

        self.global_expr_list()

    def global_expr_list(self):

        self.global_expr()

        if self.token[0] == Symbol.identifier:
            self.global_expr_list()
        elif self.token[0] == Symbol.eof:
            return
        else:
            raise Exception("expected identifier or EOF")

    def global_expr(self):
        # Look ahead one symbol and see if we have a valid block or
        # assignment_expr.
        self.tokens, lookahead = tee(self.tokens)
        looktoken = next(lookahead)
        if looktoken[0] == Symbol.oparen:
            self.block()
        elif looktoken[0] == Symbol.equal:
            self.assignment_expr()
        else:
            raise Exception('expected block or assignment expression')

    def block(self):
        if self.token[0] != Symbol.identifier:
            raise Exception('expected identifier')
        self.consume()

        if self.token[0] != Symbol.oparen:
            raise Exception('expected "{"')
        self.consume()

        self.expr_list()

        if self.token[0] != Symbol.cparen:
            raise Exception('expected "}"')
        self.consume()

    def expr_list(self):
        self.assignment_expr()
        if self.token[0] == Symbol.identifier:
            self.expr_list()

    def assignment_expr(self):
        if self.token[0] != Symbol.identifier:
            raise Exception('expected identifier')
        self.consume()

        if self.token[0] != Symbol.equal:
            raise Exception('expected "="')
        self.consume()

        self.value()

        if self.token[0] != Symbol.scolon:
            raise Exception('expected ";"')
        self.consume()

    def value(self):
        if self.token[0] == Symbol.integer:
            self.consume()
            return

        if self.token[0] == Symbol.float:
            self.consume()
            return

        if self.token[0] == Symbol.string:
            self.consume()
            return

        if self.token[0] == Symbol.keyword:
            self.consume()
            return

        raise Exception("expected value")

lex = Lexer()
parser = Parser()
parser.parse(lex.scan())
<commit_msg>Prevent stack overflow with iteration.<commit_after>import re
from itertools import tee

class Symbol:
    eof = "EOF"
    identifier = 'IDENT'
    integer = 'INT'
    float = 'FLOAT'
    string = 'STRING'
    keyword = 'KEYWORD'
    oparen = 'OPAREN'
    cparen = 'CPAREN'
    equal = 'EQUAL'
    scolon = 'SCOLON'

class Lexer:
    textmap = open("textmap.lmp").read()
    textpos = 0

    re_identifier = re.compile(r'[A-Za-z_]+[A-Za-z0-9_]*')
    re_integer = re.compile(r'[+-]?[0-9]+[0-9]*|0[0-9]+|0x[0-9A-Fa-f]+')
    re_float = re.compile(r'[+-]?[0-9]+\.[0-9]*([eE][+-]?[0-9]+)?')
    re_string = re.compile('"((?:[^"\\\\]|\\\\.)*)"')

    def scan(self):
        token = ''

        while True:
            self.consume(token)

            if self.textpos > len(self.textmap):
                raise Exception("textpos off the end of the string")

            if self.textpos == len(self.textmap):
                break # Done

            # Check for literals
            token = self.literal('{')
            if token != False:
                yield (Symbol.oparen,)
                continue

            token = self.literal('}')
            if token != False:
                yield (Symbol.cparen,)
                continue

            token = self.literal('=')
            if token != False:
                yield (Symbol.equal,)
                continue

            token = self.literal(';')
            if token != False:
                yield (Symbol.scolon,)
                continue

            # Check for complex terminals

            # A number can be a float or an integer, so check for
            # floats first because doing things the opposite way can
            # result in a truncated float as an integer.
            token, value = self.float()
            if token != False:
                yield (Symbol.float, value)
                continue

            token, value = self.integer()
            if token != False:
                yield (Symbol.integer, value)
                continue

            # Quoted strings
            token, value = self.string()
            if token != False:
                yield (Symbol.string, value)
                continue

            # Keywords
            token = self.keyword("true")
            if token != False:
                yield (Symbol.keyword, True)
                continue

            token = self.keyword("false")
            if token != False:
                yield (Symbol.keyword, False)
                continue

            # Idenfitiers
            token = self.identifier()
            if token != False:
                yield (Symbol.identifier, token)
                continue

            raise Exception("invalid syntax")

        yield (Symbol.eof,)

    # Consume the string and skip ahead to the next symbol, ignoring
    # all whitespace and comments.
    def consume(self, string):
        self.textpos += len(string)
        while True:
            char = self.textmap[self.textpos:self.textpos + 1]

            # Skip whitespace.
            if char == ' ' or char == '\r' or char == '\n':
                self.textpos += 1
                continue

            # Skip comments
            if char == '/':
                nextchar = self.textmap[self.textpos + 1:self.textpos + 2]
                if nextchar == '/':
                    found = self.textmap.find('\n', self.textpos)
                    self.textpos += found - self.textpos + 1
                    continue
                elif nextchar == '*':
                    found = self.textmap.find('*/', self.textpos)
                    self.textpos += found - self.textpos + 1
                    continue

            # We're at our next symbol.
            break

    ## Terminal Symbols ##

    def literal(self, char):
        if self.textmap[self.textpos:self.textpos + 1] == char:
            return char
        else:
            return False

    def keyword(self, string):
        if self.textmap[self.textpos:self.textpos + len(string)] == string:
            return string
        else:
            return False

    def identifier(self):
        match = self.re_identifier.match(self.textmap[self.textpos:])
        if match:
            return match.group(0)
        else:
            return False

    def integer(self):
        match = self.re_integer.match(self.textmap[self.textpos:])
        if match:
            return (match.group(0), int(match.group(0)))
        else:
            return (False, False)

    def float(self):
        match = self.re_float.match(self.textmap[self.textpos:])
        if match:
            return (match.group(0), float(match.group(0)))
        else:
            return (False, False)

    def string(self):
        match = self.re_string.match(self.textmap[self.textpos:])
        if match:
            return (match.group(0), match.group(1).replace('\\"', '"'))
        else:
            return (False, False)

class Parser:
    # Token generator
    tokens = None

    # Current token
    token = None

    def consume(self):
        self.token = next(self.tokens)

    ## Non-terminals ##

    def parse(self, tokens):
        self.tokens = tokens
        self.consume()

        self.global_expr_list()

    def global_expr_list(self):
        while True:
            self.global_expr()

            if self.token[0] == Symbol.identifier:
                continue
            elif self.token[0] == Symbol.eof:
                return
            else:
                raise Exception("expected identifier or EOF")

    def global_expr(self):
        # Look ahead one symbol and see if we have a valid block or
        # assignment_expr.
        self.tokens, lookahead = tee(self.tokens)
        looktoken = next(lookahead)
        if looktoken[0] == Symbol.oparen:
            self.block()
        elif looktoken[0] == Symbol.equal:
            self.assignment_expr()
        else:
            raise Exception('expected block or assignment expression')

    def block(self):
        if self.token[0] != Symbol.identifier:
            raise Exception('expected identifier')
        self.consume()

        if self.token[0] != Symbol.oparen:
            raise Exception('expected "{"')
        self.consume()

        self.expr_list()

        if self.token[0] != Symbol.cparen:
            raise Exception('expected "}"')
        self.consume()

    def expr_list(self):
        while True:
            self.assignment_expr()
            if self.token[0] == Symbol.identifier:
                continue
            else:
                return

    def assignment_expr(self):
        if self.token[0] != Symbol.identifier:
            raise Exception('expected identifier')
        self.consume()

        if self.token[0] != Symbol.equal:
            raise Exception('expected "="')
        self.consume()

        self.value()

        if self.token[0] != Symbol.scolon:
            raise Exception('expected ";"')
        self.consume()

    def value(self):
        if self.token[0] == Symbol.integer:
            self.consume()
            return

        if self.token[0] == Symbol.float:
            self.consume()
            return

        if self.token[0] == Symbol.string:
            self.consume()
            return

        if self.token[0] == Symbol.keyword:
            self.consume()
            return

        raise Exception("expected value")

lex = Lexer()
parser = Parser()
parser.parse(lex.scan())
<|endoftext|>


<commit_before>from django.conf.urls.defaults import *

from django.contrib import admin
from django.conf import settings

from haystack.forms import FacetedSearchForm
from haystack.query import SearchQuerySet
from haystack.views import FacetedSearchView

from core.forms import UserProfileForm

admin.autodiscover()
author_sqs = SearchQuerySet().facet('author')
project_sqs = SearchQuerySet().facet('project')

handler500 = 'core.views.server_error'
handler404 = 'core.views.server_error_404'

urlpatterns = patterns('',
    url(r'^$', 'core.views.homepage'),
    url(r'^docs/(?P<project_slug>[-\w]+)/(?P<version_slug>latest)/(?P<filename>.*)$',
        'core.views.serve_docs',
        name='docs_detail'
    ),
    url(r'^docs/(?P<project_slug>[-\w]+)/(?P<version_slug>[-\w]+?)/(?P<filename>.*)$',
        'core.views.serve_docs',
        name='docs_detail'
    ),
    url(r'^docs/(?P<project_slug>[-\w]+)/(?P<filename>.*)$',
        'core.views.serve_docs',
        {'version_slug': None},
        name='docs_detail'
    ),
    url(r'^projects/', include('projects.urls.public')),
    url(r'^builds/', include('builds.urls')),
    url(r'^bookmarks/', include('bookmarks.urls')),
    url(r'^flagging/', include('basic.flagging.urls')),
    url(r'^views/', include('watching.urls')),
    url(r'^accounts/', include('registration.backends.default.urls')),
    url(r'^search/author/',
        FacetedSearchView(form_class=FacetedSearchForm,
                          searchqueryset=author_sqs,
                          template="search/faceted_author.html"),
        name='haystack_author'),
    url(r'^search/project/',
        FacetedSearchView(form_class=FacetedSearchForm,
                          searchqueryset=project_sqs,
                          template="search/faceted_project.html"),
        name='haystack_project'),
    url(r'^search/', include('haystack.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^dashboard/bookmarks/',
        'bookmarks.views.user_bookmark_list',
        name='user_bookmarks'
    ),
    url(r'^dashboard/', include('projects.urls.private')),
    url(r'^github', 'core.views.github_build', name='github_build'),
    url(r'^build/(?P<pk>\d+)', 'core.views.generic_build', name='generic_build'),

    url(r'^random/', 'core.views.random_page', name='random_page'),

    url(r'^render_header/',
        'core.views.render_header',
        name='render_header'
    ),
    url(r'^profiles/create/', 'profiles.views.create_profile',
        {'form_class': UserProfileForm},
       name='profiles_profile_create'),
    url(r'^profiles/edit/', 'profiles.views.edit_profile',
        {'form_class': UserProfileForm},
       name='profiles_profile_edit'),
    url(r'^profiles/', include('profiles.urls')),
)

if settings.DEBUG:
    urlpatterns += patterns('',
        url(
            regex  = '^%s/(?P<path>.*)$' % settings.MEDIA_URL.strip('/'),
            view   = 'django.views.static.serve',
            kwargs = {'document_root': settings.MEDIA_ROOT},
        )
    )
<commit_msg>fixed urls.py also accepting new-slugs<commit_after>from django.conf.urls.defaults import *

from django.contrib import admin
from django.conf import settings

from haystack.forms import FacetedSearchForm
from haystack.query import SearchQuerySet
from haystack.views import FacetedSearchView

from core.forms import UserProfileForm

admin.autodiscover()
author_sqs = SearchQuerySet().facet('author')
project_sqs = SearchQuerySet().facet('project')

handler500 = 'core.views.server_error'
handler404 = 'core.views.server_error_404'

urlpatterns = patterns('',
    url(r'^$', 'core.views.homepage'),
    url(r'^docs/(?P<project_slug>[-\w]+)/(?P<version_slug>latest)/(?P<filename>.*)$',
        'core.views.serve_docs',
        name='docs_detail'
    ),
    url(r'^docs/(?P<project_slug>[-\w]+)/(?P<version_slug>[-._\w]+?)/(?P<filename>.*)$',
        'core.views.serve_docs',
        name='docs_detail'
    ),
    url(r'^docs/(?P<project_slug>[-\w]+)/(?P<filename>.*)$',
        'core.views.serve_docs',
        {'version_slug': None},
        name='docs_detail'
    ),
    url(r'^projects/', include('projects.urls.public')),
    url(r'^builds/', include('builds.urls')),
    url(r'^bookmarks/', include('bookmarks.urls')),
    url(r'^flagging/', include('basic.flagging.urls')),
    url(r'^views/', include('watching.urls')),
    url(r'^accounts/', include('registration.backends.default.urls')),
    url(r'^search/author/',
        FacetedSearchView(form_class=FacetedSearchForm,
                          searchqueryset=author_sqs,
                          template="search/faceted_author.html"),
        name='haystack_author'),
    url(r'^search/project/',
        FacetedSearchView(form_class=FacetedSearchForm,
                          searchqueryset=project_sqs,
                          template="search/faceted_project.html"),
        name='haystack_project'),
    url(r'^search/', include('haystack.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^dashboard/bookmarks/',
        'bookmarks.views.user_bookmark_list',
        name='user_bookmarks'
    ),
    url(r'^dashboard/', include('projects.urls.private')),
    url(r'^github', 'core.views.github_build', name='github_build'),
    url(r'^build/(?P<pk>\d+)', 'core.views.generic_build', name='generic_build'),

    url(r'^random/', 'core.views.random_page', name='random_page'),

    url(r'^render_header/',
        'core.views.render_header',
        name='render_header'
    ),
    url(r'^profiles/create/', 'profiles.views.create_profile',
        {'form_class': UserProfileForm},
       name='profiles_profile_create'),
    url(r'^profiles/edit/', 'profiles.views.edit_profile',
        {'form_class': UserProfileForm},
       name='profiles_profile_edit'),
    url(r'^profiles/', include('profiles.urls')),
)

if settings.DEBUG:
    urlpatterns += patterns('',
        url(
            regex  = '^%s/(?P<path>.*)$' % settings.MEDIA_URL.strip('/'),
            view   = 'django.views.static.serve',
            kwargs = {'document_root': settings.MEDIA_ROOT},
        )
    )
<|endoftext|>


<commit_before>from django.conf.urls.defaults import patterns, include, url
from virtmgr import settings
from registration.forms import RegistrationFormUniqueEmail
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Users
    url(r'^user/register/$', 'registration.views.register', {'form_class': RegistrationFormUniqueEmail, 'backend': 'registration.backends.default.DefaultBackend'}, name='registration_register'),
    url(r'^user/', include('registration.urls')),
    url(r'^user/profile/$', include('registration.urls')),

    # Static pages
    url(r'^$', 'virtmgr.pages.views.index'),
    url(r'^features/', 'virtmgr.pages.views.features'),
    url(r'^support/', 'virtmgr.pages.views.support'),
    url(r'^docs/$', 'virtmgr.pages.views.docs'),
    url(r'^docs/settings/', 'virtmgr.pages.views.settings'),
    url(r'^docs/faq/', 'virtmgr.pages.views.faq'),

    # Host
    url(r'^dashboard/$', 'virtmgr.dashboard.views.index'),

    # NewVM
    url(r'^newvm/(\w+)/$', 'virtmgr.newvm.views.index'),
    url(r'^newvm/', 'virtmgr.newvm.views.redir'),

    # Overview
    url(r'^overview/(\w+)/$', 'virtmgr.overview.views.index'),
    url(r'^overview/', 'virtmgr.overview.views.redir'),

    # Storage
    url(r'^storage/(\w+)/$', 'virtmgr.storage.views.index'),
    url(r'^storage/(\w+)/(\w+)/$', 'virtmgr.storage.views.pool'),
    url(r'^storage/', 'virtmgr.storage.views.redir'),

    # Network
    url(r'^network/(\w+)/$', 'virtmgr.network.views.index'),
    url(r'^network/(\w+)/(\w+)/$', 'virtmgr.network.views.pool'),
    url(r'^network/', 'virtmgr.network.views.redir'),

    # Interfaces
    #url(r'^interfaces/(\w+)/$', 'virtmgr.interfaces.views.index'),
    #url(r'^interfaces/(\w+)/(\w+)/$', 'virtmgr.interfaces.views.ifcfg'),
    #url(r'^interfaces/', 'virtmgr.interfaces.views.redir'),

    # VM
    url(r'^vm/(\w+)/(\w+)/$', 'virtmgr.vm.views.index'),
    url(r'^vm/(\w+)/$', 'virtmgr.vm.views.redir_two'),
    url(r'^vm/', 'virtmgr.vm.views.redir_one'),

    # VNC
    url(r'^vnc/(\w+)/(\w+)/$', 'virtmgr.vnc.views.index'),
    url(r'^vnc/(\w+)/$', 'virtmgr.vnc.views.redir_two'),
    url(r'^vnc/', 'virtmgr.vnc.views.redir_one'),

    # Media
    url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': False}),

    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
)
<commit_msg>Add screenshot<commit_after>from django.conf.urls.defaults import patterns, include, url
from virtmgr import settings
from registration.forms import RegistrationFormUniqueEmail
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Users
    url(r'^user/register/$', 'registration.views.register', {'form_class': RegistrationFormUniqueEmail, 'backend': 'registration.backends.default.DefaultBackend'}, name='registration_register'),
    url(r'^user/', include('registration.urls')),
    url(r'^user/profile/$', include('registration.urls')),

    # Static pages
    url(r'^$', 'virtmgr.pages.views.index'),
    url(r'^features/', 'virtmgr.pages.views.features'),
    url(r'^support/', 'virtmgr.pages.views.support'),
    url(r'^screenshot/', 'virtmgr.pages.views.screenshot'),
    url(r'^docs/$', 'virtmgr.pages.views.docs'),
    url(r'^docs/settings/', 'virtmgr.pages.views.settings'),
    url(r'^docs/faq/', 'virtmgr.pages.views.faq'),

    # Host
    url(r'^dashboard/$', 'virtmgr.dashboard.views.index'),

    # NewVM
    url(r'^newvm/(\w+)/$', 'virtmgr.newvm.views.index'),
    url(r'^newvm/', 'virtmgr.newvm.views.redir'),

    # Overview
    url(r'^overview/(\w+)/$', 'virtmgr.overview.views.index'),
    url(r'^overview/', 'virtmgr.overview.views.redir'),

    # Storage
    url(r'^storage/(\w+)/$', 'virtmgr.storage.views.index'),
    url(r'^storage/(\w+)/(\w+)/$', 'virtmgr.storage.views.pool'),
    url(r'^storage/', 'virtmgr.storage.views.redir'),

    # Network
    url(r'^network/(\w+)/$', 'virtmgr.network.views.index'),
    url(r'^network/(\w+)/(\w+)/$', 'virtmgr.network.views.pool'),
    url(r'^network/', 'virtmgr.network.views.redir'),

    # Interfaces
    #url(r'^interfaces/(\w+)/$', 'virtmgr.interfaces.views.index'),
    #url(r'^interfaces/(\w+)/(\w+)/$', 'virtmgr.interfaces.views.ifcfg'),
    #url(r'^interfaces/', 'virtmgr.interfaces.views.redir'),

    # VM
    url(r'^vm/(\w+)/(\w+)/$', 'virtmgr.vm.views.index'),
    url(r'^vm/(\w+)/$', 'virtmgr.vm.views.redir_two'),
    url(r'^vm/', 'virtmgr.vm.views.redir_one'),

    # VNC
    url(r'^vnc/(\w+)/(\w+)/$', 'virtmgr.vnc.views.index'),
    url(r'^vnc/(\w+)/$', 'virtmgr.vnc.views.redir_two'),
    url(r'^vnc/', 'virtmgr.vnc.views.redir_one'),

    # Media
    url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': False}),

    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
)
<|endoftext|>


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

#
# ekm
#
# Numerically integrate only the octupole term of the equations of motion of
# a hierarchical triple.  This procedure averages over not only the
# individual orbits, but also the individual KL cycles as well.
#

import json
import sys
import time
import random
import numpy as np
from scipy.integrate import ode, quad
from scipy.optimize import brentq
from scipy.special import ellipk, ellipe
import astropy.constants as const
import astropy.units as unit

class Triple_octupole:
  '''A hierachical triple where only the octupole term of the Hamiltonian is
  considered.  The quadrupole term is averaged over.

  Parameters:
    e1: Inner eccentricity
    e2: Outer eccentricity
    a1: Inner semi-major axis in AU
    a2: OUter semi-major axis in AU
    inc: Inclination in degrees
    argperi: Argument of periastron in degrees
    longascnode: Longitude of ascending node in degrees

    epsoct: e2 / (1 - e2^2) * (a1 / a2)
    phiq: The value of the quadrupole term of the Hamiltonian
    Xi: The other integral of motion of the octupole term

    tstop: The time to integrate (units of t_KL)
    cputstop: The number of CPU seconds to integrate for
    outfreq: Print out state every n steps (-1 for no output)
    outfile: Filename to write output to (None for stdout)
    atol: Absolute tolerance of the integrator
    rtol: Relative tolerance of the integrator
  '''

  # Some useful constants
  G = const.G.value
  c = const.c.value
  yr2s = 3.15576e7
  au = const.au.value

  def __init__(self, a1=1, a2=20, e1=.1, e2=.3, inc=80, longascnode=180,
    argperi=0, epsoct=None, phiq=None, Xi=None, tstop=1e3, cputstop=300,
    outfreq=1, outfilename=None, atol=1e-9, rtol=1e-9):

    #
    # Given parameters
    #
    self.a1 = a1
    self.a2 = a2
    self.e1 = e1
    self.e2 = e2
    self.inc = inc
    self.Omega = longascnode * np.pi / 180
    self.omega = argperi * np.pi / 180

    #
    # Derived parameters
    #
    self.cosi = np.cos(inc * np.pi / 180)
    self.j = np.sqrt(1 - e1**2)
    self.jz = self.j * self.cosi

    # We don't use calc_CKL() at first because we need CKL to calculate Xi.
    self.CKL = (self.e1**2 * (1 - 5/2. * (1 - self.cosi**2) *
      np.sin(self.omega)**2))

    if phiq is None:
      self.phiq = self.CKL + self.jz**2 / 2.
    else:
      self.phiq = phiq
      self.jz = 0
      self.CKL = self.phiq
    if epsoct is None:
      self.epsoct = self.e2 / (1 - self.e2**2) * (self.a1 / self.a2)
    else:
      self.epsoct = epsoct
    if Xi is None:
      self.Xi = F(self.CKL) - self.epsoct * np.cos(self.Omega)
    else:
      self.Xi = Xi
      self.Omega = np.arccos((F(self.CKL) - self.Xi) / self.epsoct)

    self.set_x()
    self.set_fj()
    self.set_fOmega()

    #
    # Integration parameters
    #
    self.nstep = 0
    self.t = 0
    self.tstop = tstop
    self.cputstop = cputstop
    self.outfreq = outfreq
    self.outfilename = outfilename
    self.integration_algo = 'vode'
    self.y = [self.jz, self.Omega]
    self.tol = 1e-9

    if self.outfilename is not None:
      self.outfile = open(self.outfilename, 'w')

    # Set up the integrator
    self.solver = ode(self._deriv)
    self.solver.set_integrator(self.integration_algo, nsteps=1, atol=atol,
      rtol=rtol)
    self.solver.set_initial_value(self.y, self.t).set_f_params(self.epsoct,
      self.phiq)
    self.solver._integrator.iwork[2] = -1 # Don't print FORTRAN errors

  def _deriv(self, t, y, epsoct, phiq):
    # Eqs. 11 of Katz (2011)
    jz, Omega = y
    CKL = phiq - jz**2 / 2.
    x = (3 - 3 * CKL) / (3 + 2 * CKL)
    fj = (15 * np.pi / (128 * np.sqrt(10)) / ellipk(x) * (4 - 11 * CKL)
      * np.sqrt(6 + 4 * CKL))
    fOmega = ((6 * ellipe(x) - 3 * ellipk(x)) / (4 * ellipk(x)))

    jzdot = -epsoct * fj * np.sin(Omega)
    Omegadot = jz * fOmega

    return [jzdot, Omegadot]

  def _step(self):
    self.solver.integrate(self.tstop, step=True)

    self.t = self.solver.t
    self.jz, self.Omega = self.solver.y

    # Update all the parameters
    self.set_CKL()
    self.set_x()
    self.set_fj()
    self.set_fOmega()
    self.nstep += 1

  def set_CKL(self):
    self.CKL = self.calc_CKL()

  def calc_CKL(self):
    return self.phiq - self.jz**2 / 2.

  def calc_x(self):
    return (3 - 3 * self.CKL) / (3 + 2 * self.CKL)

  def set_x(self):
    self.x = self.calc_x()

  def calc_fj(self):
    return (15 * np.pi / (128 * np.sqrt(10)) / ellipk(self.x) *
      (4 - 11 * self.CKL) * np.sqrt(6 + 4 * self.CKL))

  def set_fj(self):
    self.fj = self.calc_fj()

  def calc_fOmega(self):
    return ((6 * ellipe(self.x) - 3 * ellipk(self.x)) / (4 *
      ellipk(self.x)))

  def set_fOmega(self):
    self.fOmega = self.calc_fOmega()

  def integrate(self):
    '''Integrate the triple in time.'''
    self.printout()
    while self.t < self.tstop:
      self._step()
      if self.nstep % self.outfreq == 0:
        self.printout()

    self.printout()
    self.outfile.close()

  def printout(self):
    '''Print out the state of the system in the format:

    time  jz  Omega  <f_j>  <f_Omega>  x  C_KL

    '''
    outstring = ' '.join(map(str, [self.t, self.jz, self.Omega, self.fj,
      self.fOmega, self.x, self.CKL]))
    if self.outfilename is None:
      print outstring
    else:
      self.outfile.write(outstring + '\n')

  def period(self):
    '''Analytically calculate the period of EKM oscillations.'''

    # First calculate the limits.
    xcrit = brentq(lambda x: ellipk(x) - 2 * ellipe(x), 0, 1)
    phicrit = 3 * (1 - xcrit) / (3 + 2 * xcrit)

    if self.phiq < phicrit:
      CKLmin = brentq(lambda CKL: self.Xi - self.epsoct - F(CKL), self.tol, self.phiq)
    else:
      CKLmin = brentq(lambda CKL: self.Xi + self.epsoct - F(CKL), self.tol, self.phiq)
    if self.doesflip():
      CKLmax = self.phiq
    else:
      CKLmax = brentq(lambda CKL: self.Xi + self.epsoct - F(CKL), 0, 1)

    prefactor = 256 * np.sqrt(10) / (15 * np.pi) / self.epsoct
    P = quad(lambda CKL: (prefactor * ellipk((3 - 3*CKL)/(3 + 2*CKL)) /
      (4 - 11*CKL) / np.sqrt(6 + 4*CKL) / np.sqrt(1 - 1/self.epsoct**2 *
      (F(CKL) - self.Xi)**2) / np.sqrt(2* np.fabs(self.phiq - CKL))),
      CKLmin, CKLmax, epsabs=1e-12, epsrel=1e-12, limit=100)

    return P[0]

  def doesflip(self):
    '''Return True if the triple flips, false otherwise.  This is determined
    using Eq. 16 of Katz (2011).
    '''

    #
    # Calculate Delta F over many values of x.  x can range from
    #
    # C_KL < x < C_KL + j_z^2 / 2
    #
    X = np.linspace(self.CKL, self.CKL + (self.jz)**2 / 2.)
    DeltaF = np.fabs(np.array(map(F, X)) - F(self.CKL))

    epsoct_crit = np.max(DeltaF) / 2.

    if self.epsoct > epsoct_crit:
      return True
    else:
      return False

  def __exit__(self):
    self.outfile.close()

def _F_integrand(x):
  return (ellipk(x) - 2 * ellipe(x)) / (41*x - 21) / np.sqrt(2*x + 3)

def F(CKL):
  x_low = (3 - 3 * CKL) / (3 + 2 * CKL)
  integral = quad(_F_integrand, x_low, 1)[0]
  return 32 * np.sqrt(3) / np.pi * integral

if __name__ == '__main__':
  triple = Triple_octupole(epsoct=.01, tstop=400)
  triple.integrate()
<commit_msg>Improved limit calculation in period method<commit_after>#! /usr/bin/env python

#
# ekm
#
# Numerically integrate only the octupole term of the equations of motion of
# a hierarchical triple.  This procedure averages over not only the
# individual orbits, but also the individual KL cycles as well.
#

import json
import sys
import time
import random
import numpy as np
from scipy.integrate import ode, quad
from scipy.optimize import brentq
from scipy.special import ellipk, ellipe
import astropy.constants as const
import astropy.units as unit

class Triple_octupole:
  '''A hierachical triple where only the octupole term of the Hamiltonian is
  considered.  The quadrupole term is averaged over.

  Parameters:
    e1: Inner eccentricity
    e2: Outer eccentricity
    a1: Inner semi-major axis in AU
    a2: OUter semi-major axis in AU
    inc: Inclination in degrees
    argperi: Argument of periastron in degrees
    longascnode: Longitude of ascending node in degrees

    epsoct: e2 / (1 - e2^2) * (a1 / a2)
    phiq: The value of the quadrupole term of the Hamiltonian
    Xi: The other integral of motion of the octupole term

    tstop: The time to integrate (units of t_KL)
    cputstop: The number of CPU seconds to integrate for
    outfreq: Print out state every n steps (-1 for no output)
    outfile: Filename to write output to (None for stdout)
    atol: Absolute tolerance of the integrator
    rtol: Relative tolerance of the integrator
  '''

  # Some useful constants
  G = const.G.value
  c = const.c.value
  yr2s = 3.15576e7
  au = const.au.value

  def __init__(self, a1=1, a2=20, e1=.1, e2=.3, inc=80, longascnode=180,
    argperi=0, epsoct=None, phiq=None, Xi=None, tstop=1e3, cputstop=300,
    outfreq=1, outfilename=None, atol=1e-9, rtol=1e-9):

    #
    # Given parameters
    #
    self.a1 = a1
    self.a2 = a2
    self.e1 = e1
    self.e2 = e2
    self.inc = inc
    self.Omega = longascnode * np.pi / 180
    self.omega = argperi * np.pi / 180

    #
    # Derived parameters
    #
    self.cosi = np.cos(inc * np.pi / 180)
    self.j = np.sqrt(1 - e1**2)
    self.jz = self.j * self.cosi

    # We don't use calc_CKL() at first because we need CKL to calculate Xi.
    self.CKL = (self.e1**2 * (1 - 5/2. * (1 - self.cosi**2) *
      np.sin(self.omega)**2))

    if phiq is None:
      self.phiq = self.CKL + self.jz**2 / 2.
    else:
      self.phiq = phiq
      self.jz = 0
      self.CKL = self.phiq
    if epsoct is None:
      self.epsoct = self.e2 / (1 - self.e2**2) * (self.a1 / self.a2)
    else:
      self.epsoct = epsoct
    if Xi is None:
      self.Xi = F(self.CKL) - self.epsoct * np.cos(self.Omega)
    else:
      self.Xi = Xi
      self.Omega = np.arccos((F(self.CKL) - self.Xi) / self.epsoct)

    self.set_x()
    self.set_fj()
    self.set_fOmega()

    #
    # Integration parameters
    #
    self.nstep = 0
    self.t = 0
    self.tstop = tstop
    self.cputstop = cputstop
    self.outfreq = outfreq
    self.outfilename = outfilename
    self.integration_algo = 'vode'
    self.y = [self.jz, self.Omega]
    self.tol = 1e-9

    if self.outfilename is not None:
      self.outfile = open(self.outfilename, 'w')

    # Set up the integrator
    self.solver = ode(self._deriv)
    self.solver.set_integrator(self.integration_algo, nsteps=1, atol=atol,
      rtol=rtol)
    self.solver.set_initial_value(self.y, self.t).set_f_params(self.epsoct,
      self.phiq)
    self.solver._integrator.iwork[2] = -1 # Don't print FORTRAN errors

  def _deriv(self, t, y, epsoct, phiq):
    # Eqs. 11 of Katz (2011)
    jz, Omega = y
    CKL = phiq - jz**2 / 2.
    x = (3 - 3 * CKL) / (3 + 2 * CKL)
    fj = (15 * np.pi / (128 * np.sqrt(10)) / ellipk(x) * (4 - 11 * CKL)
      * np.sqrt(6 + 4 * CKL))
    fOmega = ((6 * ellipe(x) - 3 * ellipk(x)) / (4 * ellipk(x)))

    jzdot = -epsoct * fj * np.sin(Omega)
    Omegadot = jz * fOmega

    return [jzdot, Omegadot]

  def _step(self):
    self.solver.integrate(self.tstop, step=True)

    self.t = self.solver.t
    self.jz, self.Omega = self.solver.y

    # Update all the parameters
    self.set_CKL()
    self.set_x()
    self.set_fj()
    self.set_fOmega()
    self.nstep += 1

  def set_CKL(self):
    self.CKL = self.calc_CKL()

  def calc_CKL(self):
    return self.phiq - self.jz**2 / 2.

  def calc_x(self):
    return (3 - 3 * self.CKL) / (3 + 2 * self.CKL)

  def set_x(self):
    self.x = self.calc_x()

  def calc_fj(self):
    return (15 * np.pi / (128 * np.sqrt(10)) / ellipk(self.x) *
      (4 - 11 * self.CKL) * np.sqrt(6 + 4 * self.CKL))

  def set_fj(self):
    self.fj = self.calc_fj()

  def calc_fOmega(self):
    return ((6 * ellipe(self.x) - 3 * ellipk(self.x)) / (4 *
      ellipk(self.x)))

  def set_fOmega(self):
    self.fOmega = self.calc_fOmega()

  def integrate(self):
    '''Integrate the triple in time.'''
    self.printout()
    while self.t < self.tstop:
      self._step()
      if self.nstep % self.outfreq == 0:
        self.printout()

    self.printout()
    self.outfile.close()

  def printout(self):
    '''Print out the state of the system in the format:

    time  jz  Omega  <f_j>  <f_Omega>  x  C_KL

    '''
    outstring = ' '.join(map(str, [self.t, self.jz, self.Omega, self.fj,
      self.fOmega, self.x, self.CKL]))
    if self.outfilename is None:
      print outstring
    else:
      self.outfile.write(outstring + '\n')

  def period(self):
    '''Analytically calculate the period of EKM oscillations.'''

    # First calculate the limits.
    xcrit = brentq(lambda x: ellipk(x) - 2 * ellipe(x), 0, 1)
    phicrit = 3 * (1 - xcrit) / (3 + 2 * xcrit)

    if self.phiq < phicrit:
      CKLmin = brentq(lambda CKL: self.Xi - self.epsoct - F(CKL), self.tol, self.phiq)
    else:
      # Check if flips occur for Omega = Pi or 0
      if (np.sign(self.Xi - self.epsoct - F(self.tol)) !=
          np.sign(self.Xi - self.epsoct - F(self.phiq))):
        CKLmin = brentq(lambda CKL: self.Xi - self.epsoct - F(CKL), self.tol, self.phiq)
      else:
        CKLmin = brentq(lambda CKL: self.Xi + self.epsoct - F(CKL), self.tol, self.phiq)
    if self.doesflip():
      CKLmax = self.phiq
    else:
      CKLmax = brentq(lambda CKL: self.Xi + self.epsoct - F(CKL), 0, 1)

    prefactor = 256 * np.sqrt(10) / (15 * np.pi) / self.epsoct
    P = quad(lambda CKL: (prefactor * ellipk((3 - 3*CKL)/(3 + 2*CKL)) /
      (4 - 11*CKL) / np.sqrt(6 + 4*CKL) / np.sqrt(1 - 1/self.epsoct**2 *
      (F(CKL) - self.Xi)**2) / np.sqrt(2* np.fabs(self.phiq - CKL))),
      CKLmin, CKLmax, epsabs=1e-12, epsrel=1e-12, limit=100)

    return P[0]

  def doesflip(self):
    '''Return True if the triple flips, false otherwise.  This is determined
    using Eq. 16 of Katz (2011).
    '''

    #
    # Calculate Delta F over many values of x.  x can range from
    #
    # C_KL < x < C_KL + j_z^2 / 2
    #
    X = np.linspace(self.CKL, self.CKL + (self.jz)**2 / 2.)
    DeltaF = np.fabs(np.array(map(F, X)) - F(self.CKL))

    epsoct_crit = np.max(DeltaF) / 2.

    if self.epsoct > epsoct_crit:
      return True
    else:
      return False

  def __exit__(self):
    self.outfile.close()

def _F_integrand(x):
  return (ellipk(x) - 2 * ellipe(x)) / (41*x - 21) / np.sqrt(2*x + 3)

def F(CKL):
  x_low = (3 - 3 * CKL) / (3 + 2 * CKL)
  integral = quad(_F_integrand, x_low, 1)[0]
  return 32 * np.sqrt(3) / np.pi * integral

if __name__ == '__main__':
  triple = Triple_octupole(epsoct=.01, tstop=400)
  triple.integrate()
<|endoftext|>


<commit_before>from django.conf.urls.defaults import *

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Inschrijf formulier
    (r'^inschrijven/(?P<slug>[\w-]+)/$', 'subscribe.views.register'),

    (r'^check/$', 'subscribe.views.check'),
    (r'^refresh_issuers/$', 'subscribe.views.refresh_issuers'),
    (r'^updateEventTransactionStatuses/$', 'subscribe.views.update_all_event_transaction_statuses'),
    (r'^updateTransactionStatus/$', 'subscribe.views.update_transaction_status'),

    # Uncomment the admin/doc line below to enable admin documentation:
    (r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    (r'^admin/', include(admin.site.urls)),
)
<commit_msg>Removed some more wild includes.<commit_after>from django.conf.urls.defaults import include, patterns

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Inschrijf formulier
    (r'^inschrijven/(?P<slug>[\w-]+)/$', 'subscribe.views.register'),

    (r'^check/$', 'subscribe.views.check'),
    (r'^refresh_issuers/$', 'subscribe.views.refresh_issuers'),
    (r'^updateEventTransactionStatuses/$', 'subscribe.views.update_all_event_transaction_statuses'),
    (r'^updateTransactionStatus/$', 'subscribe.views.update_transaction_status'),

    # Uncomment the admin/doc line below to enable admin documentation:
    (r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    (r'^admin/', include(admin.site.urls)),
)
<|endoftext|>


<commit_before>from typing import *

import cog

String = str
Int = int
Float = float
Bool = bool
Maybe = Optional

def lower_first(s):
    return s[0].lower() + s[1:]

class ElmLiteral:
    def __init__(self, s):
        self.s = s

    def __str__(self):
        return self.s

def elm_literal(s):
    if isinstance(s, ElmLiteral):
        return str(s)

    if isinstance(s, str):
        return f'"{s}"'

    return f'{s}'

def elm_type_by_python_type(t):
    if isinstance(t, ElmLiteral):
        return str(t)

    typing_origin = getattr(t, '__origin__', None)
    if typing_origin is List:
        return f'( List {elm_type_by_python_type(t.__args__[0])} )'

    if typing_origin is Dict:
        return f'( Dict {elm_type_by_python_type(t.__args__[0])} {elm_type_by_python_type(t.__args__[1])} )'

    if typing_origin is Union and t.__args__[1] is type(None):
        return f'( Maybe {elm_type_by_python_type(t.__args__[0])} )'

    if '_ForwardRef' in str(t):
        return t.__forward_arg__

    return {
        int: 'Int',
        float: 'Float',
        str: 'String',
        bool: 'Bool',
    }.get(t, t)

def parse_list(items: Union[tuple, list, str]):
    if isinstance(items, (tuple, list)):
        return items
    return [x.strip() for x in items.split(',')]

def _indent(s):
    lines = s.split('\n')
    return '\n'.join(['    ' + x if x else '' for x in lines])

def indent(s, levels=1):
    result = s
    for i in range(levels):
        result = _indent(result)
    return result

def elm_whitespace(f):
    def wrapper(*args, **kwargs):
        cog.out('\n\n')
        f(*args, **kwargs)
        cog.out('\n\n\n\n')
    return wrapper

def _list_single_line(items, *, start_char='[', end_char=']', item_separator_char=','):
    if not isinstance(items, list):
        items = parse_list(items)

    if not items:
        return f'{start_char}{end_char}'

    r = f'{start_char} {items[0]}'

    for item in items[1:]:
        r += f'{item_separator_char} {item}'

    if end_char:
        r += f' {end_char}'

    return r

def _list(items, *, start_char='[', end_char=']', item_separator_char=','):
    if not isinstance(items, list):
        items = parse_list(items)

    if not items:
        return f'{start_char}{end_char}\n'

    r = f'{start_char} {items[0]}'

    for item in items[1:]:
        r += f'\n{item_separator_char} {item}'

    if end_char:
        r += f'\n{end_char}'

    return r

@elm_whitespace
def list_of(name, items, *, start_char='[', end_char=']', item_separator_char=',', single_line=False):
    cog.outl(f'{name} =')
    f = _list_single_line if single_line else _list
    cog.out(indent(f(
        items=items,
        start_char=start_char,
        end_char=end_char,
        item_separator_char=item_separator_char,
    )))

def _union(name, definition):
    return f'type {name}\n' + indent(_list(
        items=definition,
        start_char='=',
        end_char='',
        item_separator_char='|',
    ))

@elm_whitespace
def union(name, definition):
    cog.out(_union(name=name, definition=definition))

def _enum(name, definition):
    return f"""{_union(name, definition)}

{lower_first(name)}_list =
    {_list_single_line(definition)}"""

@elm_whitespace
def enum(name, definition):
    cog.out(_enum(name=name, definition=definition))

def _type_alias(name, type_info):
    return f'type alias {name} =\n' + indent(_list(
        items=[f'{item} : {elm_type_by_python_type(type_info[item])}' for item in type_info.keys()],
        start_char='{',
        end_char='}',
    ))

@elm_whitespace
def type_alias(name, type_info):
    cog.out(_type_alias(name=name, type_info=type_info))

def _type_alias_with_json(name, type_info, decoder, encoder):
    r = [_type_alias(name=name, type_info=type_info)]

    if decoder:
        def decoder_name_for_type(t):
            if isinstance(t, str):
                return lower_first(t) + 'Decoder'

            typing_origin = getattr(t, '__origin__', None)
            if typing_origin is List:
                return f'( Json.Decode.list {decoder_name_for_type(t.__args__[0])} )'

            if typing_origin is Dict:
                assert t.__args__[0] is str
                return f'( Json.Decode.dict {decoder_name_for_type(t.__args__[1])} )'

            if typing_origin is Union and t.__args__[1] is type(None):
                return f'( Json.Decode.maybe {decoder_name_for_type(t.__args__[0])} )'

            if '_ForwardRef' in str(t):
                return decoder_name_for_type(t.__forward_arg__)

            return {
                int: 'Json.Decode.int',
                float: 'Json.Decode.float',
                str: 'Json.Decode.string',
                bool: 'Json.Decode.bool',
            }[t]

        decoder_fields = '\n'.join([f'|> Json.Decode.Pipeline.required "{key}" {decoder_name_for_type(value)}' for key, value in type_info.items()])

        decoder_name = f'{lower_first(name)}Decoder'
        r.append(f"""{decoder_name} : Json.Decode.Decoder {name}
{decoder_name} =
    Json.Decode.Pipeline.decode {name}
{indent(decoder_fields, levels=2)}""")

    if encoder:
        def encoder_name_for_type(t):
            return decoder_name_for_type(t).replace("Decode", "Encode")

        encoder_fields = [f'( "{key}", {encoder_name_for_type(value)} record.{key} )' for key, value in type_info.items()]
        encoder_name = f'{lower_first(name)}Encoder'
        r.append(f"""{encoder_name} : {name} -> Json.Encode.Value
{encoder_name} record =
    Json.Encode.object
{indent(_list(encoder_fields), levels=2)}""")

    return '\n\n\n'.join(r)

@elm_whitespace
def type_alias_with_json(name, type_info, decoder=True, encoder=True):
    cog.out(_type_alias_with_json(name=name, type_info=type_info, decoder=decoder, encoder=encoder))

def _record(definition: Dict[str, Any]):
    return _list([f'{key} = {elm_literal(value)}' for key, value in definition.items()], start_char='{', end_char='}')

@elm_whitespace
def record(name, definition: Dict[str, Any]):
    cog.out(f'{name} =\n' + indent(_record(definition=definition)))

def _enhanced_enum(name, rows, type_info):
    enum_definition = list(rows.keys())
    r = _enum(name, enum_definition)

    r += '\n\n\n'

    r += _type_alias(name=name + '_row', type_info={lower_first(k): v for k, v in type_info.items()})

    r += '\n\n\n'

    def to_str(value):
        return " ".join([elm_literal(x) for x in value])

    items = '\n'.join([f'{key} ->\n' + indent(f'{name}_row {to_str(value.values())}\n') for key, value in rows.items()])
    items = items[:-1]  # remove last newline
    r += f"""\
{lower_first(name)}_data input =
    case input of
{indent(items, levels=2)}"""
    return r

@elm_whitespace
def enhanced_enum(name, rows: Dict[str, dict], type_info=None):
    if type_info is None:
        type_info = {key: elm_type_by_python_type(type(value)) for key, value in list(rows.values())[0].items()}
    cog.out(_enhanced_enum(name=name, type_info=type_info, rows=rows))
<commit_msg>Assume that the type is a class and use the name if nothing else fits. Do not allow strings as a type.<commit_after>from typing import *

import cog

String = str
Int = int
Float = float
Bool = bool
Maybe = Optional

def lower_first(s):
    return s[0].lower() + s[1:]

class ElmLiteral:
    def __init__(self, s):
        self.s = s

    def __str__(self):
        return self.s

def elm_literal(s):
    if isinstance(s, ElmLiteral):
        return str(s)

    if isinstance(s, str):
        return f'"{s}"'

    return f'{s}'

def elm_type_by_python_type(t):
    if isinstance(t, ElmLiteral):
        return str(t)

    assert not isinstance(t, str), 'A string is not a type'

    typing_origin = getattr(t, '__origin__', None)
    if typing_origin is List:
        return f'( List {elm_type_by_python_type(t.__args__[0])} )'

    if typing_origin is Dict:
        return f'( Dict {elm_type_by_python_type(t.__args__[0])} {elm_type_by_python_type(t.__args__[1])} )'

    if typing_origin is Union and t.__args__[1] is type(None):
        return f'( Maybe {elm_type_by_python_type(t.__args__[0])} )'

    if '_ForwardRef' in str(t):
        return t.__forward_arg__

    return {
        int: 'Int',
        float: 'Float',
        str: 'String',
        bool: 'Bool',
    }.get(t, t.__name__)

def parse_list(items: Union[tuple, list, str]):
    if isinstance(items, (tuple, list)):
        return items
    return [x.strip() for x in items.split(',')]

def _indent(s):
    lines = s.split('\n')
    return '\n'.join(['    ' + x if x else '' for x in lines])

def indent(s, levels=1):
    result = s
    for i in range(levels):
        result = _indent(result)
    return result

def elm_whitespace(f):
    def wrapper(*args, **kwargs):
        cog.out('\n\n')
        f(*args, **kwargs)
        cog.out('\n\n\n\n')
    return wrapper

def _list_single_line(items, *, start_char='[', end_char=']', item_separator_char=','):
    if not isinstance(items, list):
        items = parse_list(items)

    if not items:
        return f'{start_char}{end_char}'

    r = f'{start_char} {items[0]}'

    for item in items[1:]:
        r += f'{item_separator_char} {item}'

    if end_char:
        r += f' {end_char}'

    return r

def _list(items, *, start_char='[', end_char=']', item_separator_char=','):
    if not isinstance(items, list):
        items = parse_list(items)

    if not items:
        return f'{start_char}{end_char}\n'

    r = f'{start_char} {items[0]}'

    for item in items[1:]:
        r += f'\n{item_separator_char} {item}'

    if end_char:
        r += f'\n{end_char}'

    return r

@elm_whitespace
def list_of(name, items, *, start_char='[', end_char=']', item_separator_char=',', single_line=False):
    cog.outl(f'{name} =')
    f = _list_single_line if single_line else _list
    cog.out(indent(f(
        items=items,
        start_char=start_char,
        end_char=end_char,
        item_separator_char=item_separator_char,
    )))

def _union(name, definition):
    return f'type {name}\n' + indent(_list(
        items=definition,
        start_char='=',
        end_char='',
        item_separator_char='|',
    ))

@elm_whitespace
def union(name, definition):
    cog.out(_union(name=name, definition=definition))

def _enum(name, definition):
    return f"""{_union(name, definition)}

{lower_first(name)}_list =
    {_list_single_line(definition)}"""

@elm_whitespace
def enum(name, definition):
    cog.out(_enum(name=name, definition=definition))

def _type_alias(name, type_info):
    return f'type alias {name} =\n' + indent(_list(
        items=[f'{item} : {elm_type_by_python_type(type_info[item])}' for item in type_info.keys()],
        start_char='{',
        end_char='}',
    ))

@elm_whitespace
def type_alias(name, type_info):
    cog.out(_type_alias(name=name, type_info=type_info))

def _type_alias_with_json(name, type_info, decoder, encoder):
    r = [_type_alias(name=name, type_info=type_info)]

    if decoder:
        def decoder_name_for_type(t):
            assert not isinstance(t, str), 'A string is not a type'

            typing_origin = getattr(t, '__origin__', None)
            if typing_origin is List:
                return f'( Json.Decode.list {decoder_name_for_type(t.__args__[0])} )'

            if typing_origin is Dict:
                assert t.__args__[0] is str
                return f'( Json.Decode.dict {decoder_name_for_type(t.__args__[1])} )'

            if typing_origin is Union and t.__args__[1] is type(None):
                return f'( Json.Decode.maybe {decoder_name_for_type(t.__args__[0])} )'

            if '_ForwardRef' in str(t):
                return decoder_name_for_type(t.__forward_arg__)

            return {
                int: 'Json.Decode.int',
                float: 'Json.Decode.float',
                str: 'Json.Decode.string',
                bool: 'Json.Decode.bool',
            }.get(t, lower_first(t.__name__) + 'Decoder')

        decoder_fields = '\n'.join([f'|> Json.Decode.Pipeline.required "{key}" {decoder_name_for_type(value)}' for key, value in type_info.items()])

        decoder_name = f'{lower_first(name)}Decoder'
        r.append(f"""{decoder_name} : Json.Decode.Decoder {name}
{decoder_name} =
    Json.Decode.Pipeline.decode {name}
{indent(decoder_fields, levels=2)}""")

    if encoder:
        def encoder_name_for_type(t):
            return decoder_name_for_type(t).replace("Decode", "Encode")

        encoder_fields = [f'( "{key}", {encoder_name_for_type(value)} record.{key} )' for key, value in type_info.items()]
        encoder_name = f'{lower_first(name)}Encoder'
        r.append(f"""{encoder_name} : {name} -> Json.Encode.Value
{encoder_name} record =
    Json.Encode.object
{indent(_list(encoder_fields), levels=2)}""")

    return '\n\n\n'.join(r)

@elm_whitespace
def type_alias_with_json(name, type_info, decoder=True, encoder=True):
    cog.out(_type_alias_with_json(name=name, type_info=type_info, decoder=decoder, encoder=encoder))

def _record(definition: Dict[str, Any]):
    return _list([f'{key} = {elm_literal(value)}' for key, value in definition.items()], start_char='{', end_char='}')

@elm_whitespace
def record(name, definition: Dict[str, Any]):
    cog.out(f'{name} =\n' + indent(_record(definition=definition)))

def _enhanced_enum(name, rows, type_info):
    enum_definition = list(rows.keys())
    r = _enum(name, enum_definition)

    r += '\n\n\n'

    r += _type_alias(name=name + '_row', type_info={lower_first(k): v for k, v in type_info.items()})

    r += '\n\n\n'

    def to_str(value):
        return " ".join([elm_literal(x) for x in value])

    items = '\n'.join([f'{key} ->\n' + indent(f'{name}_row {to_str(value.values())}\n') for key, value in rows.items()])
    items = items[:-1]  # remove last newline
    r += f"""\
{lower_first(name)}_data input =
    case input of
{indent(items, levels=2)}"""
    return r

@elm_whitespace
def enhanced_enum(name, rows: Dict[str, dict], type_info=None):
    if type_info is None:
        type_info = {key: elm_type_by_python_type(type(value)) for key, value in list(rows.values())[0].items()}
    cog.out(_enhanced_enum(name=name, type_info=type_info, rows=rows))
<|endoftext|>