<commit_before># -*- coding: utf-8 -*-
#
# Robot Framework documentation build configuration file, created by
# sphinx-quickstart on Sun Oct 23 11:12:31 2011.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

import sys, os

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath(os.path.join('.', '..', '..', 'src')))

from robot.version import VERSION, get_version

# -- General configuration -----------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
autoclass_content = "both"
autodoc_member_order = "bysource"
autodoc_default_flags = ["inherited-members"]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix of source filenames.
source_suffix = '.rst'

# The encoding of source files.
#source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'Robot Framework'
copyright = u'2013, Nokia Siemens Networks'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = VERSION
# The full version, including alpha/beta/rc tags.
release = get_version()

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']

# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []

# -- Options for HTML output ---------------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
html_theme = 'default'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}

# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
#html_title = None

# A shorter title for the navigation bar.  Default is the same as html_title.
#html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}

# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}

# If false, no module index is generated.
#html_domain_indices = True

# If false, no index is generated.
#html_use_index = True

# If true, the index is split into individual pages for each letter.
#html_split_index = False

# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None

# Output file base name for HTML help builder.
htmlhelp_basename = 'RobotFrameworkdoc'

# -- Options for LaTeX output --------------------------------------------------

latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',

# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',

# Additional stuff for the LaTeX preamble.
#'preamble': '',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
  ('index', 'RobotFramework.tex', u'Robot Framework Documentation',
   u'Robot Framework developers', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False

# If true, show page references after internal links.
#latex_show_pagerefs = False

# If true, show URL addresses after external links.
#latex_show_urls = False

# Documents to append as an appendix to all manuals.
#latex_appendices = []

# If false, no module index is generated.
#latex_domain_indices = True

# -- Options for manual page output --------------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    ('index', 'robotframework', u'Robot Framework Documentation',
     [u'Robot Framework developers'], 1)
]

# If true, show URL addresses after external links.
#man_show_urls = False

# -- Options for Texinfo output ------------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
  ('index', 'RobotFramework', u'Robot Framework Documentation', u'Robot Framework developers',
   'RobotFramework', 'One line description of project.', 'Miscellaneous'),
]

# Documents to append as an appendix to all manuals.
#texinfo_appendices = []

# If false, no module index is generated.
#texinfo_domain_indices = True

# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'

def non_example_lines(line):
    if not line.startswith(('| ', 'Examples', 'Example', '=>')):
        return True

def remove_library_examples(app, what, name, obj, options, lines):
    if name.startswith("robot.libraries"):
        lines[:] = filter(non_example_lines, lines)

def setup(app):
    app.connect('autodoc-process-docstring', remove_library_examples)
<commit_msg>Automated merge with https://robotframework.googlecode.com/hg/<commit_after># -*- coding: utf-8 -*-
#
# Robot Framework documentation build configuration file, created by
# sphinx-quickstart on Sun Oct 23 11:12:31 2011.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

import sys, os

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath(os.path.join('.', '..', '..', 'src')))

from robot.version import VERSION, get_version

# -- General configuration -----------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
autoclass_content = 'both'
autodoc_default_flags = ['members', 'undoc-members', 'inherited-members']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix of source filenames.
source_suffix = '.rst'

# The encoding of source files.
#source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'Robot Framework'
copyright = u'2013, Nokia Siemens Networks'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = VERSION
# The full version, including alpha/beta/rc tags.
release = get_version()

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']

# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []

# -- Options for HTML output ---------------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
html_theme = 'default'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}

# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
#html_title = None

# A shorter title for the navigation bar.  Default is the same as html_title.
#html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}

# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}

# If false, no module index is generated.
#html_domain_indices = True

# If false, no index is generated.
#html_use_index = True

# If true, the index is split into individual pages for each letter.
#html_split_index = False

# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None

# Output file base name for HTML help builder.
htmlhelp_basename = 'RobotFrameworkdoc'

# -- Options for LaTeX output --------------------------------------------------

latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',

# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',

# Additional stuff for the LaTeX preamble.
#'preamble': '',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
  ('index', 'RobotFramework.tex', u'Robot Framework Documentation',
   u'Robot Framework developers', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False

# If true, show page references after internal links.
#latex_show_pagerefs = False

# If true, show URL addresses after external links.
#latex_show_urls = False

# Documents to append as an appendix to all manuals.
#latex_appendices = []

# If false, no module index is generated.
#latex_domain_indices = True

# -- Options for manual page output --------------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    ('index', 'robotframework', u'Robot Framework Documentation',
     [u'Robot Framework developers'], 1)
]

# If true, show URL addresses after external links.
#man_show_urls = False

# -- Options for Texinfo output ------------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
  ('index', 'RobotFramework', u'Robot Framework Documentation', u'Robot Framework developers',
   'RobotFramework', 'One line description of project.', 'Miscellaneous'),
]

# Documents to append as an appendix to all manuals.
#texinfo_appendices = []

# If false, no module index is generated.
#texinfo_domain_indices = True

# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'

def non_example_lines(line):
    if not line.startswith(('| ', 'Examples', 'Example', '=>')):
        return True

def remove_library_examples(app, what, name, obj, options, lines):
    if name.startswith("robot.libraries"):
        lines[:] = filter(non_example_lines, lines)

def setup(app):
    app.connect('autodoc-process-docstring', remove_library_examples)
<|endoftext|>


<commit_before>"""
Receipt objects for the messages app
"""

from django.contrib.auth.models import User
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string

from datetime import datetime

from muckrock.foia.models import FOIARequest

class GenericReceipt(EmailMultiAlternatives):
    """A basic receipt"""
    subject = u'Your Receipt'
    item = u''
    text_template = 'message/receipt/receipt.txt'

    def __init__(self, user, charge, **kwargs):
        super(GenericReceipt, self).__init__(**kwargs)
        if isinstance(user, User):
            self.user = user
            self.to = [user.email]
        else:
            self.user = None
            try:
                user_email = charge['metadata']['email']
                self.to = [user_email]
            except KeyError:
                self.to = []
        self.from_email = 'MuckRock <info@muckrock.com>'
        self.bcc = ['diagnostics@muckrock.com']
        self.body = render_to_string(
            self.get_text_template(),
            self.get_context_data(charge)
        )

    def get_text_template(self):
        """Returns a plain text email template reference"""
        return self.text_template

    def get_context_data(self, charge):
        """Returns a dictionary of context for the template, given the charge object"""
        amount = charge['amount'] / 100.0 # Stripe uses smallest-unit formatting
        card = charge['source']
        return {
            'user': self.user,
            'id': charge['id'],
            'date': datetime.fromtimestamp(charge['created']),
            'item': self.item,
            'last4': card['last4'],
            'amount': amount
        }

class RequestPurchaseReceipt(GenericReceipt):
    """A receipt for request purchases"""
    subject = u'Payment received for additional requests'
    item = u'4 requests'
    text_template = 'message/receipt/request_purchase.txt'

class RequestFeeReceipt(GenericReceipt):
    """A receipt for payment of request fees"""
    subject = u'Payment received for request fee'
    item = u'Request fee'
    text_template = 'message/receipt/request_fees.txt'

    def get_context_data(self, charge):
        """Returns the context for the template"""
        context = super(RequestFeeReceipt, self).get_context_data(charge)
        amount = context['amount']
        base_amount = amount / 1.05
        fee_amount = amount - base_amount
        context['base_amount'] = base_amount
        context['fee_amount'] = fee_amount
        try:
            foia_pk = charge['metadata']['foia']
            foia = FOIARequest.objects.get(pk=foia_pk)
            context['url'] = foia.get_absolute_url()
        except KeyError:
            logger.error('No FOIA identified in Charge metadata.')
        except FOIARequest.DoesNotExist:
            logger.error('Could not find FOIARequest identified by Charge metadata.')
        return context

class MultiRequestReceipt(GenericReceipt):
    """A receipt for the purchase of a multirequest"""
    subject = u'Payment received for multi request fee'
    item = u'Multi-request fee'
    text_template = 'message/receipt/multirequest.txt'

class CrowdfundPaymentReceipt(GenericReceipt):
    """A receipt for the payment to a crowdfund"""
    subject = u'Payment received for crowdfunding a request'
    item = u'Crowdfund payment'
    text_template = 'message/receipt/crowdfund.txt'

class ProSubscriptionReceipt(GenericReceipt):
    """A receipt for a recurring pro subscription charge"""
    subject = u'Payment received for professional account'
    item = u'Professional subscription'
    text_template = 'message/receipt/pro.txt'

class OrgSubscriptionReceipt(GenericReceipt):
    """A receipt for a recurring org subscription charge"""
    subject = u'Payment received dor organization account'
    item = u'Organization subscription'
    text_template = 'message/receipt/org.txt'
<commit_msg>generic receipt uses the base template and doesnt use a getter for the text_template variable<commit_after>"""
Receipt objects for the messages app
"""

from django.contrib.auth.models import User
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string

from datetime import datetime

from muckrock.foia.models import FOIARequest

class GenericReceipt(EmailMultiAlternatives):
    """A basic receipt"""
    subject = u'Your Receipt'
    item = u''
    text_template = 'message/receipt/base.txt'

    def __init__(self, user, charge, **kwargs):
        super(GenericReceipt, self).__init__(**kwargs)
        if isinstance(user, User):
            self.user = user
            self.to = [user.email]
        else:
            self.user = None
            try:
                user_email = charge['metadata']['email']
                self.to = [user_email]
            except KeyError:
                self.to = []
        self.from_email = 'MuckRock <info@muckrock.com>'
        self.bcc = ['diagnostics@muckrock.com']
        self.body = render_to_string(
            self.text_template,
            self.get_context_data(charge)
        )

    def get_context_data(self, charge):
        """Returns a dictionary of context for the template, given the charge object"""
        amount = charge['amount'] / 100.0 # Stripe uses smallest-unit formatting
        card = charge['source']
        return {
            'user': self.user,
            'id': charge['id'],
            'date': datetime.fromtimestamp(charge['created']),
            'item': self.item,
            'last4': card['last4'],
            'amount': amount
        }

class RequestPurchaseReceipt(GenericReceipt):
    """A receipt for request purchases"""
    subject = u'Payment received for additional requests'
    item = u'4 requests'
    text_template = 'message/receipt/request_purchase.txt'

class RequestFeeReceipt(GenericReceipt):
    """A receipt for payment of request fees"""
    subject = u'Payment received for request fee'
    item = u'Request fee'
    text_template = 'message/receipt/request_fees.txt'

    def get_context_data(self, charge):
        """Returns the context for the template"""
        context = super(RequestFeeReceipt, self).get_context_data(charge)
        amount = context['amount']
        base_amount = amount / 1.05
        fee_amount = amount - base_amount
        context['base_amount'] = base_amount
        context['fee_amount'] = fee_amount
        try:
            foia_pk = charge['metadata']['foia']
            foia = FOIARequest.objects.get(pk=foia_pk)
            context['url'] = foia.get_absolute_url()
        except KeyError:
            logger.error('No FOIA identified in Charge metadata.')
        except FOIARequest.DoesNotExist:
            logger.error('Could not find FOIARequest identified by Charge metadata.')
        return context

class MultiRequestReceipt(GenericReceipt):
    """A receipt for the purchase of a multirequest"""
    subject = u'Payment received for multi request fee'
    item = u'Multi-request fee'
    text_template = 'message/receipt/multirequest.txt'

class CrowdfundPaymentReceipt(GenericReceipt):
    """A receipt for the payment to a crowdfund"""
    subject = u'Payment received for crowdfunding a request'
    item = u'Crowdfund payment'
    text_template = 'message/receipt/crowdfund.txt'

class ProSubscriptionReceipt(GenericReceipt):
    """A receipt for a recurring pro subscription charge"""
    subject = u'Payment received for professional account'
    item = u'Professional subscription'
    text_template = 'message/receipt/pro.txt'

class OrgSubscriptionReceipt(GenericReceipt):
    """A receipt for a recurring org subscription charge"""
    subject = u'Payment received dor organization account'
    item = u'Organization subscription'
    text_template = 'message/receipt/org.txt'
<|endoftext|>


<commit_before>import pygame
import sys
import random
from ctypes import windll, Structure, c_long, byref  # Keep on top

WIDTH, HEIGHT = 480, 360
CENTER = (WIDTH/2, HEIGHT/2)
BLACK = (0,0,0)
WHITE = (255,255,255)

class RECT(Structure):  # 直接从CyberPet搬过来
    _fields_ = [
    ('left',    c_long),
    ('top',     c_long),
    ('right',   c_long),
    ('bottom',  c_long),
    ]
    def width(self):  return self.right  - self.left
    def height(self): return self.bottom - self.top

def main():
    global LARGER_FONT, SMALLER_FONT, CLOCK, FPS, DISPLAY
    pygame.init()
    pygame.font.init()
    pygame.display.set_caption('BREATHE')
    pygame.display.set_icon(pygame.image.load('breathe.png'))

    DISPLAY = pygame.display.set_mode((WIDTH, HEIGHT))
    CLOCK = pygame.time.Clock()
    FPS = 60
    LARGER_FONT = pygame.font.SysFont('Microsoft YaHei', 132)
    SMALLER_FONT = pygame.font.SysFont('Microsoft YaHei', 64)

    POWER_BREATHING_SEQUENCE = [('INHALE', 4), ('EXHALE', 8)]
    FOUR_SEVEN_EIGHT_SEQUENCE = [('INHALE', 4), ('HOLD', 7), ('EXHALE', 8)]
    EQUAL_BREATHING_SEQUENCE = [('INHALE', 5), ('EXHALE', 5)]

    DICT_OF_SEQUENCE = {'Power Breathing': POWER_BREATHING_SEQUENCE, '4-7-8 Breathing': FOUR_SEVEN_EIGHT_SEQUENCE,
                        'Equal Breathing': EQUAL_BREATHING_SEQUENCE}
    LIST_OF_SEQUENCE = list(DICT_OF_SEQUENCE.keys())

    number_banner, number_rect = banner(0)
    label, label_rect = banner('', upper=True)

    print('Please choose a sequence, Enter for random:')
    for i, seq in enumerate(LIST_OF_SEQUENCE):
        print(f'  {i}. {seq}')
    try:
        choice = LIST_OF_SEQUENCE[int(input('>'))]
        SEQUENCE = DICT_OF_SEQUENCE[choice]
    except (KeyError, ValueError):
        choice = random.choice(LIST_OF_SEQUENCE)
        SEQUENCE = DICT_OF_SEQUENCE[choice]
    print('Presenting:', choice)

    while True:
        for label_text, length in SEQUENCE:
            label, label_rect = banner(label_text, upper=True)
            for second in range(1, length+1):
                for frame in range(FPS):
                    if frame == 0:
                        number_banner, number_rect = banner(second)
                    for event in pygame.event.get():
                        if event.type == pygame.QUIT:
                            pygame.quit()
                            sys.exit()
                    DISPLAY.fill(WHITE)
                    DISPLAY.blit(label, label_rect)
                    DISPLAY.blit(number_banner, number_rect)
                    onTop(pygame.display.get_wm_info()['window'])
                    pygame.display.flip()
                    CLOCK.tick(FPS)

def banner(text, upper=False):
    if upper:
        text = SMALLER_FONT.render(text, True, BLACK)
        rect = text.get_rect()
        rect.center = (WIDTH/2, HEIGHT/1.25)
    else:
        text = LARGER_FONT.render(str(text), True, BLACK)
        rect = text.get_rect()
        rect.center = CENTER
    return text, rect

def onTop(window):
    SetWindowPos = windll.user32.SetWindowPos
    GetWindowRect = windll.user32.GetWindowRect
    rc = RECT()
    GetWindowRect(window, byref(rc))
    SetWindowPos(window, -1, rc.left, rc.top, 0, 0, 0x0001)

if __name__ == '__main__':
    main()
<commit_msg>New breathing technique<commit_after># -*- coding: UTF-8 -*-
import pygame
import sys
import random
from ctypes import windll, Structure, c_long, byref  # Keep on top

WIDTH, HEIGHT = 480, 360
CENTER = (WIDTH/2, HEIGHT/2)
BLACK = (0,0,0)
WHITE = (255,255,255)

class RECT(Structure):  # 直接从CyberPet搬过来
    _fields_ = [
    ('left',    c_long),
    ('top',     c_long),
    ('right',   c_long),
    ('bottom',  c_long),
    ]
    def width(self):  return self.right  - self.left
    def height(self): return self.bottom - self.top

def main():
    global LARGER_FONT, SMALLER_FONT, CLOCK, FPS, DISPLAY

    POWER_BREATHING_SEQUENCE = [('INHALE', 4), ('EXHALE', 8)]
    FOUR_SEVEN_EIGHT_SEQUENCE= [('INHALE', 4), ('HOLD', 7), ('EXHALE', 8)]
    EQUAL_BREATHING_SEQUENCE = [('INHALE', 5), ('EXHALE', 5)]
    SQUARE_BREATHING_SEQUENCE= [('INHALE', 4), ('HOLD', 4), ('EXHALE', 4), ('HOLD', 4)]

    DICT_OF_SEQUENCE = {'Power Breathing': POWER_BREATHING_SEQUENCE, '4-7-8 Breathing': FOUR_SEVEN_EIGHT_SEQUENCE,
                        'Equal Breathing': EQUAL_BREATHING_SEQUENCE, 'Square Breathing': SQUARE_BREATHING_SEQUENCE,
                        }
    LIST_OF_SEQUENCE = list(DICT_OF_SEQUENCE.keys())

    print('Please choose a sequence, Enter for random:')
    for i, seq in enumerate(LIST_OF_SEQUENCE):
        print(f'  {i}. {seq}')
    try:
        choice = LIST_OF_SEQUENCE[int(input('>'))]
        SEQUENCE = DICT_OF_SEQUENCE[choice]
    except (KeyError, ValueError):
        choice = random.choice(LIST_OF_SEQUENCE)
        SEQUENCE = DICT_OF_SEQUENCE[choice]
    print('Presenting:', choice)

    pygame.init()
    pygame.font.init()
    pygame.display.set_caption('BREATHE')
    try:
        pygame.display.set_icon(pygame.image.load('./breathe.png'))
    except pygame.error:
        pass

    DISPLAY = pygame.display.set_mode((WIDTH, HEIGHT))
    CLOCK = pygame.time.Clock()
    FPS = 60
    LARGER_FONT = pygame.font.SysFont('Microsoft YaHei', 132)
    SMALLER_FONT = pygame.font.SysFont('Microsoft YaHei', 64)
    number_banner, number_rect = banner(0)
    label, label_rect = banner('', upper=True)

    while True:
        for label_text, length in SEQUENCE:
            label, label_rect = banner(label_text, upper=True)
            for second in range(1, length+1):
                for frame in range(FPS):
                    if frame == 0:
                        number_banner, number_rect = banner(second)
                    for event in pygame.event.get():
                        if event.type == pygame.QUIT:
                            pygame.quit()
                            sys.exit()
                    DISPLAY.fill(WHITE)
                    DISPLAY.blit(label, label_rect)
                    DISPLAY.blit(number_banner, number_rect)
                    onTop(pygame.display.get_wm_info()['window'])
                    pygame.display.flip()
                    CLOCK.tick(FPS)

def banner(text, upper=False):
    if upper:
        text = SMALLER_FONT.render(text, True, BLACK)
        rect = text.get_rect()
        rect.center = (WIDTH/2, HEIGHT/1.25)
    else:
        text = LARGER_FONT.render(str(text), True, BLACK)
        rect = text.get_rect()
        rect.center = CENTER
    return text, rect

def onTop(window):
    SetWindowPos = windll.user32.SetWindowPos
    GetWindowRect = windll.user32.GetWindowRect
    rc = RECT()
    GetWindowRect(window, byref(rc))
    SetWindowPos(window, -1, rc.left, rc.top, 0, 0, 0x0001)

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


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Brill Tagger classes."""

import codecs
import os
import random

from nltk.tag import brill
from nltk.tag.brill_trainer import BrillTaggerTrainer
from nltk.tag.sequential import RegexpTagger, UnigramTagger, BigramTagger, \
                                TrigramTagger

from . import ten
from .config import DATA_DIR_NAME
from .files import to_unicode_or_bust as tuob
from .files import TTTaggedCorpusReader

class TTBrillTaggerTrainer(object):
    """A trainer for tbl taggers."""

    def __init__(self, file_name, language='', separator='_', ws_delim=True,
                 number_of_groups=10, train_size=0.65, max_rules=300,
                 min_score=3):
        """Construct a Brill tagger from baseline tagger and templates."""
        self.tcr = TTTaggedCorpusReader(file_name=file_name,
                                        language=language,
                                        separator=separator,
                                        ws_delim=ws_delim)
        self.num_groups = number_of_groups
        self.dev_size = len(self.tcr.sents())
        self.train_size = train_size
        self.max_rules = max_rules
        self.min_score = min_score
        self.tagged_data_list = [[(w.lower(), t) for w, t in s]
                                   for s in self.tcr.tagged_sents()]

    def train(self, templates=None, verbose=True):
        """Train a new Brill tagger."""
        if templates is None:
            templates = brill.nltkdemo18()

        random.seed(len(self.tagged_data_list))
        random.shuffle(self.tagged_data_list)
        cutoff = int(self.dev_size * self.train_size)

        training_data = self.tagged_data_list[:cutoff]
        test_data = self.tagged_data_list[cutoff:self.dev_size]

        # very simple regular expression tagger
        regex_tagger = RegexpTagger([
            (r'^-?[0-9]+(.[0-9]+)?$', 'PUNCT'),
            (r'.*', 'N')
            ])
        if verbose == True:
            print "Regular expression tagger accuracy:\n{}\n".format(
                    regex_tagger.evaluate(test_data))

        # unigram tagger
        unigram_tagger = UnigramTagger(train=training_data,
                                       backoff=regex_tagger)
        if verbose == True:
            print "Unigram tagger accuracy:\n{}\n".format(
                    unigram_tagger.evaluate(test_data))

        # bigram tagger
        bigram_tagger = BigramTagger(train=training_data,
                                     backoff=unigram_tagger)
        if verbose == True:
            print "Bigram tagger accuracy:\n{}\n".format(
                    bigram_tagger.evaluate(test_data))

        # trigram tagger
        trigram_tagger = TrigramTagger(train=training_data,
                                       backoff=bigram_tagger)
        if verbose == True:
            print "Trigram tagger accuracy:\n{}\n".format(
                    trigram_tagger.evaluate(test_data))

        # first iteration
        trainer = BrillTaggerTrainer(initial_tagger=trigram_tagger,
                                     templates=templates)
        brill_tagger = trainer.train(train_sents=training_data,
                                     max_rules=self.max_rules,
                                     min_score=self.min_score)
        if verbose == True:
            print "Initial Brill tagger accuracy:\n{}\n".format(
                    brill_tagger.evaluate(test_data))

        # folding
        for i in range(0, self.num_groups):
            # random splitting
            random.seed(len(self.tagged_data_list))
            random.shuffle(self.tagged_data_list)
            cutoff = int(self.dev_size * self.train_size)

            training_data = self.tagged_data_list[:cutoff]
            test_data = self.tagged_data_list[cutoff:self.dev_size]

            brill_tagger = trainer.train(train_sents=training_data,
                                         max_rules=self.max_rules,
                                         min_score=self.min_score)
            if verbose == True:
                print "Brill tagger accuracy, fold {}:\n{}\n".format(
                        i+1, brill_tagger.evaluate(test_data))

    def compare_templates(self):
        for i, t in enumerate([brill.nltkdemo18(), brill.nltkdemo18plus(),
                               brill.brill24(), brill.fntbl37()]):
            print "\nTEMPLATE {}==================\n".format(i)
            self.train(templates=t)

class TTBrillTagger(brill.BrillTagger):
    pass

<commit_msg>add TaggerTesterBrill class for Brill tagger cross-validation<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Brill Tagger classes."""

import codecs
import os
import random

from nltk.tag import brill
from nltk.tag.brill_trainer import BrillTaggerTrainer
from nltk.tag.sequential import RegexpTagger, UnigramTagger, BigramTagger, \
                                TrigramTagger

from . import ten
from .config import DATA_DIR_NAME
from .files import to_unicode_or_bust as tuob
from .files import TTTaggedCorpusReader

class TTBrillTaggerTrainer(object):
    """A trainer for tbl taggers."""

    def __init__(self, file_name, language='', separator='_', ws_delim=True,
                 number_of_groups=10, train_size=0.65, max_rules=300,
                 min_score=3):
        """Construct a Brill tagger from baseline tagger and templates."""
        self.tcr = TTTaggedCorpusReader(file_name=file_name,
                                        language=language,
                                        separator=separator,
                                        ws_delim=ws_delim)
        self.num_groups = number_of_groups
        self.dev_size = len(self.tcr.sents())
        self.train_size = train_size
        self.max_rules = max_rules
        self.min_score = min_score
        self.tagged_data_list = [[(w.lower(), t) for w, t in s]
                                   for s in self.tcr.tagged_sents()]

    def train(self, templates=None, verbose=True):
        """Train a new Brill tagger."""
        if templates is None:
            templates = brill.nltkdemo18()

        random.seed(len(self.tagged_data_list))
        random.shuffle(self.tagged_data_list)
        cutoff = int(self.dev_size * self.train_size)

        training_data = self.tagged_data_list[:cutoff]
        test_data = self.tagged_data_list[cutoff:self.dev_size]

        # very simple regular expression tagger
        regex_tagger = RegexpTagger([
            (r'^-?[0-9]+(.[0-9]+)?$', 'PUNCT'),
            (r'.*', 'N')
            ])
        if verbose == True:
            print "Regular expression tagger accuracy:\n{}\n".format(
                    regex_tagger.evaluate(test_data))

        # unigram tagger
        unigram_tagger = UnigramTagger(train=training_data,
                                       backoff=regex_tagger)
        if verbose == True:
            print "Unigram tagger accuracy:\n{}\n".format(
                    unigram_tagger.evaluate(test_data))

        # bigram tagger
        bigram_tagger = BigramTagger(train=training_data,
                                     backoff=unigram_tagger)
        if verbose == True:
            print "Bigram tagger accuracy:\n{}\n".format(
                    bigram_tagger.evaluate(test_data))

        # trigram tagger
        trigram_tagger = TrigramTagger(train=training_data,
                                       backoff=bigram_tagger)
        if verbose == True:
            print "Trigram tagger accuracy:\n{}\n".format(
                    trigram_tagger.evaluate(test_data))

        # first iteration
        trainer = BrillTaggerTrainer(initial_tagger=trigram_tagger,
                                     templates=templates)
        brill_tagger = trainer.train(train_sents=training_data,
                                     max_rules=self.max_rules,
                                     min_score=self.min_score)
        if verbose == True:
            print "Initial Brill tagger accuracy:\n{}\n".format(
                    brill_tagger.evaluate(test_data))

        # folding
        for i in range(0, self.num_groups):
            # random splitting
            random.seed(len(self.tagged_data_list))
            random.shuffle(self.tagged_data_list)
            cutoff = int(self.dev_size * self.train_size)

            training_data = self.tagged_data_list[:cutoff]
            test_data = self.tagged_data_list[cutoff:self.dev_size]

            brill_tagger = trainer.train(train_sents=training_data,
                                         max_rules=self.max_rules,
                                         min_score=self.min_score)
            if verbose == True:
                print "Brill tagger accuracy, fold {}:\n{}\n".format(
                        i+1, brill_tagger.evaluate(test_data))

    def compare_templates(self):
        for i, t in enumerate([brill.nltkdemo18(), brill.nltkdemo18plus(),
                               brill.brill24(), brill.fntbl37()]):
            print "\nTEMPLATE {}==================\n".format(i)
            self.train(templates=t)

class TaggerTesterBrill(object):
    """Collection of files for training/testing Brill taggers."""

    def __init__(self, file_name, language='', subfile_pfx='brill_chunk_',
                 separator='_', ws_delim=True, starting_idx=1,
                 number_of_groups=10, encoding='utf-8'):
        """Initialize the test suite.

           Parameters
           ----------
             file_name (str) : name of the input file, with extension
             language (str) : the language of the file (e.g., 'Uyghur')
             subfile_pfx (str) : name (minus index) of generated files
             separator (str) : the character used in the file to separate
               words from their part-of-speech tags, e.g.:
                   'table/NN' -- separator is '/'
                   'table_NN' -- separator is '_'
             ws_delim (boolean) : is the file already whitespace-delimited?
               if the answer is 'yes', then True, e.g.:
                   Tursun_Npr ._PUNCT
               if the answer is 'no', then False, e.g.:
                   Tursun_Npr._Punct
             starting_idx (int) : number at which group numbering will start
             number_of_groups (int) : number of groups into which the file
               will be split for cross-validation
             encoding (str) : encoding of the input file
        """
        pass
<|endoftext|>


<commit_before>import time
import math
import Adafruit_PCA9685

pwm = Adafruit_PCA9685.PCA9685()
pwm.set_pwm_freq(60)

class Servo:
    """
    Controls the position of a Servo using velocity and acceleration to
    move the sevro to different target positions
    """

    global covD2S, covS2D, calculateDistance

    def covD2S(deg):
        sig = int((29 * deg) / 12 + 150)
        if(sig > 585):
            return 585
        elif(sig < 0):
            return 0
        else:
            return int(sig)

    def covS2D(sig):
        deg = int((12 * sig) / 29 - 62)
        if(deg > 180):
            return 180
        elif(deg < 0):
            return 0
        else:
            return deg

    def calculateDistance(iV, a, t):
        return (iV * t) + 0.5 * a * t ** 2

    def __init__(self, port, max, min):
        self.port = port
        self.max = max
        self.min = min

        self.target = min
        self.position = min
        self.velocity = 0

        self.maxABSVelocity = 200.0 # Must be a decimal and > 0
        self.maxABSacceleration = 500.0 # Must be a decimal and > 0

        self.startPosition = 0
        self.startTime = 0
        self.initialVelocity = 0
        self.direction = 1

        self.rampUpAcceleration = 0
        self.rampDownAcceleration = 0
        self.cruiseVelocity = 0

        self.rampUpTime = 0
        self.cruiseTime = 0
        self.rampDownTime = 0

        self.rampUpDistance = 0
        self.cruiseDistance = 0
        self.rampDownDistance = 0

        self.startRampUp = 0
        self.startCruise = 0
        self.startRampDown = 0
        self.finished = 0

    def updateTarget(self, newTarget):
        if newTarget == self.position:
            return

        self.startPosition = self.position
        self.initialVelocity = self.velocity
        self.target = newTarget
        distance = self.target - self.startPosition

        if distance > 0: # positive direction
            self.rampUpAcceleration = self.maxABSacceleration
            self.rampDownAcceleration = -self.maxABSacceleration
            self.cruiseVelocity = self.maxABSVelocity
        else: # negative direction
            self.rampUpAcceleration = -self.maxABSacceleration
            self.rampDownAcceleration = self.maxABSacceleration
            self.cruiseVelocity = -self.maxABSVelocity

        self.rampUpTime = math.fabs((self.cruiseVelocity - self.initialVelocity) / self.rampUpAcceleration)
        self.rampUpDistance = calculateDistance(self.initialVelocity, self.rampUpAcceleration, self.rampUpTime)

        self.rampDownTime = math.fabs(self.cruiseVelocity / self.rampDownAcceleration)
        self.rampDownDistance = calculateDistance(self.cruiseVelocity, self.rampDownAcceleration, self.rampDownTime)

        # overshoot
        if math.fabs(self.rampUpDistance + self.rampUpDistance) > math.fabs(distance):

            self.rampUpDistance = distance / 2
            self.rampUpTime = math.sqrt(math.fabs(distance / self.maxABSacceleration))

            self.rampDownDistance = self.rampUpDistance
            self.rampDownTime = self.rampUpTime

            self.cruiseDistance = 0
            self.cruiseTime = 0
            self.cruiseVelocity = self.rampUpTime * self.maxABSacceleration

            if distance < 0:
                self.cruiseVelocity = -self.cruiseVelocity

            if self.initialVelocity + self.cruiseVelocity > self.cruiseVelocity: # initial velocity approaching cruise velocity
                # timeDiff = math.fabs(self.initialVelocity / self.maxABSacceleration)
                # distanceDiff = calculateDistance(self.initialVelocity, self.maxABSacceleration, timeDiff)
                # self.rampUpTime -= timeDiff
                # self.rampUpDistance -= distanceDiff
                #
                # self.cruiseTime = timeDiff
                # self.cruiseDistance = distanceDiff
                #
                self.position = self.target
                return

            if self.initialVelocity + self.cruiseVelocity < self.cruiseVelocity: # initial velocity dissenting cruise velocity
                self.position = self.target
                return

        else:
            self.cruiseDistance = distance - self.rampUpDistance - self.rampDownDistance
            self.cruiseTime = math.fabs(self.cruiseDistance / self.cruiseVelocity)

        self.startRampUp = 0
        self.startCruise = self.rampUpTime
        self.startRampDown = self.startCruise + self.cruiseTime
        self.finished = self.startRampDown + self.rampDownTime
        self.startTime = time.time()

    def updatePosition(self, ctime):
        if self.position == self.target:
            return self.position

        currentTime = time.time() - self.startTime

        if self.startRampUp <= currentTime and currentTime < self.startCruise:
            self.position = self.startPosition + calculateDistance(self.initialVelocity, self.rampUpAcceleration, currentTime)
            self.velocity = self.initialVelocity + self.rampUpAcceleration * currentTime
            stage = 'RAMP UP'
        elif self.startCruise <= currentTime and currentTime < self.startRampDown:
            self.position = self.startPosition + self.rampUpDistance + self.cruiseVelocity * (currentTime - self.startCruise)
            self.velocity = self.cruiseVelocity
            stage = 'CRUISE'
        elif self.startRampDown <= currentTime and currentTime < self.finished:
            self.position = self.startPosition + self.rampUpDistance + self.cruiseDistance + calculateDistance(self.cruiseVelocity, self.rampDownAcceleration, currentTime - self.startRampDown)
            self.velocity = self.cruiseVelocity + self.rampDownAcceleration * (currentTime - self.startRampDown)
            stage = 'RAMP DOWN'
        else:
            self.position = self.target
            self.velocity = 0
            stage = 'DONE'

        print('{0:10} position: {1:8.3f}, velocity: {2:8.3f}, time:{3:8.3f}'.format(stage, self.position, self.velocity, currentTime))
        pwm.set_pwm(self.port, 0, covD2S(self.position))

        return self.position

    def setPosition(self, pos):
        self.position = pos
        #pwm.set_pwm(self.port, 0, covD2S(pos))
<commit_msg>triangle profile w/ aproaching initial velocity<commit_after>import time
import math
import Adafruit_PCA9685

pwm = Adafruit_PCA9685.PCA9685()
pwm.set_pwm_freq(60)

class Servo:
    """
    Controls the position of a Servo using velocity and acceleration to
    move the sevro to different target positions
    """

    global covD2S, covS2D, calculateDistance

    def covD2S(deg):
        sig = int((29 * deg) / 12 + 150)
        if(sig > 585):
            return 585
        elif(sig < 0):
            return 0
        else:
            return int(sig)

    def covS2D(sig):
        deg = int((12 * sig) / 29 - 62)
        if(deg > 180):
            return 180
        elif(deg < 0):
            return 0
        else:
            return deg

    def calculateDistance(iV, a, t):
        return (iV * t) + 0.5 * a * t ** 2

    def __init__(self, port, max, min):
        self.port = port
        self.max = max
        self.min = min

        self.target = min
        self.position = min
        self.velocity = 0

        self.maxABSVelocity = 200.0 # Must be a decimal and > 0
        self.maxABSacceleration = 500.0 # Must be a decimal and > 0

        self.startPosition = 0
        self.startTime = 0
        self.initialVelocity = 0
        self.direction = 1

        self.rampUpAcceleration = 0
        self.rampDownAcceleration = 0
        self.cruiseVelocity = 0

        self.rampUpTime = 0
        self.cruiseTime = 0
        self.rampDownTime = 0

        self.rampUpDistance = 0
        self.cruiseDistance = 0
        self.rampDownDistance = 0

        self.startRampUp = 0
        self.startCruise = 0
        self.startRampDown = 0
        self.finished = 0

    def updateTarget(self, newTarget):
        if newTarget == self.position:
            return

        self.startPosition = self.position
        self.initialVelocity = self.velocity
        self.target = newTarget
        distance = self.target - self.startPosition

        if distance > 0: # positive direction
            self.rampUpAcceleration = self.maxABSacceleration
            self.rampDownAcceleration = -self.maxABSacceleration
            self.cruiseVelocity = self.maxABSVelocity
        else: # negative direction
            self.rampUpAcceleration = -self.maxABSacceleration
            self.rampDownAcceleration = self.maxABSacceleration
            self.cruiseVelocity = -self.maxABSVelocity

        self.rampUpTime = math.fabs((self.cruiseVelocity - self.initialVelocity) / self.rampUpAcceleration)
        self.rampUpDistance = calculateDistance(self.initialVelocity, self.rampUpAcceleration, self.rampUpTime)

        self.rampDownTime = math.fabs(self.cruiseVelocity / self.rampDownAcceleration)
        self.rampDownDistance = calculateDistance(self.cruiseVelocity, self.rampDownAcceleration, self.rampDownTime)

        # overshoot
        if math.fabs(self.rampUpDistance + self.rampUpDistance) > math.fabs(distance):

            self.rampUpDistance = distance / 2
            self.rampUpTime = math.sqrt(math.fabs(distance / self.maxABSacceleration))

            self.rampDownDistance = self.rampUpDistance
            self.rampDownTime = self.rampUpTime

            self.cruiseDistance = 0
            self.cruiseTime = 0
            self.cruiseVelocity = self.rampUpTime * self.rampUpAcceleration

            if math.fabs(self.initialVelocity + self.cruiseVelocity) > math.fabs(self.cruiseVelocity): # initial velocity approaching cruise velocity
                timeDiff = math.fabs(self.initialVelocity / self.rampUpAcceleration)
                distanceDiff = calculateDistance(0, self.rampUpAcceleration, timeDiff)

                self.rampUpTime -= timeDiff
                self.rampUpDistance -= distanceDiff
                self.cruiseTime = distanceDiff / self.cruiseVelocity
                self.cruiseDistance = distanceDiff

            if math.fabs(self.initialVelocity + self.cruiseVelocity) < math.fabs(self.cruiseVelocity): # initial velocity dissenting cruise velocity

                self.position = self.target
                return

        else:
            self.cruiseDistance = distance - self.rampUpDistance - self.rampDownDistance
            self.cruiseTime = math.fabs(self.cruiseDistance / self.cruiseVelocity)

        self.startRampUp = 0
        self.startCruise = self.rampUpTime
        self.startRampDown = self.startCruise + self.cruiseTime
        self.finished = self.startRampDown + self.rampDownTime
        self.startTime = time.time()

    def updatePosition(self, ctime):
        if self.position == self.target:
            return self.position

        currentTime = time.time() - self.startTime

        if self.startRampUp <= currentTime and currentTime < self.startCruise:
            self.position = self.startPosition + calculateDistance(self.initialVelocity, self.rampUpAcceleration, currentTime)
            self.velocity = self.initialVelocity + self.rampUpAcceleration * currentTime
            stage = 'RAMP UP'
        elif self.startCruise <= currentTime and currentTime < self.startRampDown:
            self.position = self.startPosition + self.rampUpDistance + self.cruiseVelocity * (currentTime - self.startCruise)
            self.velocity = self.cruiseVelocity
            stage = 'CRUISE'
        elif self.startRampDown <= currentTime and currentTime < self.finished:
            self.position = self.startPosition + self.rampUpDistance + self.cruiseDistance + calculateDistance(self.cruiseVelocity, self.rampDownAcceleration, currentTime - self.startRampDown)
            self.velocity = self.cruiseVelocity + self.rampDownAcceleration * (currentTime - self.startRampDown)
            stage = 'RAMP DOWN'
        else:
            self.position = self.target
            self.velocity = 0
            stage = 'DONE'

        print('{0:10} position: {1:8.3f}, velocity: {2:8.3f}, time:{3:8.3f}'.format(stage, self.position, self.velocity, currentTime))
        pwm.set_pwm(self.port, 0, covD2S(self.position))

        return self.position

    def setPosition(self, pos):
        self.position = pos
        pwm.set_pwm(self.port, 0, covD2S(pos))
<|endoftext|>


<commit_before># Copyright: Damien Elmes <anki@ichi2.net>
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html

import os, sys, optparse, atexit, tempfile, __builtin__
from aqt.qt import *
import locale, gettext
import anki.lang
from anki.consts import HELP_SITE
from anki.lang import langDir

appVersion="2.0.6"
appWebsite="http://ankisrs.net/"
appChanges="http://ankisrs.net/docs/changes.html"
appDonate="http://ankisrs.net/support/"
appShared="https://ankiweb.net/shared/"
appUpdate="https://ankiweb.net/update/desktop"
appHelpSite=HELP_SITE
mw = None # set on init

moduleDir = os.path.split(os.path.dirname(os.path.abspath(__file__)))[0]

try:
    import aqt.forms
except ImportError, e:
    if "forms" in str(e):
        print "If you're running from git, did you run build_ui.sh?"
        print
    raise

# Dialog manager - manages modeless windows
##########################################################################

class DialogManager(object):

    def __init__(self):
        from aqt import addcards, browser, editcurrent
        self._dialogs = {
            "AddCards": [addcards.AddCards, None],
            "Browser": [browser.Browser, None],
            "EditCurrent": [editcurrent.EditCurrent, None],
        }

    def open(self, name, *args):
        (creator, instance) = self._dialogs[name]
        if instance:
            instance.activateWindow()
            instance.raise_()
            return instance
        else:
            instance = creator(*args)
            self._dialogs[name][1] = instance
            return instance

    def close(self, name):
        self._dialogs[name] = [self._dialogs[name][0], None]

    def closeAll(self):
        for (n, (creator, instance)) in self._dialogs.items():
            if instance:
                instance.forceClose = True
                instance.close()
                self.close(n)

dialogs = DialogManager()

# Language handling
##########################################################################
# Qt requires its translator to be installed before any GUI widgets are
# loaded, and we need the Qt language to match the gettext language or
# translated shortcuts will not work.

_gtrans = None
_qtrans = None

def setupLang(pm, app, force=None):
    global _gtrans, _qtrans
    try:
        locale.setlocale(locale.LC_ALL, '')
    except:
        pass
    lang = force or pm.meta["defaultLang"]
    dir = langDir()
    # gettext
    _gtrans = gettext.translation(
        'anki', dir, languages=[lang], fallback=True)
    __builtin__.__dict__['_'] = _gtrans.ugettext
    __builtin__.__dict__['ngettext'] = _gtrans.ungettext
    anki.lang.setLang(lang, local=False)
    if lang in ("he","ar","fa"):
        app.setLayoutDirection(Qt.RightToLeft)
    else:
        app.setLayoutDirection(Qt.LeftToRight)
    # qt
    _qtrans = QTranslator()
    if _qtrans.load("qt_" + lang, dir):
        app.installTranslator(_qtrans)

# App initialisation
##########################################################################

class AnkiApp(QApplication):

    # Single instance support on Win32/Linux
    ##################################################

    KEY = "anki"
    TMOUT = 5000

    def __init__(self, argv):
        QApplication.__init__(self, argv)
        self._argv = argv
        self._shmem = QSharedMemory(self.KEY)
        self.alreadyRunning = self._shmem.attach()

    def secondInstance(self):
        if not self.alreadyRunning:
            # use a 1 byte shared memory instance to signal we exist
            if not self._shmem.create(1):
                raise Exception("shared memory not supported")
            atexit.register(self._shmem.detach)
            # and a named pipe/unix domain socket for ipc
            QLocalServer.removeServer(self.KEY)
            self._srv = QLocalServer(self)
            self.connect(self._srv, SIGNAL("newConnection()"), self.onRecv)
            self._srv.listen(self.KEY)
        else:
            # we accept only one command line argument. if it's missing, send
            # a blank screen to just raise the existing window
            opts, args = parseArgs(self._argv)
            buf = "raise"
            if args and args[0]:
                buf = os.path.abspath(args[0])
            self.sendMsg(buf)
            return True

    def sendMsg(self, txt):
        sock = QLocalSocket(self)
        sock.connectToServer(self.KEY, QIODevice.WriteOnly)
        if not sock.waitForConnected(self.TMOUT):
            raise Exception("existing instance not responding")
        sock.write(txt)
        if not sock.waitForBytesWritten(self.TMOUT):
            raise Exception("existing instance not emptying")
        sock.disconnectFromServer()

    def onRecv(self):
        sock = self._srv.nextPendingConnection()
        if not sock.waitForReadyRead(self.TMOUT):
            sys.stderr.write(sock.errorString())
            return
        buf = sock.readAll()
        self.emit(SIGNAL("appMsg"), buf)
        sock.disconnectFromServer()

    # OS X file/url handler
    ##################################################

    def event(self, evt):
        if evt.type() == QEvent.FileOpen:
            self.emit(SIGNAL("appMsg"), evt.file() or "raise")
            return True
        return QApplication.event(self, evt)

def parseArgs(argv):
    "Returns (opts, args)."
    parser = optparse.OptionParser()
    parser.usage = "%prog [OPTIONS] [file to import]"
    parser.add_option("-b", "--base", help="path to base folder")
    parser.add_option("-p", "--profile", help="profile name to load")
    parser.add_option("-l", "--lang", help="interface language (en, de, etc)")
    return parser.parse_args(argv[1:])

def run():
    global mw
    from anki.utils import  isMac

    # on osx we'll need to add the qt plugins to the search path
    if isMac and getattr(sys, 'frozen', None):
        rd = os.path.abspath(moduleDir + "/../../..")
        QCoreApplication.setLibraryPaths([rd])

    # create the app
    app = AnkiApp(sys.argv)
    QCoreApplication.setApplicationName("Anki")
    if app.secondInstance():
        # we've signaled the primary instance, so we should close
        return

    # we must have a usable temp dir
    try:
        tempfile.gettempdir()
    except:
        QMessageBox.critical(
            None, "Error", """\
No usable temporary folder found. Make sure C:\\temp exists or TEMP in your \
environment points to a valid, writable folder.""")
        return

    # qt version must be up to date
    if qtmajor <= 4 and qtminor <= 6:
        QMessageBox.warning(
            None, "Error", "Your Qt version is known to be buggy. Until you "
          "upgrade to a newer Qt, you may experience issues such as images "
          "failing to show up during review.")

    # parse args
    opts, args = parseArgs(sys.argv)
    opts.base = unicode(opts.base or "", sys.getfilesystemencoding())
    opts.profile = unicode(opts.profile or "", sys.getfilesystemencoding())

    # profile manager
    from aqt.profiles import ProfileManager
    pm = ProfileManager(opts.base, opts.profile)

    # i18n
    setupLang(pm, app, opts.lang)

    # remaining pm init
    pm.ensureProfile()

    # load the main window
    import aqt.main
    mw = aqt.main.AnkiQt(app, pm, args)
    app.exec_()

if __name__ == "__main__":
    run()
<commit_msg>bump version<commit_after># Copyright: Damien Elmes <anki@ichi2.net>
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html

import os, sys, optparse, atexit, tempfile, __builtin__
from aqt.qt import *
import locale, gettext
import anki.lang
from anki.consts import HELP_SITE
from anki.lang import langDir

appVersion="2.0.7"
appWebsite="http://ankisrs.net/"
appChanges="http://ankisrs.net/docs/changes.html"
appDonate="http://ankisrs.net/support/"
appShared="https://ankiweb.net/shared/"
appUpdate="https://ankiweb.net/update/desktop"
appHelpSite=HELP_SITE
mw = None # set on init

moduleDir = os.path.split(os.path.dirname(os.path.abspath(__file__)))[0]

try:
    import aqt.forms
except ImportError, e:
    if "forms" in str(e):
        print "If you're running from git, did you run build_ui.sh?"
        print
    raise

# Dialog manager - manages modeless windows
##########################################################################

class DialogManager(object):

    def __init__(self):
        from aqt import addcards, browser, editcurrent
        self._dialogs = {
            "AddCards": [addcards.AddCards, None],
            "Browser": [browser.Browser, None],
            "EditCurrent": [editcurrent.EditCurrent, None],
        }

    def open(self, name, *args):
        (creator, instance) = self._dialogs[name]
        if instance:
            instance.activateWindow()
            instance.raise_()
            return instance
        else:
            instance = creator(*args)
            self._dialogs[name][1] = instance
            return instance

    def close(self, name):
        self._dialogs[name] = [self._dialogs[name][0], None]

    def closeAll(self):
        for (n, (creator, instance)) in self._dialogs.items():
            if instance:
                instance.forceClose = True
                instance.close()
                self.close(n)

dialogs = DialogManager()

# Language handling
##########################################################################
# Qt requires its translator to be installed before any GUI widgets are
# loaded, and we need the Qt language to match the gettext language or
# translated shortcuts will not work.

_gtrans = None
_qtrans = None

def setupLang(pm, app, force=None):
    global _gtrans, _qtrans
    try:
        locale.setlocale(locale.LC_ALL, '')
    except:
        pass
    lang = force or pm.meta["defaultLang"]
    dir = langDir()
    # gettext
    _gtrans = gettext.translation(
        'anki', dir, languages=[lang], fallback=True)
    __builtin__.__dict__['_'] = _gtrans.ugettext
    __builtin__.__dict__['ngettext'] = _gtrans.ungettext
    anki.lang.setLang(lang, local=False)
    if lang in ("he","ar","fa"):
        app.setLayoutDirection(Qt.RightToLeft)
    else:
        app.setLayoutDirection(Qt.LeftToRight)
    # qt
    _qtrans = QTranslator()
    if _qtrans.load("qt_" + lang, dir):
        app.installTranslator(_qtrans)

# App initialisation
##########################################################################

class AnkiApp(QApplication):

    # Single instance support on Win32/Linux
    ##################################################

    KEY = "anki"
    TMOUT = 5000

    def __init__(self, argv):
        QApplication.__init__(self, argv)
        self._argv = argv
        self._shmem = QSharedMemory(self.KEY)
        self.alreadyRunning = self._shmem.attach()

    def secondInstance(self):
        if not self.alreadyRunning:
            # use a 1 byte shared memory instance to signal we exist
            if not self._shmem.create(1):
                raise Exception("shared memory not supported")
            atexit.register(self._shmem.detach)
            # and a named pipe/unix domain socket for ipc
            QLocalServer.removeServer(self.KEY)
            self._srv = QLocalServer(self)
            self.connect(self._srv, SIGNAL("newConnection()"), self.onRecv)
            self._srv.listen(self.KEY)
        else:
            # we accept only one command line argument. if it's missing, send
            # a blank screen to just raise the existing window
            opts, args = parseArgs(self._argv)
            buf = "raise"
            if args and args[0]:
                buf = os.path.abspath(args[0])
            self.sendMsg(buf)
            return True

    def sendMsg(self, txt):
        sock = QLocalSocket(self)
        sock.connectToServer(self.KEY, QIODevice.WriteOnly)
        if not sock.waitForConnected(self.TMOUT):
            raise Exception("existing instance not responding")
        sock.write(txt)
        if not sock.waitForBytesWritten(self.TMOUT):
            raise Exception("existing instance not emptying")
        sock.disconnectFromServer()

    def onRecv(self):
        sock = self._srv.nextPendingConnection()
        if not sock.waitForReadyRead(self.TMOUT):
            sys.stderr.write(sock.errorString())
            return
        buf = sock.readAll()
        self.emit(SIGNAL("appMsg"), buf)
        sock.disconnectFromServer()

    # OS X file/url handler
    ##################################################

    def event(self, evt):
        if evt.type() == QEvent.FileOpen:
            self.emit(SIGNAL("appMsg"), evt.file() or "raise")
            return True
        return QApplication.event(self, evt)

def parseArgs(argv):
    "Returns (opts, args)."
    parser = optparse.OptionParser()
    parser.usage = "%prog [OPTIONS] [file to import]"
    parser.add_option("-b", "--base", help="path to base folder")
    parser.add_option("-p", "--profile", help="profile name to load")
    parser.add_option("-l", "--lang", help="interface language (en, de, etc)")
    return parser.parse_args(argv[1:])

def run():
    global mw
    from anki.utils import  isMac

    # on osx we'll need to add the qt plugins to the search path
    if isMac and getattr(sys, 'frozen', None):
        rd = os.path.abspath(moduleDir + "/../../..")
        QCoreApplication.setLibraryPaths([rd])

    # create the app
    app = AnkiApp(sys.argv)
    QCoreApplication.setApplicationName("Anki")
    if app.secondInstance():
        # we've signaled the primary instance, so we should close
        return

    # we must have a usable temp dir
    try:
        tempfile.gettempdir()
    except:
        QMessageBox.critical(
            None, "Error", """\
No usable temporary folder found. Make sure C:\\temp exists or TEMP in your \
environment points to a valid, writable folder.""")
        return

    # qt version must be up to date
    if qtmajor <= 4 and qtminor <= 6:
        QMessageBox.warning(
            None, "Error", "Your Qt version is known to be buggy. Until you "
          "upgrade to a newer Qt, you may experience issues such as images "
          "failing to show up during review.")

    # parse args
    opts, args = parseArgs(sys.argv)
    opts.base = unicode(opts.base or "", sys.getfilesystemencoding())
    opts.profile = unicode(opts.profile or "", sys.getfilesystemencoding())

    # profile manager
    from aqt.profiles import ProfileManager
    pm = ProfileManager(opts.base, opts.profile)

    # i18n
    setupLang(pm, app, opts.lang)

    # remaining pm init
    pm.ensureProfile()

    # load the main window
    import aqt.main
    mw = aqt.main.AnkiQt(app, pm, args)
    app.exec_()

if __name__ == "__main__":
    run()
<|endoftext|>


<commit_before>"""
Copyright 2015 Ronald J. Nowling

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

from exceptions import NotImplementedError
import os
import sys

import numpy as np

from newioutils import *

DEFAULT_COLUMNS = {'CHROM' : 0, 'POS' : 1, 'ID' : 2, 'REF' : 3, 'ALT' : 4, 'QUAL' : 5, 'FILTER' : 6, 'INFO' : 7, 'FORMAT' : 8}

def read_groups(flname):
    fl = open(flname)
    groups = dict()
    for group_id, ln in enumerate(fl):
        cols = ln.strip().split(",")
        for ident in cols[1:]:
            groups[ident] = group_id

    return groups

def extract_features(triplet):
    chrom, pos, snps = triplet
    n_individuals = len(snps)

    all_nucl = set()
    for nucl_dict in snps:
        all_nucl.update(nucl_dict.keys())

    features = dict()
    for nucl in all_nucl:
        features[(chrom, pos, nucl)] = np.zeros(n_individuals)

    for idx, nucl_dict in enumerate(snps):
        for nucl, count in nucl_dict.items():
            features[(chrom, pos, nucl)][idx] = count

    return { key : tuple(value) for key, value in features.iteritems() }

def parse_vcf_line(ln):
    cols = ln.strip().split()
    ref_seq = cols[DEFAULT_COLUMNS["REF"]]
    alt_seq = cols[DEFAULT_COLUMNS["ALT"]]

    snps = []
    for i, col in enumerate(cols[len(DEFAULT_COLUMNS):]):
        tags = col.split(":")[0].split("/")

        nucleotides = defaultdict(int)

        for tag in tags:
            if tag == ".":
                # ignore unknown nucleotides
                pass
            elif tag == "0":
                nucleotides[ref_seq] += 1
            elif tag == "1":
                nucleotides[alt_seq] += 1
            else:
                raise NotImplementedError("Support for non-biallelic SNPs not implemented. Found '" + tag + "'")

        snps.append(dict(nucleotides))

    return (cols[DEFAULT_COLUMNS["CHROM"]], cols[DEFAULT_COLUMNS["POS"]], snps)

class SelectIndividuals(object):
    def __init__(self, kept_individual_idx):
        self.kept_individual_idx = kept_individual_idx

    def __call__(self, triplets):
        chrom, pos, snps = triplets
        selected = [snps[idx] for idx in self.kept_individual_idx]
        return (chrom, pos, selected)

def stream_vcf_fl(flname, kept_individuals):
    with open(flname) as fl:
        for ln in fl:
            if ln.startswith("#CHROM"):
                column_names = ln[1:].strip().split()
                break

        all_ids = column_names[len(DEFAULT_COLUMNS):]

        individual_ids = [ident for ident in all_ids
                          if ident in kept_individuals]

        individual_idx = list([i for i, ident in enumerate(all_ids)
                              if ident in kept_individuals])

        yield individual_ids, individual_idx

        for ln in fl:
            if not ln.startswith("#"):
                yield ln

def is_fixed_difference(snp_features, class_labels):
    n_individuals = len(class_labels)

    individuals_without_missing = []
    for idx in xrange(n_individuals):
        nucl_count = 0
        for key, features in snp_features.items():
            nucl_count += features[idx]
        if nucl_count == 2:
            individuals_without_missing.append(idx)

    class_entries = defaultdict(set)
    for idx in individuals_without_missing:
        nucl_counts = []
        for key, features in snp_features.items():
            nucl_counts.append(features[idx])
        class_entries[class_labels[idx]].add(tuple(nucl_counts))

    all_class_entries = reduce(lambda x, y: x.intersection(y), class_entries.values())

    # fixed differences, any missing
    is_trivial = len(all_class_entries) == 0
    has_missing = len(individuals_without_missing) != len(class_labels)

    return is_trivial, has_missing

def convert(groups_flname, vcf_flname, outbase, compress):
    groups = read_groups(groups_flname)

    gen = stream_vcf_fl(vcf_flname, groups.keys())
    individual_ids, individual_idx = list(next(gen))

    parsed_lines = map(parse_vcf_line, gen)
    selected_individuals = map(SelectIndividuals(individual_idx), parsed_lines)
    extracted_features = map(extract_features, selected_individuals)

    class_labels = [groups[ident] for ident in individual_ids]

    feature_labels = []
    trivial_snps = dict()
    missing = dict()
    column_idx = 0
    feature_column = dict()

    feature_columns = []
    for snp_features in extracted_features:
        # all nucleotides are missing or only one genotype
        if len(snp_features) <= 1:
            continue

        is_trivial, is_missing_data = is_fixed_difference(snp_features, class_labels)

        snp_label = snp_features.items()[0][0][:2]
        trivial_snps[snp_label] = is_trivial
        missing[snp_label] = is_missing_data

        if compress:
            for label, column in snp_features.iteritems():
                if tuple(column) not in feature_column:
                    feature_column[tuple(column)] = column_idx
                    feature_labels.append([label])
                    feature_columns.append(tuple(column))
                    column_idx += 1
                else:
                    feature_column_idx = feature_column[tuple(column)]
                    feature_labels[feature_column_idx].append(label)
        else:
            for label, column in snp_features.iteritems():
                feature_labels.append([label])
                feature_columns.append(tuple(column))
                column_idx += 1

    # need to transpose, otherwise we get (n_features, n_individuals) instead
    feature_matrix = np.array(feature_columns).T

    print feature_matrix.shape[0], "individuals", feature_matrix.shape[1], "features"

    np.save(os.path.join(outbase, FEATURE_MATRIX_FLNAME), feature_matrix)
    to_json(os.path.join(outbase, FEATURE_LABELS_FLNAME), feature_labels)
    to_json(os.path.join(outbase, SAMPLE_LABELS_FLNAME), individual_ids)
    to_json(os.path.join(outbase, CLASS_LABELS_FLNAME), class_labels)
    to_json(os.path.join(outbase, FIXED_DIFFERENCES_FLNAME), trivial_snps)
    to_json(os.path.join(outbase, MISSING_DATA_FLNAME), missing)

<commit_msg>Move filtering of features<commit_after>"""
Copyright 2015 Ronald J. Nowling

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

from exceptions import NotImplementedError
import os
import sys

import numpy as np

from newioutils import *

DEFAULT_COLUMNS = {'CHROM' : 0, 'POS' : 1, 'ID' : 2, 'REF' : 3, 'ALT' : 4, 'QUAL' : 5, 'FILTER' : 6, 'INFO' : 7, 'FORMAT' : 8}

def read_groups(flname):
    fl = open(flname)
    groups = dict()
    for group_id, ln in enumerate(fl):
        cols = ln.strip().split(",")
        for ident in cols[1:]:
            groups[ident] = group_id

    return groups

def extract_features(triplet):
    chrom, pos, snps = triplet
    n_individuals = len(snps)

    all_nucl = set()
    for nucl_dict in snps:
        all_nucl.update(nucl_dict.keys())

    features = dict()
    for nucl in all_nucl:
        features[(chrom, pos, nucl)] = np.zeros(n_individuals)

    for idx, nucl_dict in enumerate(snps):
        for nucl, count in nucl_dict.items():
            features[(chrom, pos, nucl)][idx] = count

    return { key : tuple(value) for key, value in features.iteritems() }

def parse_vcf_line(ln):
    cols = ln.strip().split()
    ref_seq = cols[DEFAULT_COLUMNS["REF"]]
    alt_seq = cols[DEFAULT_COLUMNS["ALT"]]

    snps = []
    for i, col in enumerate(cols[len(DEFAULT_COLUMNS):]):
        tags = col.split(":")[0].split("/")

        nucleotides = defaultdict(int)

        for tag in tags:
            if tag == ".":
                # ignore unknown nucleotides
                pass
            elif tag == "0":
                nucleotides[ref_seq] += 1
            elif tag == "1":
                nucleotides[alt_seq] += 1
            else:
                raise NotImplementedError("Support for non-biallelic SNPs not implemented. Found '" + tag + "'")

        snps.append(dict(nucleotides))

    return (cols[DEFAULT_COLUMNS["CHROM"]], cols[DEFAULT_COLUMNS["POS"]], snps)

class SelectIndividuals(object):
    def __init__(self, kept_individual_idx):
        self.kept_individual_idx = kept_individual_idx

    def __call__(self, triplets):
        chrom, pos, snps = triplets
        selected = [snps[idx] for idx in self.kept_individual_idx]
        return (chrom, pos, selected)

def stream_vcf_fl(flname, kept_individuals):
    with open(flname) as fl:
        for ln in fl:
            if ln.startswith("#CHROM"):
                column_names = ln[1:].strip().split()
                break

        all_ids = column_names[len(DEFAULT_COLUMNS):]

        individual_ids = [ident for ident in all_ids
                          if ident in kept_individuals]

        individual_idx = list([i for i, ident in enumerate(all_ids)
                              if ident in kept_individuals])

        yield individual_ids, individual_idx

        for ln in fl:
            if not ln.startswith("#"):
                yield ln

def is_fixed_difference(snp_features, class_labels):
    n_individuals = len(class_labels)

    individuals_without_missing = []
    for idx in xrange(n_individuals):
        nucl_count = 0
        for key, features in snp_features.items():
            nucl_count += features[idx]
        if nucl_count == 2:
            individuals_without_missing.append(idx)

    class_entries = defaultdict(set)
    for idx in individuals_without_missing:
        nucl_counts = []
        for key, features in snp_features.items():
            nucl_counts.append(features[idx])
        class_entries[class_labels[idx]].add(tuple(nucl_counts))

    all_class_entries = reduce(lambda x, y: x.intersection(y), class_entries.values())

    # fixed differences, any missing
    is_trivial = len(all_class_entries) == 0
    has_missing = len(individuals_without_missing) != len(class_labels)

    return is_trivial, has_missing

def convert(groups_flname, vcf_flname, outbase, compress):
    groups = read_groups(groups_flname)

    gen = stream_vcf_fl(vcf_flname, groups.keys())
    individual_ids, individual_idx = list(next(gen))

    parsed_lines = map(parse_vcf_line, gen)
    selected_individuals = map(SelectIndividuals(individual_idx), parsed_lines)
    extracted_features = map(extract_features, selected_individuals)
    # all nucleotides are missing or only one genotype
    non_empty_features = filter(lambda features: len(features) > 1, extracted_features)

    class_labels = [groups[ident] for ident in individual_ids]

    feature_labels = []
    trivial_snps = dict()
    missing = dict()
    column_idx = 0
    feature_column = dict()

    feature_columns = []
    for snp_features in non_empty_features:
        is_trivial, is_missing_data = is_fixed_difference(snp_features, class_labels)

        snp_label = snp_features.items()[0][0][:2]
        trivial_snps[snp_label] = is_trivial
        missing[snp_label] = is_missing_data

        if compress:
            for label, column in snp_features.iteritems():
                if tuple(column) not in feature_column:
                    feature_column[tuple(column)] = column_idx
                    feature_labels.append([label])
                    feature_columns.append(tuple(column))
                    column_idx += 1
                else:
                    feature_column_idx = feature_column[tuple(column)]
                    feature_labels[feature_column_idx].append(label)
        else:
            for label, column in snp_features.iteritems():
                feature_labels.append([label])
                feature_columns.append(tuple(column))
                column_idx += 1

    # need to transpose, otherwise we get (n_features, n_individuals) instead
    feature_matrix = np.array(feature_columns).T

    print feature_matrix.shape[0], "individuals", feature_matrix.shape[1], "features"

    np.save(os.path.join(outbase, FEATURE_MATRIX_FLNAME), feature_matrix)
    to_json(os.path.join(outbase, FEATURE_LABELS_FLNAME), feature_labels)
    to_json(os.path.join(outbase, SAMPLE_LABELS_FLNAME), individual_ids)
    to_json(os.path.join(outbase, CLASS_LABELS_FLNAME), class_labels)
    to_json(os.path.join(outbase, FIXED_DIFFERENCES_FLNAME), trivial_snps)
    to_json(os.path.join(outbase, MISSING_DATA_FLNAME), missing)

<|endoftext|>


<commit_before>#!/usr/bin/env python3.2

from hashlib import md5

try:
    from PIL import Image
    from PIL.ImageDraw import Draw
except ImportError:
    text_output = True
else:
    text_output = False

import csv
import os.path

import ariblib

save_dir = os.path.expanduser('~/.ariblib/drcs/')
mapping_path = os.path.join((os.path.split(ariblib.__file__)[0]), 'drcs.tsv')
user_mapping_path = os.path.expanduser('~/.ariblib/drcs.tsv')
mapping = {}

# DRCSイメージ保存ディレクトリが存在しない場合は作成する
if not os.path.isdir(save_dir):
    import os
    os.makedirs(save_dir)

for path in (mapping_path, user_mapping_path):
    try:
        with open(path) as f:
            reader = csv.reader(f, delimiter='\t')
            mapping.update(line for line in reader)
    except IOError:
        pass

class DRCSImage(object):

    """DRCSの画像イメージ"""

    def __init__(self, width, height, bgcolor='white'):
        self.image = Image.new('RGB', (width, height), bgcolor)
        self.hash = None

    def point(self, patterns, color='black'):
        hasher = md5()
        draw = Draw(self.image)
        for y, pattern in enumerate(patterns):
            pattern_data = pattern.pattern_data
            hasher.update(pattern_data)
            points = [(x, y) for x, dot in enumerate(_to_bit(pattern_data))
                             if dot == '1']
            draw.point(points, color)
        self.hash = hasher.hexdigest()

    def save(self, ext='png', path=None):
        if path is None:
            if self.hash is None:
                raise ValueError('画像イメージが作成されていません')
            path = self.hash
        self.image.save(os.path.join(save_dir, path + '.' + ext))

class DRCSText(object):

    """DRCSのテキストイメージ"""

    def __init__(self, width, height, bgcolor='white'):
        self.hash = None
        self.dots = []

    def point(self, patterns, color='black'):
        hasher = md5()
        for pattern in patterns:
            pattern_data = pattern.pattern_data
            hasher.update(pattern_data)
            points = _to_bit(pattern_data).replace('0', '　').replace('1', '■')
            self.dots.append(points)
        self.hash = hasher.hexdigest()

    def save(self, ext='txt', path=None):
        if path is None:
            if self.hash is None:
                raise ValueError('画像イメージが作成されていません')
            path = self.hash
        with open(os.path.join(save_dir, path + '.' + ext), 'w') as out:
            out.write('\n'.join(self.dots))

def _to_bit(raw):
    """bytearrayを0,1のビットを表す文字列に変換する"""

    return ''.join(map(lambda s: format(s, '08b'), raw))

# 画像出力ができないときはテキスト出力を行う
if text_output:
    DRCSImage = DRCSText

<commit_msg>pep8: drcs.py<commit_after>#!/usr/bin/env python3.2

from hashlib import md5

try:
    from PIL import Image
    from PIL.ImageDraw import Draw
except ImportError:
    text_output = True
else:
    text_output = False

import csv
import os.path

import ariblib

save_dir = os.path.expanduser('~/.ariblib/drcs/')
mapping_path = os.path.join((os.path.split(ariblib.__file__)[0]), 'drcs.tsv')
user_mapping_path = os.path.expanduser('~/.ariblib/drcs.tsv')
mapping = {}

# DRCSイメージ保存ディレクトリが存在しない場合は作成する
if not os.path.isdir(save_dir):
    import os
    os.makedirs(save_dir)

for path in (mapping_path, user_mapping_path):
    try:
        with open(path) as f:
            reader = csv.reader(f, delimiter='\t')
            mapping.update(line for line in reader)
    except IOError:
        pass

class DRCSImage(object):

    """DRCSの画像イメージ"""

    def __init__(self, width, height, bgcolor='white'):
        self.image = Image.new('RGB', (width, height), bgcolor)
        self.hash = None

    def point(self, patterns, color='black'):
        hasher = md5()
        draw = Draw(self.image)
        for y, pattern in enumerate(patterns):
            pattern_data = pattern.pattern_data
            hasher.update(pattern_data)
            points = [
                (x, y)
                for x, dot in enumerate(_to_bit(pattern_data)) if dot == '1'
            ]
            draw.point(points, color)
        self.hash = hasher.hexdigest()

    def save(self, ext='png', path=None):
        if path is None:
            if self.hash is None:
                raise ValueError('画像イメージが作成されていません')
            path = self.hash
        self.image.save(os.path.join(save_dir, path + '.' + ext))

class DRCSText(object):

    """DRCSのテキストイメージ"""

    def __init__(self, width, height, bgcolor='white'):
        self.hash = None
        self.dots = []

    def point(self, patterns, color='black'):
        hasher = md5()
        for pattern in patterns:
            pattern_data = pattern.pattern_data
            hasher.update(pattern_data)
            points = _to_bit(pattern_data).replace('0', '　').replace('1', '■')
            self.dots.append(points)
        self.hash = hasher.hexdigest()

    def save(self, ext='txt', path=None):
        if path is None:
            if self.hash is None:
                raise ValueError('画像イメージが作成されていません')
            path = self.hash
        with open(os.path.join(save_dir, path + '.' + ext), 'w') as out:
            out.write('\n'.join(self.dots))

def _to_bit(raw):
    """bytearrayを0,1のビットを表す文字列に変換する"""

    return ''.join(map(lambda s: format(s, '08b'), raw))

# 画像出力ができないときはテキスト出力を行う
if text_output:
    DRCSImage = DRCSText
<|endoftext|>


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

Copy this code and do

    import hanging_threads

If a thread is at the same place for SECONDS_FROZEN then the stacktrace is printed.

This script prints

--------------------    Thread 6628     --------------------
  File "hanging_threads.py", line 70, in <module>
        time.sleep(3) # TEST
--------------------    Thread 6628     --------------------
  File "hanging_threads.py", line 70, in <module>
        time.sleep(3) # TEST

"""
import sys
import threading
import linecache
import time

__version__ = "2.0.0"
__author__ = "Nicco Kunzmann"

SECONDS_FROZEN = 10  # seconds
TEST_INTERVAL = 100 #milliseconds

def start_monitoring(seconds_frozen=SECONDS_FROZEN,
                     test_interval=TEST_INTERVAL):
    """Start monitoring threads

    seconds_frozen - How much time should thread hang to activate printing stack trace - default(10)
    tests_interval - Sleep time of monitoring thread (in milliseconds) - default(100)
    """
    thread = StoppableThread(target=monitor, args=(seconds_frozen,
                                                   test_interval))
    thread.daemon = True
    thread.start()
    return thread

class StoppableThread(threading.Thread):
    """
    Thread class with a stop() method.
    The thread itself has to check regularly for the is_stopped() condition.
    """
    def __init__(self, *args, **kwargs):
        super(StoppableThread, self).__init__(*args, **kwargs)
        self._stopped = False

    def stop(self):
        self._stopped = True

    def is_stopped(self):
        return self._stopped

def monitor(seconds_frozen, test_interval):
    """Monitoring thread function

    Checks if thread is hanging for time defined by
    seconds_frozen parameter every test_interval milliseconds
    """
    current_thread = threading.current_thread()
    hanging_threads = set()
    old_threads = {}  # Threads found on previous iteration.

    while not current_thread.is_stopped():
        new_threads = get_current_frames()

        # Report died threads.
        for thread_id in old_threads.keys():
            if thread_id not in new_threads and thread_id in hanging_threads:
                log_died_thread(thread_id)

        # Process live threads.
        time.sleep(test_interval/1000.)
        now = time.time()
        then = now - seconds_frozen
        for thread_id, thread_data in new_threads.items():
            # Don't report the monitor thread.
            if thread_id == current_thread.ident:
                continue
            frame = thread_data['frame']
            # If thread is new or it's stack is changed then update time.
            if (thread_id not in old_threads or
                    frame != old_threads[thread_id]['frame']):
                thread_data['time'] = now
                # If the thread was hanging then report awaked thread.
                if thread_id in hanging_threads:
                    hanging_threads.remove(thread_id)
                    log_awaked_thread(thread_id)
            else:
                # If stack is not changed then keep old time.
                last_change_time = old_threads[thread_id]['time']
                thread_data['time'] = last_change_time
                # Check if this is a new hanging thread.
                if (thread_id not in hanging_threads and
                        last_change_time < then):
                    # Gotcha!
                    hanging_threads.add(thread_id)
                    # Report the hanged thread.
                    log_hanged_thread(thread_id, frame)
        old_threads = new_threads

def get_current_frames():
    """Return current threads prepared for further processing"""
    return dict(
        (thread_id, {'frame': thread2list(frame), 'time': None})
        for thread_id, frame in sys._current_frames().items()
    )

def frame2string(frame):
    """Return info about frame

    Keyword arg:
        frame

    Return string in format:

    File {file name}, line {line number}, in {name of parent of code object ?}
    Line from file at line number

    """
    lineno = frame.f_lineno  # or f_lasti
    co = frame.f_code
    filename = co.co_filename
    name = co.co_name
    s = '  File "{0}", line {1}, in {2}'.format(filename, lineno, name)
    line = linecache.getline(filename, lineno, frame.f_globals).lstrip()
    return s + '\n\t' + line

def thread2list(frame):
    """Return list with string frame representation of each frame of thread"""
    l = []
    while frame:
        l.insert(0, frame2string(frame))
        frame = frame.f_back
    return l

def log_hanged_thread(thread_id, frame):
    """Print the stack trace of the deadlock after hanging `seconds_frozen`"""
    write_log('Thread {0} hangs '.format(thread_id), ''.join(frame))

def log_awaked_thread(thread_id):
    write_log('Thread {0} awaked'.format(thread_id))

def log_died_thread(thread_id):
    write_log('Thread {0} died  '.format(thread_id))

def write_log(title, message=''):
    sys.stderr.write(''.join([
        title.center(40).center(60, '-'), '\n', message
    ]))
<commit_msg>Fix the comment formatting<commit_after>#!/usr/bin/python
"""

Copy this code and do

    import hanging_threads

If a thread is at the same place for SECONDS_FROZEN then the stacktrace is printed.

This script prints

--------------------    Thread 6628     --------------------
  File "hanging_threads.py", line 70, in <module>
        time.sleep(3) # TEST
--------------------    Thread 6628     --------------------
  File "hanging_threads.py", line 70, in <module>
        time.sleep(3) # TEST

"""
import sys
import threading
import linecache
import time

__version__ = "2.0.0"
__author__ = "Nicco Kunzmann"

SECONDS_FROZEN = 10  # seconds
TEST_INTERVAL = 100  # milliseconds

def start_monitoring(seconds_frozen=SECONDS_FROZEN,
                     test_interval=TEST_INTERVAL):
    """Start monitoring threads

    seconds_frozen - How much time should thread hang to activate printing stack trace - default(10)
    tests_interval - Sleep time of monitoring thread (in milliseconds) - default(100)
    """
    thread = StoppableThread(target=monitor, args=(seconds_frozen,
                                                   test_interval))
    thread.daemon = True
    thread.start()
    return thread

class StoppableThread(threading.Thread):
    """
    Thread class with a stop() method.
    The thread itself has to check regularly for the is_stopped() condition.
    """
    def __init__(self, *args, **kwargs):
        super(StoppableThread, self).__init__(*args, **kwargs)
        self._stopped = False

    def stop(self):
        self._stopped = True

    def is_stopped(self):
        return self._stopped

def monitor(seconds_frozen, test_interval):
    """Monitoring thread function

    Checks if thread is hanging for time defined by
    seconds_frozen parameter every test_interval milliseconds
    """
    current_thread = threading.current_thread()
    hanging_threads = set()
    old_threads = {}  # Threads found on previous iteration.

    while not current_thread.is_stopped():
        new_threads = get_current_frames()

        # Report died threads.
        for thread_id in old_threads.keys():
            if thread_id not in new_threads and thread_id in hanging_threads:
                log_died_thread(thread_id)

        # Process live threads.
        time.sleep(test_interval/1000.)
        now = time.time()
        then = now - seconds_frozen
        for thread_id, thread_data in new_threads.items():
            # Don't report the monitor thread.
            if thread_id == current_thread.ident:
                continue
            frame = thread_data['frame']
            # If thread is new or it's stack is changed then update time.
            if (thread_id not in old_threads or
                    frame != old_threads[thread_id]['frame']):
                thread_data['time'] = now
                # If the thread was hanging then report awaked thread.
                if thread_id in hanging_threads:
                    hanging_threads.remove(thread_id)
                    log_awaked_thread(thread_id)
            else:
                # If stack is not changed then keep old time.
                last_change_time = old_threads[thread_id]['time']
                thread_data['time'] = last_change_time
                # Check if this is a new hanging thread.
                if (thread_id not in hanging_threads and
                        last_change_time < then):
                    # Gotcha!
                    hanging_threads.add(thread_id)
                    # Report the hanged thread.
                    log_hanged_thread(thread_id, frame)
        old_threads = new_threads

def get_current_frames():
    """Return current threads prepared for further processing"""
    return dict(
        (thread_id, {'frame': thread2list(frame), 'time': None})
        for thread_id, frame in sys._current_frames().items()
    )

def frame2string(frame):
    """Return info about frame

    Keyword arg:
        frame

    Return string in format:

    File {file name}, line {line number}, in {name of parent of code object ?}
    Line from file at line number

    """
    lineno = frame.f_lineno  # or f_lasti
    co = frame.f_code
    filename = co.co_filename
    name = co.co_name
    s = '  File "{0}", line {1}, in {2}'.format(filename, lineno, name)
    line = linecache.getline(filename, lineno, frame.f_globals).lstrip()
    return s + '\n\t' + line

def thread2list(frame):
    """Return list with string frame representation of each frame of thread"""
    l = []
    while frame:
        l.insert(0, frame2string(frame))
        frame = frame.f_back
    return l

def log_hanged_thread(thread_id, frame):
    """Print the stack trace of the deadlock after hanging `seconds_frozen`"""
    write_log('Thread {0} hangs '.format(thread_id), ''.join(frame))

def log_awaked_thread(thread_id):
    write_log('Thread {0} awaked'.format(thread_id))

def log_died_thread(thread_id):
    write_log('Thread {0} died  '.format(thread_id))

def write_log(title, message=''):
    sys.stderr.write(''.join([
        title.center(40).center(60, '-'), '\n', message
    ]))
<|endoftext|>