<commit_before># vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
#    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 sqlalchemy import ForeignKey
from sqlalchemy.schema import Column
from sqlalchemy.schema import MetaData
from sqlalchemy.schema import UniqueConstraint

from melange.db.sqlalchemy.migrate_repo.schema import Boolean
from melange.db.sqlalchemy.migrate_repo.schema import create_tables
from melange.db.sqlalchemy.migrate_repo.schema import DateTime
from melange.db.sqlalchemy.migrate_repo.schema import drop_tables
from melange.db.sqlalchemy.migrate_repo.schema import Integer
from melange.db.sqlalchemy.migrate_repo.schema import String
from melange.db.sqlalchemy.migrate_repo.schema import Table

meta = MetaData()

ip_blocks = Table('ip_blocks', meta,
        Column('id', String(36), primary_key=True, nullable=False),
        Column('network_id', String(255)),
        Column('cidr', String(255), nullable=False),
        Column('created_at', DateTime()),
        Column('updated_at', DateTime()),
        Column('type', String(7)),
        Column('tenant_id', String(255)),
        Column('gateway', String(255)),
        Column('dns1', String(255)),
        Column('dns2', String(255)),
        Column('allocatable_ip_counter', Integer()),
        Column('is_full', Boolean()),
        Column('policy_id', String(36), ForeignKey('policies.id')),
        Column('parent_id', String(36), ForeignKey('ip_blocks.id')))

ip_addresses = Table('ip_addresses', meta,
        Column('id', String(36), primary_key=True, nullable=False),
        Column('address', String(255), nullable=False),
        Column('interface_id', String(255), ForeignKey('interfaces.id')),
        Column('ip_block_id', String(36), ForeignKey('ip_blocks.id')),
        Column('used_by_tenant_id', String(255)),
        Column('created_at', DateTime()),
        Column('updated_at', DateTime()),
        Column('marked_for_deallocation', Boolean()),
        Column('deallocated_at', DateTime()),
        UniqueConstraint('address', 'ip_block_id'))

ip_nats = Table('ip_nats', meta,
        Column('id', String(36), primary_key=True, nullable=False),
        Column('inside_local_address_id',
               String(36),
               ForeignKey('ip_addresses.id'),
               nullable=False),
        Column('inside_global_address_id',
               String(36),
               ForeignKey('ip_addresses.id'),
               nullable=False),
        Column('created_at', DateTime()),
        Column('updated_at', DateTime()))

policies = Table('policies', meta,
        Column('id', String(36), primary_key=True, nullable=False),
        Column('name', String(255), nullable=False),
        Column('tenant_id', String(255)),
        Column('description', String(255)),
        Column('created_at', DateTime()),
        Column('updated_at', DateTime()))

ip_ranges = Table('ip_ranges', meta,
        Column('id', String(36), primary_key=True, nullable=False),
        Column('offset', Integer(), nullable=False),
        Column('length', Integer(), nullable=False),
        Column('policy_id', String(36), ForeignKey('policies.id')),
        Column('created_at', DateTime()),
        Column('updated_at', DateTime()))

ip_octets = Table('ip_octets', meta,
        Column('id', String(36), primary_key=True, nullable=False),
        Column('octet', Integer(), nullable=False),
        Column('policy_id', String(36), ForeignKey('policies.id')),
        Column('created_at', DateTime()),
        Column('updated_at', DateTime()))

ip_routes = Table('ip_routes', meta,
        Column('id', String(36), primary_key=True, nullable=False),
        Column('destination', String(255), nullable=False),
        Column('netmask', String(255)),
        Column('gateway', String(255), nullable=False),
        Column('source_block_id', String(36), ForeignKey('ip_blocks.id')),
        Column('created_at', DateTime()),
        Column('updated_at', DateTime()))

allocatable_ips = Table('allocatable_ips', meta,
        Column('id', String(36), primary_key=True, nullable=False),
        Column('ip_block_id', String(36), ForeignKey('ip_blocks.id')),
        Column('address', String(255), nullable=False),
        Column('created_at', DateTime()),
        Column('updated_at', DateTime()))

mac_address_ranges = Table('mac_address_ranges', meta,
        Column('id', String(36), primary_key=True, nullable=False),
        Column('cidr', String(255), nullable=False),
        Column('next_address', Integer()),
        Column('created_at', DateTime()),
        Column('updated_at', DateTime()))

mac_addresses = Table('mac_addresses', meta,
        Column('id', String(36), primary_key=True, nullable=False),
        Column('address', Integer(), nullable=False),
        Column('mac_address_range_id', String(36),
               ForeignKey('mac_address_ranges.id')),
        Column('interface_id', String(36), ForeignKey('interfaces.id')),
        Column('created_at', DateTime()),
        Column('updated_at', DateTime()),
        UniqueConstraint('interface_id'),
        UniqueConstraint('address'))

interfaces = Table('interfaces', meta,
        Column('id', String(36), primary_key=True, nullable=False),
        Column('virtual_interface_id', String(36), nullable=False),
        Column('device_id', String(36)),
        Column('tenant_id', String(36)),
        Column('created_at', DateTime()),
        Column('updated_at', DateTime()),
        UniqueConstraint('virtual_interface_id'))

allowed_ips = Table('allowed_ips', meta,
        Column('id', String(36), primary_key=True, nullable=False),
        Column('ip_address_id', String(36), ForeignKey('ip_addresses.id'),
               nullable=False),
        Column('interface_id', String(36), ForeignKey('interfaces.id'),
               nullable=False),
        UniqueConstraint('ip_address_id', 'interface_id'))

def upgrade(migrate_engine):
    meta.bind = migrate_engine
    create_tables([policies, ip_ranges, ip_octets, ip_blocks, ip_routes,
                   mac_address_ranges, mac_addresses, interfaces, ip_addresses,
                   ip_nats, allocatable_ips, allowed_ips])

def downgrade(migrate_engine):
    meta.bind = migrate_engine
    drop_tables([allowed_ips, allocatable_ips, ip_nats, ip_addresses,
                 interfaces, mac_addresses, mac_address_ranges, ip_routes,
                 ip_blocks, ip_ranges, ip_octets, policies])
<commit_msg>Fixed table creation order<commit_after># vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
#    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 sqlalchemy import ForeignKey
from sqlalchemy.schema import Column
from sqlalchemy.schema import MetaData
from sqlalchemy.schema import UniqueConstraint

from melange.db.sqlalchemy.migrate_repo.schema import Boolean
from melange.db.sqlalchemy.migrate_repo.schema import create_tables
from melange.db.sqlalchemy.migrate_repo.schema import DateTime
from melange.db.sqlalchemy.migrate_repo.schema import drop_tables
from melange.db.sqlalchemy.migrate_repo.schema import Integer
from melange.db.sqlalchemy.migrate_repo.schema import String
from melange.db.sqlalchemy.migrate_repo.schema import Table

meta = MetaData()

ip_blocks = Table('ip_blocks', meta,
        Column('id', String(36), primary_key=True, nullable=False),
        Column('network_id', String(255)),
        Column('cidr', String(255), nullable=False),
        Column('created_at', DateTime()),
        Column('updated_at', DateTime()),
        Column('type', String(7)),
        Column('tenant_id', String(255)),
        Column('gateway', String(255)),
        Column('dns1', String(255)),
        Column('dns2', String(255)),
        Column('allocatable_ip_counter', Integer()),
        Column('is_full', Boolean()),
        Column('policy_id', String(36), ForeignKey('policies.id')),
        Column('parent_id', String(36), ForeignKey('ip_blocks.id')))

ip_addresses = Table('ip_addresses', meta,
        Column('id', String(36), primary_key=True, nullable=False),
        Column('address', String(255), nullable=False),
        Column('interface_id', String(255), ForeignKey('interfaces.id')),
        Column('ip_block_id', String(36), ForeignKey('ip_blocks.id')),
        Column('used_by_tenant_id', String(255)),
        Column('created_at', DateTime()),
        Column('updated_at', DateTime()),
        Column('marked_for_deallocation', Boolean()),
        Column('deallocated_at', DateTime()),
        UniqueConstraint('address', 'ip_block_id'))

ip_nats = Table('ip_nats', meta,
        Column('id', String(36), primary_key=True, nullable=False),
        Column('inside_local_address_id',
               String(36),
               ForeignKey('ip_addresses.id'),
               nullable=False),
        Column('inside_global_address_id',
               String(36),
               ForeignKey('ip_addresses.id'),
               nullable=False),
        Column('created_at', DateTime()),
        Column('updated_at', DateTime()))

policies = Table('policies', meta,
        Column('id', String(36), primary_key=True, nullable=False),
        Column('name', String(255), nullable=False),
        Column('tenant_id', String(255)),
        Column('description', String(255)),
        Column('created_at', DateTime()),
        Column('updated_at', DateTime()))

ip_ranges = Table('ip_ranges', meta,
        Column('id', String(36), primary_key=True, nullable=False),
        Column('offset', Integer(), nullable=False),
        Column('length', Integer(), nullable=False),
        Column('policy_id', String(36), ForeignKey('policies.id')),
        Column('created_at', DateTime()),
        Column('updated_at', DateTime()))

ip_octets = Table('ip_octets', meta,
        Column('id', String(36), primary_key=True, nullable=False),
        Column('octet', Integer(), nullable=False),
        Column('policy_id', String(36), ForeignKey('policies.id')),
        Column('created_at', DateTime()),
        Column('updated_at', DateTime()))

ip_routes = Table('ip_routes', meta,
        Column('id', String(36), primary_key=True, nullable=False),
        Column('destination', String(255), nullable=False),
        Column('netmask', String(255)),
        Column('gateway', String(255), nullable=False),
        Column('source_block_id', String(36), ForeignKey('ip_blocks.id')),
        Column('created_at', DateTime()),
        Column('updated_at', DateTime()))

allocatable_ips = Table('allocatable_ips', meta,
        Column('id', String(36), primary_key=True, nullable=False),
        Column('ip_block_id', String(36), ForeignKey('ip_blocks.id')),
        Column('address', String(255), nullable=False),
        Column('created_at', DateTime()),
        Column('updated_at', DateTime()))

mac_address_ranges = Table('mac_address_ranges', meta,
        Column('id', String(36), primary_key=True, nullable=False),
        Column('cidr', String(255), nullable=False),
        Column('next_address', Integer()),
        Column('created_at', DateTime()),
        Column('updated_at', DateTime()))

mac_addresses = Table('mac_addresses', meta,
        Column('id', String(36), primary_key=True, nullable=False),
        Column('address', Integer(), nullable=False),
        Column('mac_address_range_id', String(36),
               ForeignKey('mac_address_ranges.id')),
        Column('interface_id', String(36), ForeignKey('interfaces.id')),
        Column('created_at', DateTime()),
        Column('updated_at', DateTime()),
        UniqueConstraint('interface_id'),
        UniqueConstraint('address'))

interfaces = Table('interfaces', meta,
        Column('id', String(36), primary_key=True, nullable=False),
        Column('virtual_interface_id', String(36), nullable=False),
        Column('device_id', String(36)),
        Column('tenant_id', String(36)),
        Column('created_at', DateTime()),
        Column('updated_at', DateTime()),
        UniqueConstraint('virtual_interface_id'))

allowed_ips = Table('allowed_ips', meta,
        Column('id', String(36), primary_key=True, nullable=False),
        Column('ip_address_id', String(36), ForeignKey('ip_addresses.id'),
               nullable=False),
        Column('interface_id', String(36), ForeignKey('interfaces.id'),
               nullable=False),
        UniqueConstraint('ip_address_id', 'interface_id'))

def upgrade(migrate_engine):
    meta.bind = migrate_engine
    create_tables([policies, ip_ranges, ip_octets, ip_blocks, ip_routes,
                   mac_address_ranges, interfaces, mac_addresses, ip_addresses,
                   ip_nats, allocatable_ips, allowed_ips])

def downgrade(migrate_engine):
    meta.bind = migrate_engine
    drop_tables([allowed_ips, allocatable_ips, ip_nats, ip_addresses,
                 mac_addresses, interfaces, mac_address_ranges, ip_routes,
                 ip_blocks, ip_ranges, ip_octets, policies])
<|endoftext|>


<commit_before><commit_msg>add docstring<commit_after>"""Package in cui sono inserite tutte le classi necessarie per i dati.
   Le classi base per rappresentare i dati sono:
   - Room
   - Area
   - Event
   - Image
   - Item
   - ItemRequest
   - Param
   - Var
   - VarRequirement
   Ogni classe rappresenta un tag necessario per rappresentare l'informazione.
   Nella classe Origin si ha la funzione dictionary che ritorna un dizionario
   le cui coppie (chiave, valore) sono rispettivamente gli attributi i valori
   di ogni tag. In ogni classe si ha una variabile di classe che da il nome
   del tag che la classe rappresenta.
   Le informazioni di tutto il progetto sono contenute nella classe Project.
   Importando il modulo project.py si puo' utilizzare la variabile globale
   g_project che contiene tutte le informazioni
"""
<|endoftext|>


<commit_before>import vtk
import matplotlib.cm as cm
import sys

LABEL_NAMES = [\
'olfactory bulb',
'cerebral cortex',
'lateral septal nuclei',
'striatum',
'globus pallidus',
'thalamus',
'hypothalamus',
'hippocampal formation',
'superior colliculus',
'inferior colliculus',
'cerebellum',
'fimbria',
'internal capsule',
'ventricle',
'ventricle',
'corpus callosum',
'subcommissural organ',
'anterior commissure',
'paraflocculus',
'deep mesencephalic nucleus',
'fornix',
'aqueaduct',
'pineal gland',
'substantia nigra',
'brainstem (remainder)',
'pontine gray',
'fasciculus retroflexus',
'amygdala',
'interpeduncular nucleus',
'periacueductal gray',
'nucleus accumbens',
'optic chiasm',
'supraoptic decussation',
'optic tract',
'lateral lemniscus',
'epithalamus',
'mammillary nucleus',
'cochlear nuclei and nerve'
]

def read_intensity_data(filename):
    int_data = {}
    fp = open(filename, 'r')
    lines = fp.readlines()
    for line in lines:
        splited = line.strip().split(',')
        int_data[int(splited[0])] = float(splited[1])

    return int_data

def draw_scene(int_filename, color_mode=0, screen_name=None):
    ###############################################################################
    # read polydata file
    #
    offscreen = False
    draw_axes = False

    segs = []
    segs_mapper = []
    segs_actor = []
    transforms = []
    transforms_filter = []

    seg_fileformat = '/media/nebula/data/bah/seg2/seg%05d.vtk'
    #seg_fileformat = '/media/nebula/data/bah/vtk/seg%05d.vtk'
    #int_filename = '../matching_area/result.txt'

    int_data = read_intensity_data(int_filename)
    int_sum = sum(int_data)
    int_data_sorted = {}

    transform = vtk.vtkTransform()
    transform.RotateWXYZ(90, 0, 1, 0)
    transformFilter = vtk.vtkTransformPolyDataFilter()
    transformFilter.SetTransform(transform)
    transformFilter

    for i in range(1, 39):
        segs.append(vtk.vtkPolyDataReader())
        segs[-1].SetFileName(seg_fileformat % i)

        transforms.append(vtk.vtkTransform())
        #transforms[-1].RotateWXYZ(90., 0, 1, 0)
        transforms_filter.append(vtk.vtkTransformPolyDataFilter())
        transforms_filter[-1].SetTransform(transforms[-1])
        transforms_filter[-1].SetInputConnection(segs[-1].GetOutputPort())
        transforms_filter[-1].Update()

        segs_mapper.append(vtk.vtkPolyDataMapper())
        #segs_mapper[-1].SetInputConnection(segs[-1].GetOutputPort())
        segs_mapper[-1].SetInputConnection(transforms_filter[-1].GetOutputPort())
        segs_actor.append(vtk.vtkActor())
        segs_actor[-1].SetMapper(segs_mapper[-1])
        segs_actor[-1].GetProperty().SetOpacity(0.1)
        #color = cm.jet(i/39.)
        #segs_actor[-1].GetProperty().SetColor(color[0], color[1], color[2])

    i = 0
    for k, v in sorted(int_data.items(), key=lambda x:x[1], reverse=True):
        if i < 9:
            segs_actor[k-1].GetProperty().SetOpacity(0.8)
            if color_mode == 0:
                color = ((v-40) / 20.)
                segs_actor[k-1].GetProperty().SetColor(color, 0, 0)
            elif color_mode == 1:
                color = cm.jet( (v-float(int_sum/40)) / float(int_sum) * 10.)
                segs_actor[k-1].GetProperty().SetColor(color[0], color[1], color[2])

            print ' Rank %d : %s (%d) = %d' % (i+1, LABEL_NAMES[k-1], k, v)
            #print color
            i += 1
            #int_data_sorted[k] = v
        #print 'Lank %5d : %d (%d)' % (i, k, v)

    ###############################################################################
    # draw axis
    #
    if draw_axes:
        axesActor = vtk.vtkAxesActor()

    ###############################################################################
    # prepare rendering
    #
    ren = vtk.vtkRenderer()
    ren.SetBackground(0.0, 0.0, 0.0)

    if draw_axes:
        ren.AddActor(axesActor)

    for seg in segs_actor:
        ren.AddActor(seg)

    renWin = vtk.vtkRenderWindow()
    if offscreen:
        renWin.SetOffScreenRendering(True)
    renWin.AddRenderer(ren)
    renWin.SetWindowName('Mouse Brain Viewer 2 + (%s)' % screen_name)
    renWin.SetSize(1600, 1600)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)
    iren.Initialize()

    renWin.Render()
    '''
    get_screenshot(renWin, screen_name + '_1.png')
    for trans in transforms:
        trans.RotateWXYZ(90., 0, 1, 0)
    for trans_filter in transforms_filter:
        trans_filter.Update()
    renWin.Render()
    get_screenshot(renWin, screen_name + '_2.png')

    for trans in transforms:
        trans.RotateWXYZ(90., 0, 1, 0)
    for trans_filter in transforms_filter:
        trans_filter.Update()
    renWin.Render()
    get_screenshot(renWin, screen_name + '_3.png')
    '''

    iren.Start()

def get_screenshot(renWin, filename):
    w2if = vtk.vtkWindowToImageFilter()
    w2if.SetInput(renWin)
    w2if.Update()
    writer = vtk.vtkPNGWriter()
    writer.SetFileName(filename)
    writer.SetInput(w2if.GetOutput())
    writer.Write()
    renWin.Render()

if __name__ == '__main__':
    argvs = sys.argv
    argc = len(argvs)
    filename = ''

    if(argc >= 2):
        filename = argvs[1]
    else:
        filename = '../matching_area/result.txt'

    if(argc >= 3):
        color_mode = int(argvs[2])
    else:
        color_mode = 1

    if(argc >= 4):
        gene_name = argvs[3]
    else:
        gene_name = 'GENE_NAME'

    print '************ %s ************' % gene_name
    draw_scene(filename, color_mode, gene_name)
<commit_msg>change vtk file pos<commit_after>import vtk
import matplotlib.cm as cm
import sys

LABEL_NAMES = [\
'olfactory bulb',
'cerebral cortex',
'lateral septal nuclei',
'striatum',
'globus pallidus',
'thalamus',
'hypothalamus',
'hippocampal formation',
'superior colliculus',
'inferior colliculus',
'cerebellum',
'fimbria',
'internal capsule',
'ventricle',
'ventricle',
'corpus callosum',
'subcommissural organ',
'anterior commissure',
'paraflocculus',
'deep mesencephalic nucleus',
'fornix',
'aqueaduct',
'pineal gland',
'substantia nigra',
'brainstem (remainder)',
'pontine gray',
'fasciculus retroflexus',
'amygdala',
'interpeduncular nucleus',
'periacueductal gray',
'nucleus accumbens',
'optic chiasm',
'supraoptic decussation',
'optic tract',
'lateral lemniscus',
'epithalamus',
'mammillary nucleus',
'cochlear nuclei and nerve'
]

def read_intensity_data(filename):
    int_data = {}
    fp = open(filename, 'r')
    lines = fp.readlines()
    for line in lines:
        splited = line.strip().split(',')
        int_data[int(splited[0])] = float(splited[1])

    return int_data

def draw_scene(int_filename, color_mode=0, screen_name=None):
    ###############################################################################
    # read polydata file
    #
    offscreen = False
    draw_axes = False

    segs = []
    segs_mapper = []
    segs_actor = []
    transforms = []
    transforms_filter = []

    seg_fileformat = '/mnt/data1/bah2015/seg2/seg%05d.vtk'
    #seg_fileformat = '/media/nebula/data/bah/vtk/seg%05d.vtk'
    #int_filename = '../matching_area/result.txt'

    int_data = read_intensity_data(int_filename)
    int_sum = sum(int_data)
    int_data_sorted = {}

    transform = vtk.vtkTransform()
    transform.RotateWXYZ(90, 0, 1, 0)
    transformFilter = vtk.vtkTransformPolyDataFilter()
    transformFilter.SetTransform(transform)
    transformFilter

    for i in range(1, 39):
        segs.append(vtk.vtkPolyDataReader())
        segs[-1].SetFileName(seg_fileformat % i)

        transforms.append(vtk.vtkTransform())
        #transforms[-1].RotateWXYZ(90., 0, 1, 0)
        transforms_filter.append(vtk.vtkTransformPolyDataFilter())
        transforms_filter[-1].SetTransform(transforms[-1])
        transforms_filter[-1].SetInputConnection(segs[-1].GetOutputPort())
        transforms_filter[-1].Update()

        segs_mapper.append(vtk.vtkPolyDataMapper())
        #segs_mapper[-1].SetInputConnection(segs[-1].GetOutputPort())
        segs_mapper[-1].SetInputConnection(transforms_filter[-1].GetOutputPort())
        segs_actor.append(vtk.vtkActor())
        segs_actor[-1].SetMapper(segs_mapper[-1])
        segs_actor[-1].GetProperty().SetOpacity(0.1)
        #color = cm.jet(i/39.)
        #segs_actor[-1].GetProperty().SetColor(color[0], color[1], color[2])

    i = 0
    for k, v in sorted(int_data.items(), key=lambda x:x[1], reverse=True):
        if i < 9:
            segs_actor[k-1].GetProperty().SetOpacity(0.8)
            if color_mode == 0:
                color = ((v-40) / 20.)
                segs_actor[k-1].GetProperty().SetColor(color, 0, 0)
            elif color_mode == 1:
                color = cm.jet( (v-float(int_sum/40)) / float(int_sum) * 10.)
                segs_actor[k-1].GetProperty().SetColor(color[0], color[1], color[2])

            print ' Rank %d : %s (%d) = %d' % (i+1, LABEL_NAMES[k-1], k, v)
            #print color
            i += 1
            #int_data_sorted[k] = v
        #print 'Lank %5d : %d (%d)' % (i, k, v)

    ###############################################################################
    # draw axis
    #
    if draw_axes:
        axesActor = vtk.vtkAxesActor()

    ###############################################################################
    # prepare rendering
    #
    ren = vtk.vtkRenderer()
    ren.SetBackground(0.0, 0.0, 0.0)

    if draw_axes:
        ren.AddActor(axesActor)

    for seg in segs_actor:
        ren.AddActor(seg)

    renWin = vtk.vtkRenderWindow()
    if offscreen:
        renWin.SetOffScreenRendering(True)
    renWin.AddRenderer(ren)
    renWin.SetWindowName('Mouse Brain Viewer 2 + (%s)' % screen_name)
    renWin.SetSize(1600, 1600)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)
    iren.Initialize()

    renWin.Render()
    '''
    get_screenshot(renWin, screen_name + '_1.png')
    for trans in transforms:
        trans.RotateWXYZ(90., 0, 1, 0)
    for trans_filter in transforms_filter:
        trans_filter.Update()
    renWin.Render()
    get_screenshot(renWin, screen_name + '_2.png')

    for trans in transforms:
        trans.RotateWXYZ(90., 0, 1, 0)
    for trans_filter in transforms_filter:
        trans_filter.Update()
    renWin.Render()
    get_screenshot(renWin, screen_name + '_3.png')
    '''

    iren.Start()

def get_screenshot(renWin, filename):
    w2if = vtk.vtkWindowToImageFilter()
    w2if.SetInput(renWin)
    w2if.Update()
    writer = vtk.vtkPNGWriter()
    writer.SetFileName(filename)
    writer.SetInput(w2if.GetOutput())
    writer.Write()
    renWin.Render()

if __name__ == '__main__':
    argvs = sys.argv
    argc = len(argvs)
    filename = ''

    if(argc >= 2):
        filename = argvs[1]
    else:
        filename = '../matching_area/result.txt'

    if(argc >= 3):
        color_mode = int(argvs[2])
    else:
        color_mode = 1

    if(argc >= 4):
        gene_name = argvs[3]
    else:
        gene_name = 'GENE_NAME'

    print '************ %s ************' % gene_name
    draw_scene(filename, color_mode, gene_name)
<|endoftext|>


<commit_before># This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.

from __future__ import unicode_literals

from io import BytesIO

from flask import session, request, jsonify
from pytz import timezone
from sqlalchemy.orm import load_only, noload, joinedload
from werkzeug.exceptions import Forbidden

from indico.modules.events.contributions.models.contributions import Contribution
from indico.modules.events.contributions.models.persons import ContributionPersonLink, AuthorType
from indico.modules.events.contributions.models.subcontributions import SubContribution
from indico.modules.events.contributions.util import (get_contributions_with_user_as_submitter,
                                                      serialize_contribution_for_ical, ContributionDisplayReporter)
from indico.modules.events.contributions.views import WPMyContributions, WPContributions
from indico.modules.events.layout.util import is_menu_entry_enabled
from indico.modules.events.util import get_base_ical_parameters
from indico.modules.events.views import WPEventDisplay
from indico.web.flask.util import send_file, jsonify_data
from indico.web.http_api.metadata.serializer import Serializer
from MaKaC.common.timezoneUtils import DisplayTZ
from MaKaC.PDFinterface.conference import ContribToPDF, ContribsToPDF
from MaKaC.webinterface.rh.base import RH
from MaKaC.webinterface.rh.conferenceDisplay import RHConferenceBaseDisplay

class RHContributionDisplayBase(RHConferenceBaseDisplay):
    CSRF_ENABLED = True

    normalize_url_spec = {
        'locators': {
            lambda self: self.contrib
        }
    }

    def _checkProtection(self):
        RHConferenceBaseDisplay._checkProtection(self)
        if not self.contrib.can_access(session.user):
            raise Forbidden

    def _checkParams(self, params):
        RHConferenceBaseDisplay._checkParams(self, params)
        self.contrib = Contribution.get_one(request.view_args['contrib_id'], is_deleted=False)

class RHDisplayProtectionBase(RHConferenceBaseDisplay):
    def _checkProtection(self):
        RHConferenceBaseDisplay._checkProtection(self)
        if not is_menu_entry_enabled(self.MENU_ENTRY_NAME, self.event_new):
            raise Forbidden

class RHMyContributions(RHDisplayProtectionBase):
    """Display list of current user contributions"""

    MENU_ENTRY_NAME = 'my_contributions'

    def _process(self):
        contributions = get_contributions_with_user_as_submitter(self.event_new, session.user)
        return WPMyContributions.render_template('display/user_contribution_list.html', self._conf,
                                                 event=self.event_new, contributions=contributions)

class RHContributionList(RHDisplayProtectionBase):
    """Display list of event contributions"""

    MENU_ENTRY_NAME = 'contributions'

    def _checkParams(self, params):
        RHConferenceBaseDisplay._checkParams(self, params)
        self.contribs = self.event_new.contributions
        self.reporter = ContributionDisplayReporter(event=self.event_new)

    def _process(self):
        tz = timezone(DisplayTZ(session.user, self._conf).getDisplayTZ())
        return WPContributions.render_template('display/contribution_list.html', self._conf, event=self.event_new,
                                               timezone=tz, **self.reporter.get_contrib_report_kwargs())

class RHContributionDisplay(RHContributionDisplayBase):
    """Display page with contribution details """

    def _process(self):
        ical_params = get_base_ical_parameters(session.user, self.event_new, 'contributions')
        return WPContributions.render_template('display/contribution_display.html', self._conf,
                                               contribution=self.contrib, event=self.event_new, **ical_params)

class RHContributionAuthor(RHContributionDisplayBase):
    """Display info about an author"""

    normalize_url_spec = {
        'locators': {
            lambda self: self.author
        }
    }

    def _checkProtection(self):
        RHContributionDisplayBase._checkProtection(self)
        if not is_menu_entry_enabled('author_index', self.event_new):
            raise Forbidden

    def _checkParams(self, params):
        RHContributionDisplayBase._checkParams(self, params)
        self.author = (ContributionPersonLink.find_one(ContributionPersonLink.author_type != AuthorType.none,
                                                       id=request.view_args['person_id'],
                                                       contribution=self.contrib))

    def _process(self):
        author_contribs = (Contribution.query.with_parent(self.event_new)
                           .join(ContributionPersonLink)
                           .options(noload('*'))
                           .options(joinedload('event_new'))
                           .options(load_only('id', 'title'))
                           .filter(ContributionPersonLink.id == self.author.id,
                                   ContributionPersonLink.author_type != AuthorType.none)
                           .all())
        return WPEventDisplay.render_template('person_display.html', self._conf,
                                              author=self.author, contribs=author_contribs)

class RHContributionExportToPDF(RHContributionDisplayBase):
    def _process(self):
        pdf = ContribToPDF(self.contrib)
        return send_file('contribution.pdf', pdf.generate(), 'application/pdf')

class RHContributionsExportToPDF(RHContributionList):
    def _process(self):
        contribs = self.reporter.get_contrib_report_kwargs()['contribs']
        pdf = ContribsToPDF(self._conf, contribs)
        return send_file('contributions.pdf', pdf.generate(), 'application/pdf')

class RHContributionExportToICAL(RHContributionDisplayBase):
    """Export contribution to ICS"""

    def _process(self):
        data = {'results': serialize_contribution_for_ical(self.contrib)}
        serializer = Serializer.create('ics')
        return send_file('contribution.ics', BytesIO(serializer(data)), 'text/calendar')

class RHContributionReport(RHContributionList):
    """Display dialog with filters"""

    def _process(self):
        return RH._process(self)

    def _process_GET(self):
        return WPContributions.render_template('contrib_report_filter.html', self._conf, event=self.event_new,
                                               filters=self.reporter.report_config['filters'],
                                               filterable_items=self.reporter.filterable_items)

    def _process_POST(self):
        self.reporter.store_filters()
        return jsonify_data(**self.reporter.render_contribution_list())

class RHContributionListStaticURL(RHContributionList):
    """Generate static URL for the current set of filters"""

    def _process(self):
        return jsonify(url=self.reporter.generate_static_url())

class RHSubcontributionDisplay(RHConferenceBaseDisplay):
    normalize_url_spec = {
        'locators': {
            lambda self: self.subcontrib
        }
    }

    def _checkProtection(self):
        RHConferenceBaseDisplay._checkProtection(self)
        if not self.subcontrib.can_access(session.user):
            raise Forbidden

    def _checkParams(self, params):
        RHConferenceBaseDisplay._checkParams(self, params)
        self.subcontrib = SubContribution.get_one(request.view_args['subcontrib_id'], is_deleted=False)

    def _process(self):
        return WPContributions.render_template('display/subcontribution_display.html', self._conf, event=self.event_new,
                                               subcontrib=self.subcontrib)
<commit_msg>Show warning message to admins in disabled pages<commit_after># This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.

from __future__ import unicode_literals

from io import BytesIO

from flask import flash, session, request, jsonify
from pytz import timezone
from sqlalchemy.orm import load_only, noload, joinedload
from werkzeug.exceptions import Forbidden

from indico.modules.events.contributions.models.contributions import Contribution
from indico.modules.events.contributions.models.persons import ContributionPersonLink, AuthorType
from indico.modules.events.contributions.models.subcontributions import SubContribution
from indico.modules.events.contributions.util import (get_contributions_with_user_as_submitter,
                                                      serialize_contribution_for_ical, ContributionDisplayReporter)
from indico.modules.events.contributions.views import WPMyContributions, WPContributions
from indico.modules.events.layout.util import is_menu_entry_enabled
from indico.modules.events.util import get_base_ical_parameters
from indico.modules.events.views import WPEventDisplay
from indico.util.i18n import _
from indico.web.flask.util import send_file, jsonify_data
from indico.web.http_api.metadata.serializer import Serializer
from MaKaC.common.timezoneUtils import DisplayTZ
from MaKaC.PDFinterface.conference import ContribToPDF, ContribsToPDF
from MaKaC.webinterface.rh.base import RH
from MaKaC.webinterface.rh.conferenceDisplay import RHConferenceBaseDisplay

class RHContributionDisplayBase(RHConferenceBaseDisplay):
    CSRF_ENABLED = True

    normalize_url_spec = {
        'locators': {
            lambda self: self.contrib
        }
    }

    def _checkProtection(self):
        RHConferenceBaseDisplay._checkProtection(self)
        if not self.contrib.can_access(session.user):
            raise Forbidden

    def _checkParams(self, params):
        RHConferenceBaseDisplay._checkParams(self, params)
        self.contrib = Contribution.get_one(request.view_args['contrib_id'], is_deleted=False)

class RHDisplayProtectionBase(RHConferenceBaseDisplay):
    def _checkProtection(self):
        RHConferenceBaseDisplay._checkProtection(self)
        if not is_menu_entry_enabled(self.MENU_ENTRY_NAME, self.event_new):
            if session.user and session.user.is_admin:
                flash(_('This page is currently not visible by non-admin users (menu entry disabled)!'), 'warning')
            else:
                raise Forbidden

class RHMyContributions(RHDisplayProtectionBase):
    """Display list of current user contributions"""

    MENU_ENTRY_NAME = 'my_contributions'

    def _process(self):
        contributions = get_contributions_with_user_as_submitter(self.event_new, session.user)
        return WPMyContributions.render_template('display/user_contribution_list.html', self._conf,
                                                 event=self.event_new, contributions=contributions)

class RHContributionList(RHDisplayProtectionBase):
    """Display list of event contributions"""

    MENU_ENTRY_NAME = 'contributions'

    def _checkParams(self, params):
        RHConferenceBaseDisplay._checkParams(self, params)
        self.contribs = self.event_new.contributions
        self.reporter = ContributionDisplayReporter(event=self.event_new)

    def _process(self):
        tz = timezone(DisplayTZ(session.user, self._conf).getDisplayTZ())
        return WPContributions.render_template('display/contribution_list.html', self._conf, event=self.event_new,
                                               timezone=tz, **self.reporter.get_contrib_report_kwargs())

class RHContributionDisplay(RHContributionDisplayBase):
    """Display page with contribution details """

    def _process(self):
        ical_params = get_base_ical_parameters(session.user, self.event_new, 'contributions')
        return WPContributions.render_template('display/contribution_display.html', self._conf,
                                               contribution=self.contrib, event=self.event_new, **ical_params)

class RHContributionAuthor(RHContributionDisplayBase):
    """Display info about an author"""

    normalize_url_spec = {
        'locators': {
            lambda self: self.author
        }
    }

    def _checkProtection(self):
        RHContributionDisplayBase._checkProtection(self)
        if not is_menu_entry_enabled('author_index', self.event_new):
            raise Forbidden

    def _checkParams(self, params):
        RHContributionDisplayBase._checkParams(self, params)
        self.author = (ContributionPersonLink.find_one(ContributionPersonLink.author_type != AuthorType.none,
                                                       id=request.view_args['person_id'],
                                                       contribution=self.contrib))

    def _process(self):
        author_contribs = (Contribution.query.with_parent(self.event_new)
                           .join(ContributionPersonLink)
                           .options(noload('*'))
                           .options(joinedload('event_new'))
                           .options(load_only('id', 'title'))
                           .filter(ContributionPersonLink.id == self.author.id,
                                   ContributionPersonLink.author_type != AuthorType.none)
                           .all())
        return WPEventDisplay.render_template('person_display.html', self._conf,
                                              author=self.author, contribs=author_contribs)

class RHContributionExportToPDF(RHContributionDisplayBase):
    def _process(self):
        pdf = ContribToPDF(self.contrib)
        return send_file('contribution.pdf', pdf.generate(), 'application/pdf')

class RHContributionsExportToPDF(RHContributionList):
    def _process(self):
        contribs = self.reporter.get_contrib_report_kwargs()['contribs']
        pdf = ContribsToPDF(self._conf, contribs)
        return send_file('contributions.pdf', pdf.generate(), 'application/pdf')

class RHContributionExportToICAL(RHContributionDisplayBase):
    """Export contribution to ICS"""

    def _process(self):
        data = {'results': serialize_contribution_for_ical(self.contrib)}
        serializer = Serializer.create('ics')
        return send_file('contribution.ics', BytesIO(serializer(data)), 'text/calendar')

class RHContributionReport(RHContributionList):
    """Display dialog with filters"""

    def _process(self):
        return RH._process(self)

    def _process_GET(self):
        return WPContributions.render_template('contrib_report_filter.html', self._conf, event=self.event_new,
                                               filters=self.reporter.report_config['filters'],
                                               filterable_items=self.reporter.filterable_items)

    def _process_POST(self):
        self.reporter.store_filters()
        return jsonify_data(**self.reporter.render_contribution_list())

class RHContributionListStaticURL(RHContributionList):
    """Generate static URL for the current set of filters"""

    def _process(self):
        return jsonify(url=self.reporter.generate_static_url())

class RHSubcontributionDisplay(RHConferenceBaseDisplay):
    normalize_url_spec = {
        'locators': {
            lambda self: self.subcontrib
        }
    }

    def _checkProtection(self):
        RHConferenceBaseDisplay._checkProtection(self)
        if not self.subcontrib.can_access(session.user):
            raise Forbidden

    def _checkParams(self, params):
        RHConferenceBaseDisplay._checkParams(self, params)
        self.subcontrib = SubContribution.get_one(request.view_args['subcontrib_id'], is_deleted=False)

    def _process(self):
        return WPContributions.render_template('display/subcontribution_display.html', self._conf, event=self.event_new,
                                               subcontrib=self.subcontrib)
<|endoftext|>


<commit_before>#!/usr/bin/python
# A server that uses TextChecker.py to check text for style
# and grammar errors
# Copyright (C) 2003 Daniel Naber <daniel.naber@t-online.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or (at
# your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA

import TextChecker
import config

import ConfigParser
import os
import re
import socket
import sys
import time

sys.path.append(os.path.join(config.BASEDIR, "snakespell-1.01"))
from scriptfoundry.snakespell import iSpell

server_name = "127.0.0.1"
server_port = 50100

def makeChecker(grammar_cfg=None, falsefriends_cfg=None, words_cfg=None, \
		builtin_cfg=None, textlanguage=None, mothertongue=None, \
		max_sentence_length=None):
	"""Create a new TextChecker object and return it."""
	checker = TextChecker.TextChecker(grammar_cfg, falsefriends_cfg, words_cfg, \
		builtin_cfg, textlanguage, mothertongue, max_sentence_length)
	return checker

def loadOptionList(config, enable_name, option_name):
	val = None
	if config.has_option("General", enable_name) and \
		config.getboolean("General", enable_name):
		if config.has_option("General", option_name):
			val = re.split(',', config.get("General", option_name))
	else:
		val = ["NONE"]
	return val

def loadOptionBoolean(config, option_name):
	if config.has_option("General", option_name) and config.getboolean("General", option_name):
		return 1
	return None

def loadOptionString(config, option_name, default):
	val = default
	if config.has_option("General", option_name):
		val = config.get("General", option_name)
	return val

def readConfig():
	"""Read the checker config from a KDE config file (INI style).
	Return a checker which uses that config."""
	config = ConfigParser.ConfigParser()
	filename = os.path.join(os.getenv('HOME'), ".kde/share/config/languagetool")
	config.readfp(open(filename))
	grammar = loadOptionList(config, "EnableGrammar", "GrammarRules")
	falsefriends = loadOptionList(config, "EnableFalseFriends", "FalseFriendsRules")
	words = loadOptionList(config, "EnableWords", "WordsRules")
	builtin = []
	if loadOptionBoolean(config, "EnableArticleCheck"):
		builtin.append("DET")
	if loadOptionBoolean(config, "EnableWhitespaceCheck"):
		builtin.append("WHITESPACE")
	if len(builtin) == 0:
		builtin = None
	textlanguage = loadOptionString(config, "TextLanguage", "en")
	mothertongue = loadOptionString(config, "MotherTongue", "en")
	sentence_length = 0
	if loadOptionBoolean(config, "EnableSentenceLength"):
		if config.has_option("General", "MaxSentenceLength"):
			sentence_length = config.getint("General", "MaxSentenceLength")
	checker = makeChecker(grammar, falsefriends, words, builtin, \
		textlanguage, mothertongue, sentence_length)
	return checker

def getConfig(data):
	"""Get a new config in pseudo XML format from the client.
	It needs to be at the beginning of the string that comes
	from the client and must be of form <config ... />.
	Returns a tuple with the a checker based on this config and
	the 'data' string with the config section removed."""
	print "Receiving new config..."
	line_end_pos = data.find("/>")
	cfg_str = data[:line_end_pos]
	data = data[line_end_pos+3:]
	grammar = getConfigValue(cfg_str, "grammar")
	falsefriends = getConfigValue(cfg_str, "falsefriends")
	words = getConfigValue(cfg_str, "words")
	builtin = getConfigValue(cfg_str, "builtin")
	textlanguage = getConfigValue(cfg_str, "textlanguage")
	if textlanguage:
		textlanguage = textlanguage[0]
	mothertongue = getConfigValue(cfg_str, "mothertongue")
	if mothertongue:
		mothertongue = mothertongue[0]
	sentence_length = getConfigValue(cfg_str, "max-sentence-length")
	if not sentence_length:
		sentence_length = 0
	else:
		sentence_length = int(sentence_length[0])
	checker = makeChecker(grammar, falsefriends, words, builtin, \
		textlanguage, mothertongue, sentence_length)
	return (checker, data)

def getConfigValue(cfg_str, val):
	m = re.compile('%s="(.*?)"' % val).search(cfg_str)
	if not m:
		return None
	s = m.group(1)
	l = re.split(',', s)
	return l

def main():
	print "Binding to '%s:%d'..." % (server_name, server_port)
	s.bind((server_name, server_port))
	print "Listening..."
	s.listen(1)
	print "Setting up Checker..."
	checker = readConfig()
	print "Ready..."
	while 1:
		conn, addr = s.accept()
		if addr[0] != "127.0.0.1":		# security
			print "Connection by '%s' refused" % addr[0]
			conn.close()
			continue
		else:
			print "Connected by '%s'" % addr[0]

		l = []
		limit = 1024
		while 1:
			data = conn.recv(limit)
			l.append(data)
			#FIXME: need to look for separator, not just < limit!
			if not data or len(data) < limit:
				break
		data = str.join('', l)

		print "Received '%s'" % data
		if data.find("<config") != -1:
			del checker
			(checker, data) = getConfig(data)
			print "New config activated"
		t1 = time.time()
		check_result = checkWords(checker, data)
		t2 = time.time()-t1
		print "Replying (%.2fs) '%s'" % (t2, check_result.encode('utf8'))
		#print "Replying (%.2fs)" % t2
		conn.send(check_result.encode('utf8'))

		conn.close()
	s.close()
	return

def checkWordsTEST(words):
	"""Just for testing. Marks 'working' as incorrect."""
	words = re.split("\s+", words)
	s = '<result>'
	for w in words:
		if w == "working":
			s = s + '\t<error word="working" pos="5" corrections="Bohlen,Didda"/>'
	s = s + '</result>'
	return s

def checkWords(checker, words):
	result = u'<result>'

	### Spelling:
	ispell = iSpell()
	words = words.replace("\n", " ")		# iSpell works line by line
	r = ispell.check(words)
	if r > 0:
		# fixme: escape word
		for mistake in ispell.getMistakes():
			# TODO: make faster
			pos = []
			for p in mistake.getPositions():
				result = u'%s<error from="%d" to="%d" word="%s" corrections="%s"/>' % \
					(result, p, p+len(mistake.getWord()), \
					unicode(mistake.getWord(), 'latin1'), \
					unicode(str.join(',', mistake.corrections), ('latin1')))

	### Grammar + Style:
	(rule_matches, res, tags) = checker.check(words)
	# FIXME: only if there's no overlap?!
	result = result + res

	result = result + '</result>\n'
	return result

try:
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	os.chdir(config.BASEDIR)
	main()
except KeyboardInterrupt:
	# TODO: close explicitely, unfortunately we still get an
	# 'Address already in use' error if we restart immediately:
	s.shutdown(2)
	s.close()
	print "Stopped."
<commit_msg>avoid BASEDIR<commit_after>#!/usr/bin/python
# A server that uses TextChecker.py to check text for style
# and grammar errors
# Copyright (C) 2003 Daniel Naber <daniel.naber@t-online.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or (at
# your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA

import TextChecker

import ConfigParser
import os
import re
import socket
import sys
import time

sys.path.append(os.path.join(sys.path[0], "snakespell-1.01"))
from scriptfoundry.snakespell import iSpell

server_name = "127.0.0.1"
server_port = 50100
configfile = os.path.join(os.getenv('HOME'), ".kde/share/config/languagetool")

def makeChecker(grammar_cfg=None, falsefriends_cfg=None, words_cfg=None, \
		builtin_cfg=None, textlanguage=None, mothertongue=None, \
		max_sentence_length=None):
	"""Create a new TextChecker object and return it."""
	checker = TextChecker.TextChecker(grammar_cfg, falsefriends_cfg, words_cfg, \
		builtin_cfg, textlanguage, mothertongue, max_sentence_length)
	return checker

def loadOptionList(config, enable_name, option_name):
	val = None
	if config.has_option("General", enable_name) and \
		config.getboolean("General", enable_name):
		if config.has_option("General", option_name):
			val = re.split(',', config.get("General", option_name))
	else:
		val = ["NONE"]
	return val

def loadOptionBoolean(config, option_name):
	if config.has_option("General", option_name) and config.getboolean("General", option_name):
		return 1
	return None

def loadOptionString(config, option_name, default):
	val = default
	if config.has_option("General", option_name):
		val = config.get("General", option_name)
	return val

def readConfig():
	"""Read the checker config from a KDE config file (INI style).
	Return a checker which uses that config."""
	config = ConfigParser.ConfigParser()
	try:
		config.readfp(open(configfile))
	except IOError:
		print "Couldn't load config file '%s', using defaults..." % configfile
	grammar = loadOptionList(config, "EnableGrammar", "GrammarRules")
	falsefriends = loadOptionList(config, "EnableFalseFriends", "FalseFriendsRules")
	words = loadOptionList(config, "EnableWords", "WordsRules")
	builtin = []
	if loadOptionBoolean(config, "EnableArticleCheck"):
		builtin.append("DET")
	if loadOptionBoolean(config, "EnableWhitespaceCheck"):
		builtin.append("WHITESPACE")
	if len(builtin) == 0:
		builtin = None
	textlanguage = loadOptionString(config, "TextLanguage", "en")
	mothertongue = loadOptionString(config, "MotherTongue", "en")
	sentence_length = 0
	if loadOptionBoolean(config, "EnableSentenceLength"):
		if config.has_option("General", "MaxSentenceLength"):
			sentence_length = config.getint("General", "MaxSentenceLength")
	checker = makeChecker(grammar, falsefriends, words, builtin, \
		textlanguage, mothertongue, sentence_length)
	return checker

def getConfig(data):
	"""Get a new config in pseudo XML format from the client.
	It needs to be at the beginning of the string that comes
	from the client and must be of form <config ... />.
	Returns a tuple with the a checker based on this config and
	the 'data' string with the config section removed."""
	print "Receiving new config..."
	line_end_pos = data.find("/>")
	cfg_str = data[:line_end_pos]
	data = data[line_end_pos+3:]
	grammar = getConfigValue(cfg_str, "grammar")
	falsefriends = getConfigValue(cfg_str, "falsefriends")
	words = getConfigValue(cfg_str, "words")
	builtin = getConfigValue(cfg_str, "builtin")
	textlanguage = getConfigValue(cfg_str, "textlanguage")
	if textlanguage:
		textlanguage = textlanguage[0]
	mothertongue = getConfigValue(cfg_str, "mothertongue")
	if mothertongue:
		mothertongue = mothertongue[0]
	sentence_length = getConfigValue(cfg_str, "max-sentence-length")
	if not sentence_length:
		sentence_length = 0
	else:
		sentence_length = int(sentence_length[0])
	checker = makeChecker(grammar, falsefriends, words, builtin, \
		textlanguage, mothertongue, sentence_length)
	return (checker, data)

def getConfigValue(cfg_str, val):
	m = re.compile('%s="(.*?)"' % val).search(cfg_str)
	if not m:
		return None
	s = m.group(1)
	l = re.split(',', s)
	return l

def main():
	print "Binding to '%s:%d'..." % (server_name, server_port)
	s.bind((server_name, server_port))
	print "Listening..."
	s.listen(1)
	print "Setting up Checker..."
	checker = readConfig()
	print "Ready..."
	while 1:
		conn, addr = s.accept()
		if addr[0] != "127.0.0.1":		# security
			print "Connection by '%s' refused" % addr[0]
			conn.close()
			continue
		else:
			print "Connected by '%s'" % addr[0]

		l = []
		limit = 1024
		while 1:
			data = conn.recv(limit)
			l.append(data)
			#FIXME: need to look for separator, not just < limit!
			if not data or len(data) < limit:
				break
		data = str.join('', l)

		print "Received '%s'" % data
		if data.find("<config") != -1:
			del checker
			(checker, data) = getConfig(data)
			print "New config activated"
		t1 = time.time()
		check_result = checkWords(checker, data)
		t2 = time.time()-t1
		print "Replying (%.2fs) '%s'" % (t2, check_result.encode('utf8'))
		#print "Replying (%.2fs)" % t2
		conn.send(check_result.encode('utf8'))

		conn.close()
	s.close()
	return

def checkWordsTEST(words):
	"""Just for testing. Marks 'working' as incorrect."""
	words = re.split("\s+", words)
	s = '<result>'
	for w in words:
		if w == "working":
			s = s + '\t<error word="working" pos="5" corrections="Bohlen,Didda"/>'
	s = s + '</result>'
	return s

def checkWords(checker, words):
	result = u'<result>'

	### Spelling:
	ispell = iSpell()
	words = words.replace("\n", " ")		# iSpell works line by line
	r = ispell.check(words)
	if r > 0:
		# fixme: escape word
		for mistake in ispell.getMistakes():
			# TODO: make faster
			pos = []
			for p in mistake.getPositions():
				result = u'%s<error from="%d" to="%d" word="%s" corrections="%s"/>' % \
					(result, p, p+len(mistake.getWord()), \
					unicode(mistake.getWord(), 'latin1'), \
					unicode(str.join(',', mistake.corrections), ('latin1')))

	### Grammar + Style:
	(rule_matches, res, tags) = checker.check(words)
	# FIXME: only if there's no overlap?!
	result = result + res

	result = result + '</result>\n'
	return result

try:
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	os.chdir(sys.path[0])
	main()
except KeyboardInterrupt:
	# TODO: close explicitely, unfortunately we still get an
	# 'Address already in use' error if we restart immediately:
	s.shutdown(2)
	s.close()
	print "Stopped."
<|endoftext|>


<commit_before>import unittest

import odml.types as typ
import odml
import datetime

class TestTypes(unittest.TestCase):
    def test_date(self):
        date = datetime.date(2011, 12, 1)
        date_string = '2011-12-01'
        self.assertEqual(date, typ.date_get(date_string))
        self.assertEqual(typ.date_set(date), date_string)

    def test_time(self):
        time = datetime.time(12,34,56)
        time_string = '12:34:56'
        self.assertEqual(time, typ.time_get(time_string))
        self.assertEqual(typ.time_set(time), time_string)

    def test_datetime(self):
        date = datetime.datetime(2011, 12, 1, 12, 34, 56)
        date_string = '2011-12-01 12:34:56'
        self.assertEqual(date, typ.datetime_get(date_string))
        self.assertEqual(typ.datetime_set(date), date_string)

    def test_empty_binary(self):
        v = odml.Value("", dtype="string")
        v.dtype = "binary"
        v.encoding = "base64"
        self.assertIsNone(v.value)
        v.encoding = "quoted-printable"
        self.assertIsNone(v.value)
        v.encoding = "hexadecimal"
        self.assertIsNone(v.value)
        self.assertEqual(v.checksum, 'crc32$00000000')
        v.checksum = "md5"
        self.assertEqual(v.checksum, 'md5$d41d8cd98f00b204e9800998ecf8427e')

    def test_8bit_binary(self):
        data = ''.join([chr(i) for i in xrange(256)])
        v = odml.Value(data, dtype="binary")

        v.encoder = "base64"
        b64_data = 'AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w==\n'
        self.assertEqual(v.value, b64_data)
        v.value = b64_data
        self.assertEqual(v.data, data)
        self.assertEqual(v.value, b64_data)

        v.encoder = "quoted-printable"
        qp_data = '=00=01=02=03=04=05=06=07=08=09\n=0B=0C\r=0E=0F=10=11=12=13=14=15=16=17=18=19=1A=1B=1C=1D=1E=1F !"#$%&\'()*+,-=\n./0123456789:;<=3D>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuv=\nwxyz{|}~=7F=80=81=82=83=84=85=86=87=88=89=8A=8B=8C=8D=8E=8F=90=91=92=93=94=\n=95=96=97=98=99=9A=9B=9C=9D=9E=9F=A0=A1=A2=A3=A4=A5=A6=A7=A8=A9=AA=AB=AC=AD=\n=AE=AF=B0=B1=B2=B3=B4=B5=B6=B7=B8=B9=BA=BB=BC=BD=BE=BF=C0=C1=C2=C3=C4=C5=C6=\n=C7=C8=C9=CA=CB=CC=CD=CE=CF=D0=D1=D2=D3=D4=D5=D6=D7=D8=D9=DA=DB=DC=DD=DE=DF=\n=E0=E1=E2=E3=E4=E5=E6=E7=E8=E9=EA=EB=EC=ED=EE=EF=F0=F1=F2=F3=F4=F5=F6=F7=F8=\n=F9=FA=FB=FC=FD=FE=FF'
        self.assertEqual(v.value, qp_data)
        v.value = qp_data
        self.assertEqual(v.data, data)
        self.assertEqual(v.value, qp_data)

        v.encoder = "hexadecimal"
        hex_data = '000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff'
        self.assertEqual(v.value, hex_data)
        v.value = hex_data
        self.assertEqual(v.data, data)
        self.assertEqual(v.value, hex_data)

        self.assertEqual(v.checksum, 'crc32$29058c73')
        v.checksum = "md5"
        self.assertEqual(v.checksum, 'md5$e2c865db4162bed963bfaa9ef6ac18f0')
        v.encoder = ''
        v.data = v.data[:127] # chrs > 128 cannot be converted to ascii
        v.dtype = "string"
        self.assertIsNone(v.encoder)
        self.assertIsNone(v.checksum)
        self.assertEqual(v.value, data[:127])

    def test_int(self):
        v = odml.Value("123456789012345678901", dtype="int")
        self.assertEqual(v.data, 123456789012345678901)
        self.assertEqual(v.value, "123456789012345678901")
        v = odml.Value("-123456789012345678901", dtype="int")
        self.assertEqual(v.data, -123456789012345678901)
        v = odml.Value("123.45", dtype="int")
        self.assertEqual(v.data, 123)

if __name__ == '__main__':
    unittest.main()
<commit_msg>test.types: fix base64 encoder test (don't have newline anymore)<commit_after>import unittest

import odml.types as typ
import odml
import datetime

class TestTypes(unittest.TestCase):
    def test_date(self):
        date = datetime.date(2011, 12, 1)
        date_string = '2011-12-01'
        self.assertEqual(date, typ.date_get(date_string))
        self.assertEqual(typ.date_set(date), date_string)

    def test_time(self):
        time = datetime.time(12,34,56)
        time_string = '12:34:56'
        self.assertEqual(time, typ.time_get(time_string))
        self.assertEqual(typ.time_set(time), time_string)

    def test_datetime(self):
        date = datetime.datetime(2011, 12, 1, 12, 34, 56)
        date_string = '2011-12-01 12:34:56'
        self.assertEqual(date, typ.datetime_get(date_string))
        self.assertEqual(typ.datetime_set(date), date_string)

    def test_empty_binary(self):
        v = odml.Value("", dtype="string")
        v.dtype = "binary"
        v.encoding = "base64"
        self.assertIsNone(v.value)
        v.encoding = "quoted-printable"
        self.assertIsNone(v.value)
        v.encoding = "hexadecimal"
        self.assertIsNone(v.value)
        self.assertEqual(v.checksum, 'crc32$00000000')
        v.checksum = "md5"
        self.assertEqual(v.checksum, 'md5$d41d8cd98f00b204e9800998ecf8427e')

    def test_8bit_binary(self):
        data = ''.join([chr(i) for i in xrange(256)])
        v = odml.Value(data, dtype="binary")

        v.encoder = "base64"
        b64_data = 'AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w=='
        self.assertEqual(v.value, b64_data)
        v.value = b64_data
        self.assertEqual(v.data, data)
        self.assertEqual(v.value, b64_data)

        v.encoder = "quoted-printable"
        qp_data = '=00=01=02=03=04=05=06=07=08=09\n=0B=0C\r=0E=0F=10=11=12=13=14=15=16=17=18=19=1A=1B=1C=1D=1E=1F !"#$%&\'()*+,-=\n./0123456789:;<=3D>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuv=\nwxyz{|}~=7F=80=81=82=83=84=85=86=87=88=89=8A=8B=8C=8D=8E=8F=90=91=92=93=94=\n=95=96=97=98=99=9A=9B=9C=9D=9E=9F=A0=A1=A2=A3=A4=A5=A6=A7=A8=A9=AA=AB=AC=AD=\n=AE=AF=B0=B1=B2=B3=B4=B5=B6=B7=B8=B9=BA=BB=BC=BD=BE=BF=C0=C1=C2=C3=C4=C5=C6=\n=C7=C8=C9=CA=CB=CC=CD=CE=CF=D0=D1=D2=D3=D4=D5=D6=D7=D8=D9=DA=DB=DC=DD=DE=DF=\n=E0=E1=E2=E3=E4=E5=E6=E7=E8=E9=EA=EB=EC=ED=EE=EF=F0=F1=F2=F3=F4=F5=F6=F7=F8=\n=F9=FA=FB=FC=FD=FE=FF'
        self.assertEqual(v.value, qp_data)
        v.value = qp_data
        self.assertEqual(v.data, data)
        self.assertEqual(v.value, qp_data)

        v.encoder = "hexadecimal"
        hex_data = '000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff'
        self.assertEqual(v.value, hex_data)
        v.value = hex_data
        self.assertEqual(v.data, data)
        self.assertEqual(v.value, hex_data)

        self.assertEqual(v.checksum, 'crc32$29058c73')
        v.checksum = "md5"
        self.assertEqual(v.checksum, 'md5$e2c865db4162bed963bfaa9ef6ac18f0')
        v.encoder = ''
        v.data = v.data[:127] # chrs > 128 cannot be converted to ascii
        v.dtype = "string"
        self.assertIsNone(v.encoder)
        self.assertIsNone(v.checksum)
        self.assertEqual(v.value, data[:127])

    def test_int(self):
        v = odml.Value("123456789012345678901", dtype="int")
        self.assertEqual(v.data, 123456789012345678901)
        self.assertEqual(v.value, "123456789012345678901")
        v = odml.Value("-123456789012345678901", dtype="int")
        self.assertEqual(v.data, -123456789012345678901)
        v = odml.Value("123.45", dtype="int")
        self.assertEqual(v.data, 123)

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


<commit_before>#!/usr/bin/python3
#A Python script to set the theme for GTK+ 2 and GTK+ 3 applications in minimal environments
#This shouldn't overwrite existing ~/.gtkrc-2.0 or ~/.config/gtk-3.0/settings.ini files - instead
#it will try to update them in place.
#By Charles Bos

from tkinter import *
from tkinter import messagebox
import os

def findThemes(themeType) :
    homeDir = os.path.expanduser('~')
    a = os.listdir("/usr/share/themes")
    for x in a : a[a.index(x)] = "/usr/share/themes/" + x
    if os.path.exists("/usr/local/share/themes") :
        b = os.listdir("/usr/local/share/themes")
        for x in b : b[b.index(x)] = "/usr/local/share/themes/" + x
    else : b = []
    if os.path.exists(homeDir + "/.themes") :
        c = os.listdir(homeDir + "/.themes")
        for x in c : c[c.index(x)] = homeDir + "/.themes/" + x
    else : c = []
    allThemes = a + b + c
    final = []

    for x in allThemes :
        dirs = os.listdir(x)
        y = x.split("/")
        if themeType == "gtk2" :
            if "gtk-2.0" in (dirs) :
                gDir = os.listdir(x + "/gtk-2.0")
                if "gtkrc" in gDir : final.append(y[-1])
        else :
            if "gtk-3.0" in (dirs) :
                gDir = os.listdir(x + "/gtk-3.0")
                if "gtk.css" in gDir : final.append(y[-1])
    #Add default themes to list
    if "Adwaita" not in final : final.append("Adwaita")
    if "Raleigh" not in final : final.append("Raleigh")

    return sorted(final)

def findIcons(themeType) :
    homeDir = os.path.expanduser('~')
    a = os.listdir("/usr/share/icons")
    for x in a : a[a.index(x)] = "/usr/share/icons/" + x
    if os.path.exists("/usr/local/share/icons") :
        b = os.listdir("/usr/local/share/icons")
        for x in b : b[b.index(x)] = "/usr/local/share/icons/" + x
    else : b = []
    if os.path.exists(homeDir + "/.icons") :
        c = os.listdir(homeDir + "/.icons")
        for x in c : c[c.index(x)] = homeDir + "/.icons/" + x
    else : c = []
    allIcons = a + b + c
    final = []

    for x in allIcons :
        dirs = os.listdir(x)
        y = x.split("/")
        #Dir needs to contain index.theme and might well contain cursors dir. Therefore, the
        #number of items within dir needs to be greater than 2 for it to contain a viable icon
        #theme. For cursor theme, we only need the cursor dir.
        if "index.theme" in dirs :
            if themeType == "cursors" :
                if "cursors" in dirs : final.append(y[-1])
            else :
                if len(dirs) > 2 : final.append(y[-1])
    #Remove hicolor and default
    if "hicolor" in final : final.remove("hicolor")
    if "default" in final : final.remove("default")

    return sorted(final)

def getResource(sFile, resource) :
    if resource == "gtk-button-images" or resource == "gtk-menu-images" : default = 0
    else : default = "None set"
    homeDir = os.path.expanduser('~')
    try :
        if sFile == "gtk2" : file = open(homeDir + "/.gtkrc-2.0", "r")
        elif sFile == "gtk3" : file = open(homeDir + "/.config/gtk-3.0/settings.ini", "r")
        elif sFile == "xdg_cursor" : file = open(homeDir + "/.icons/default/index.theme", "r")
        contents = file.read()
        file.close()
        contents = contents.split("\n")
        for x in contents :
            y = x.split("=")
            if y[0].strip() == resource : return y[-1].strip().strip('"')
        return default
    except IOError :
        return default

def setResource(sFile, resource, var) :
    homeDir = os.path.expanduser('~')
    if sFile == "gtk2" : path = homeDir + "/.gtkrc-2.0"
    elif sFile == "gtk3" : path = homeDir + "/.config/gtk-3.0/settings.ini"
    elif sFile == "xdg_cursor" : path = homeDir + "/.icons/default/index.theme"
    if os.path.exists(path) :
        #If file exists, read it and try to get find resource name line
        #If found, update it
        found = False
        file = open(path, "r")
        contents = file.read()
        file.close()
        contents = contents.split("\n")
        contents = [x for x in contents if x != ""]
        for x in contents :
            y = x.split("=")
            if y[0].strip() == resource :
                if y[0][-1] == " " :
                    if sFile == "gtk2" and var.get() != "1" and var.get() != "0" : z = str(resource + " = " + '"' + var.get() + '"')
                    else : z = str(resource + " = " + var.get())
                else :
                    if sFile == "gtk2" and var.get() != "1" and var.get() != "0" : z = str(resource + "=" + '"' + var.get() + '"')
                    else : z = str(resource + "=" + var.get())
                contents[contents.index(x)] = z
                found = True
                break

        if found :
            #If file exists and resource is present, update it
            file = open(path, "w")
            for x in contents :
                if contents.index(x) == len(contents) -1 : file.write(x)
                else : file.write(x + "\n")
        elif not found and contents != [] :
            #If file exists and is full but resource is not present, append it
            file = open(path, "w")
            for x in contents :
                if contents.index(x) == len(contents) -1 : file.write(x)
                else : file.write(x + "\n")
            if sFile == "gtk2" : file.write("\n" + resource + " = " + '"' + var.get() + '"')
            elif sFile == "gtk3" : file.write("\n" + resource + " = " + var.get())
            elif sFile == "xdg_cursor" : file.write("\n" + resource + "=" + var.get())
        else :
            #If file exists but is empty, overwrite it
            file = open(path, "w")
            if sFile == "gtk2" : file.write(resource + " = " + '"' + var.get() + '"')
            elif sFile == "gtk3" : file.write("[Settings]\n" + resource + " = " + var.get())
            elif sFile == "xdg_cursor" : file.write("[Icon Theme]\n" + resource + "=" + var.get())
        file.close()
    else :
        #If file does not exist, create it
        if sFile == "gtk3" :
            try : os.makedirs(homeDir + "/.config/gtk-3.0/")
            except FileExistsError : pass
        elif sFile == "xdg_cursor" :
            try : os.makedirs(homeDir + "/.icons/default/")
            except FileExistsError : pass
        file = open(path, "w")
        if sFile == "gtk2" : file.write(resource + " = " + '"' + var.get() + '"')
        elif sFile == "gtk3" : file.write("[Settings]\n" + resource + " = " + var.get())
        elif sFile == "xdg_cursor" : file.write("[Icon Theme]\n" + resource + "=" + var.get())
        file.close()

def endOnNewline(filePath) :
    if os.path.exists(filePath) :
        file = open(filePath, "r")
        contents = file.read()
        file.close()
        if len(contents) > 0 :
            if contents[-1] != '\n' :
                file = open(filePath, "a")
                file.write('\n')
                file.close()

def update(rVars) :
    changes = False

    #Update GTK+ 2 theme
    if  rVars[0].get() != getResource("gtk2", "gtk-theme-name") :
        setResource("gtk2", "gtk-theme-name", rVars[0])
        changes = True

    #Update GTK+ 3 theme
    if  rVars[1].get() != getResource("gtk3", "gtk-theme-name") :
        setResource("gtk3", "gtk-theme-name", rVars[1])
        changes = True

    #Update GTK+ 2 and GTK+ 3 font
    if  rVars[2].get() != getResource("gtk2", "gtk-font-name") :
        setResource("gtk2", "gtk-font-name", rVars[2])
        setResource("gtk3", "gtk-font-name", rVars[2])
        changes = True

    #Update GTK+ 2 and GTK+ 3 icons
    if  rVars[3].get() != getResource("gtk2", "gtk-icon-theme-name") :
        setResource("gtk2", "gtk-icon-theme-name", rVars[3])
        setResource("gtk3", "gtk-icon-theme-name", rVars[3])
        changes = True

    #Update GTK+ 2, GTK+ 3 and XDG cursor theme
    if  rVars[4].get() != getResource("xdg_cursor", "Inherits") :
        setResource("xdg_cursor", "Inherits", rVars[4])
        setResource("gtk2", "gtk-cursor-theme-name", rVars[4])
        setResource("gtk3", "gtk-cursor-theme-name", rVars[4])
        changes = True

    #Update images in GTK+ menus and buttons
    if  rVars[5].get() != bool(int(getResource("gtk2", "gtk-button-images"))) :
        temp = StringVar()
        temp.set(str(int(rVars[5].get())))
        setResource("gtk2", "gtk-button-images", temp)
        setResource("gtk3", "gtk-button-images", temp)
        changes = True
    if  rVars[6].get() != bool(int(getResource("gtk2", "gtk-menu-images"))) :
        temp = StringVar()
        temp.set(str(int(rVars[6].get())))
        setResource("gtk2", "gtk-menu-images", temp)
        setResource("gtk3", "gtk-menu-images", temp)
        changes = True

    #Ensure that the last char in all files is a newline
    homeDir = os.path.expanduser('~')
    endOnNewline(homeDir + "/.gtkrc-2.0")
    endOnNewline(homeDir + "/.config/gtk-3.0/settings.ini")
    endOnNewline(homeDir + "/.icons/default/index.theme")

    #Show completion message
    if changes : messagebox.showinfo(title = "Complete!", message = "Restart your applications for the settings to take effect.")
    else : messagebox.showinfo(title = "Complete!", message = "Settings files were already up to date. No changes were made.")

class UI() :
    def __init__(self, parent) :
        parent.title("Set GTK+ theme")
        l1 = Label(parent, text = "Set the theme for GTK+ 2 and 3 applications", pady = 5, padx = 5, relief = RAISED)
        l1.grid(row = 1, column = 1, columnspan = 2)

        #List of resource vars. Positions format is as follows:
        #0 = GTK+ 2 theme, 1 = GTK+ 3 theme, 2 = Font, 3 = Icons, 4 = Cursors, 5 = Button images, 6 = Menu images
        rVars = []

        #GTK+ 2 section
        l2 = Label(parent, text = "GTK+ 2 app theme:", pady = 7, padx = 5).grid(row = 2, column = 1, sticky = W)
        varOpG2 = StringVar(parent)
        rVars.append(varOpG2)
        varOpG2.set(getResource("gtk2", "gtk-theme-name"))
        themesG2 = findThemes("gtk2")
        m1 = OptionMenu(parent, varOpG2, *themesG2).grid(row = 2, column = 2, sticky = W)

        #GTK+ 3 section
        l3 = Label(parent, text = "GTK+ 3 app theme:", pady = 7, padx = 5).grid(row = 3, column = 1, sticky = W)
        varOpG3 = StringVar(parent)
        rVars.append(varOpG3)
        varOpG3.set(getResource("gtk3", "gtk-theme-name"))
        themesG3 = findThemes("gtk3")
        m2 = OptionMenu(parent, varOpG3, *themesG3).grid(row = 3, column = 2, sticky = W)

        #Hereafter, we're not supporting seperate settings for GTK+ 2 and GTK+ 3.
        #For displaying the current setting, we only check the GTK+ 2 settings file.

        #Font section
        l4 = Label(parent, text = "GTK+ font:", pady = 7, padx = 5).grid(row = 4, column = 1, sticky = W)
        fontField = Entry(parent)
        rVars.append(fontField)
        fontField.grid(row = 4, column = 2, sticky = W)
        fontField.insert(0, getResource("gtk2", "gtk-font-name"))

        #Icons section
        l5 = Label(parent, text = "GTK+ icons:", pady = 7, padx = 5).grid(row = 5, column = 1, sticky = W)
        varOpIcons = StringVar(parent)
        rVars.append(varOpIcons)
        varOpIcons.set(getResource("gtk2", "gtk-icon-theme-name"))
        icons = findIcons("icons")
        m3 = OptionMenu(parent, varOpIcons, *icons).grid(row = 5, column = 2, sticky = W)

        #Cursors section
        l6 = Label(parent, text = "GTK+ cursors:", pady = 7, padx = 5).grid(row = 6, column = 1, sticky = W)
        varOpCursors = StringVar(parent)
        rVars.append(varOpCursors)
        varOpCursors.set(getResource("xdg_cursor", "Inherits"))
        cursors = findIcons("cursors")
        m4 = OptionMenu(parent, varOpCursors, *cursors).grid(row = 6, column = 2, sticky = W)

        #Button and menu images section
        varOpButtonImages = BooleanVar(parent)
        varOpMenuImages = BooleanVar(parent)
        rVars.append(varOpButtonImages)
        rVars.append(varOpMenuImages)
        varOpButtonImages.set(getResource("gtk2", "gtk-button-images"))
        varOpMenuImages.set(getResource("gtk2", "gtk-menu-images"))
        imgMenuButton = Checkbutton(parent, variable = varOpButtonImages, text = "Images in buttons").grid(row = 7, column = 1, sticky = W)
        imgMenuButton = Checkbutton(parent, variable = varOpMenuImages, text = "Images in menus").grid(row = 7, column = 2, sticky = W)

        #Buttons
        b1 = Button(parent, text = "Close", padx = 5, pady = 5, bd = 3, command = parent.destroy).grid(row = 8, column = 1)
        b2 = Button(parent, text = "Update", padx = 5, pady = 5, bd = 3, command = lambda : update(rVars)).grid(row = 8, column = 2)

top = Tk()
ui = UI(top)
top.mainloop()
<commit_msg>setgtktheme.py - remove unneeded lines from info at top<commit_after>#!/usr/bin/python3
#A Python script to set the theme for GTK+ 2 and GTK+ 3 applications in minimal environments
#By Charles Bos

from tkinter import *
from tkinter import messagebox
import os

def findThemes(themeType) :
    homeDir = os.path.expanduser('~')
    a = os.listdir("/usr/share/themes")
    for x in a : a[a.index(x)] = "/usr/share/themes/" + x
    if os.path.exists("/usr/local/share/themes") :
        b = os.listdir("/usr/local/share/themes")
        for x in b : b[b.index(x)] = "/usr/local/share/themes/" + x
    else : b = []
    if os.path.exists(homeDir + "/.themes") :
        c = os.listdir(homeDir + "/.themes")
        for x in c : c[c.index(x)] = homeDir + "/.themes/" + x
    else : c = []
    allThemes = a + b + c
    final = []

    for x in allThemes :
        dirs = os.listdir(x)
        y = x.split("/")
        if themeType == "gtk2" :
            if "gtk-2.0" in (dirs) :
                gDir = os.listdir(x + "/gtk-2.0")
                if "gtkrc" in gDir : final.append(y[-1])
        else :
            if "gtk-3.0" in (dirs) :
                gDir = os.listdir(x + "/gtk-3.0")
                if "gtk.css" in gDir : final.append(y[-1])
    #Add default themes to list
    if "Adwaita" not in final : final.append("Adwaita")
    if "Raleigh" not in final : final.append("Raleigh")

    return sorted(final)

def findIcons(themeType) :
    homeDir = os.path.expanduser('~')
    a = os.listdir("/usr/share/icons")
    for x in a : a[a.index(x)] = "/usr/share/icons/" + x
    if os.path.exists("/usr/local/share/icons") :
        b = os.listdir("/usr/local/share/icons")
        for x in b : b[b.index(x)] = "/usr/local/share/icons/" + x
    else : b = []
    if os.path.exists(homeDir + "/.icons") :
        c = os.listdir(homeDir + "/.icons")
        for x in c : c[c.index(x)] = homeDir + "/.icons/" + x
    else : c = []
    allIcons = a + b + c
    final = []

    for x in allIcons :
        dirs = os.listdir(x)
        y = x.split("/")
        #Dir needs to contain index.theme and might well contain cursors dir. Therefore, the
        #number of items within dir needs to be greater than 2 for it to contain a viable icon
        #theme. For cursor theme, we only need the cursor dir.
        if "index.theme" in dirs :
            if themeType == "cursors" :
                if "cursors" in dirs : final.append(y[-1])
            else :
                if len(dirs) > 2 : final.append(y[-1])
    #Remove hicolor and default
    if "hicolor" in final : final.remove("hicolor")
    if "default" in final : final.remove("default")

    return sorted(final)

def getResource(sFile, resource) :
    if resource == "gtk-button-images" or resource == "gtk-menu-images" : default = 0
    else : default = "None set"
    homeDir = os.path.expanduser('~')
    try :
        if sFile == "gtk2" : file = open(homeDir + "/.gtkrc-2.0", "r")
        elif sFile == "gtk3" : file = open(homeDir + "/.config/gtk-3.0/settings.ini", "r")
        elif sFile == "xdg_cursor" : file = open(homeDir + "/.icons/default/index.theme", "r")
        contents = file.read()
        file.close()
        contents = contents.split("\n")
        for x in contents :
            y = x.split("=")
            if y[0].strip() == resource : return y[-1].strip().strip('"')
        return default
    except IOError :
        return default

def setResource(sFile, resource, var) :
    homeDir = os.path.expanduser('~')
    if sFile == "gtk2" : path = homeDir + "/.gtkrc-2.0"
    elif sFile == "gtk3" : path = homeDir + "/.config/gtk-3.0/settings.ini"
    elif sFile == "xdg_cursor" : path = homeDir + "/.icons/default/index.theme"
    if os.path.exists(path) :
        #If file exists, read it and try to get find resource name line
        #If found, update it
        found = False
        file = open(path, "r")
        contents = file.read()
        file.close()
        contents = contents.split("\n")
        contents = [x for x in contents if x != ""]
        for x in contents :
            y = x.split("=")
            if y[0].strip() == resource :
                if y[0][-1] == " " :
                    if sFile == "gtk2" and var.get() != "1" and var.get() != "0" : z = str(resource + " = " + '"' + var.get() + '"')
                    else : z = str(resource + " = " + var.get())
                else :
                    if sFile == "gtk2" and var.get() != "1" and var.get() != "0" : z = str(resource + "=" + '"' + var.get() + '"')
                    else : z = str(resource + "=" + var.get())
                contents[contents.index(x)] = z
                found = True
                break

        if found :
            #If file exists and resource is present, update it
            file = open(path, "w")
            for x in contents :
                if contents.index(x) == len(contents) -1 : file.write(x)
                else : file.write(x + "\n")
        elif not found and contents != [] :
            #If file exists and is full but resource is not present, append it
            file = open(path, "w")
            for x in contents :
                if contents.index(x) == len(contents) -1 : file.write(x)
                else : file.write(x + "\n")
            if sFile == "gtk2" : file.write("\n" + resource + " = " + '"' + var.get() + '"')
            elif sFile == "gtk3" : file.write("\n" + resource + " = " + var.get())
            elif sFile == "xdg_cursor" : file.write("\n" + resource + "=" + var.get())
        else :
            #If file exists but is empty, overwrite it
            file = open(path, "w")
            if sFile == "gtk2" : file.write(resource + " = " + '"' + var.get() + '"')
            elif sFile == "gtk3" : file.write("[Settings]\n" + resource + " = " + var.get())
            elif sFile == "xdg_cursor" : file.write("[Icon Theme]\n" + resource + "=" + var.get())
        file.close()
    else :
        #If file does not exist, create it
        if sFile == "gtk3" :
            try : os.makedirs(homeDir + "/.config/gtk-3.0/")
            except FileExistsError : pass
        elif sFile == "xdg_cursor" :
            try : os.makedirs(homeDir + "/.icons/default/")
            except FileExistsError : pass
        file = open(path, "w")
        if sFile == "gtk2" : file.write(resource + " = " + '"' + var.get() + '"')
        elif sFile == "gtk3" : file.write("[Settings]\n" + resource + " = " + var.get())
        elif sFile == "xdg_cursor" : file.write("[Icon Theme]\n" + resource + "=" + var.get())
        file.close()

def endOnNewline(filePath) :
    if os.path.exists(filePath) :
        file = open(filePath, "r")
        contents = file.read()
        file.close()
        if len(contents) > 0 :
            if contents[-1] != '\n' :
                file = open(filePath, "a")
                file.write('\n')
                file.close()

def update(rVars) :
    changes = False

    #Update GTK+ 2 theme
    if  rVars[0].get() != getResource("gtk2", "gtk-theme-name") :
        setResource("gtk2", "gtk-theme-name", rVars[0])
        changes = True

    #Update GTK+ 3 theme
    if  rVars[1].get() != getResource("gtk3", "gtk-theme-name") :
        setResource("gtk3", "gtk-theme-name", rVars[1])
        changes = True

    #Update GTK+ 2 and GTK+ 3 font
    if  rVars[2].get() != getResource("gtk2", "gtk-font-name") :
        setResource("gtk2", "gtk-font-name", rVars[2])
        setResource("gtk3", "gtk-font-name", rVars[2])
        changes = True

    #Update GTK+ 2 and GTK+ 3 icons
    if  rVars[3].get() != getResource("gtk2", "gtk-icon-theme-name") :
        setResource("gtk2", "gtk-icon-theme-name", rVars[3])
        setResource("gtk3", "gtk-icon-theme-name", rVars[3])
        changes = True

    #Update GTK+ 2, GTK+ 3 and XDG cursor theme
    if  rVars[4].get() != getResource("xdg_cursor", "Inherits") :
        setResource("xdg_cursor", "Inherits", rVars[4])
        setResource("gtk2", "gtk-cursor-theme-name", rVars[4])
        setResource("gtk3", "gtk-cursor-theme-name", rVars[4])
        changes = True

    #Update images in GTK+ menus and buttons
    if  rVars[5].get() != bool(int(getResource("gtk2", "gtk-button-images"))) :
        temp = StringVar()
        temp.set(str(int(rVars[5].get())))
        setResource("gtk2", "gtk-button-images", temp)
        setResource("gtk3", "gtk-button-images", temp)
        changes = True
    if  rVars[6].get() != bool(int(getResource("gtk2", "gtk-menu-images"))) :
        temp = StringVar()
        temp.set(str(int(rVars[6].get())))
        setResource("gtk2", "gtk-menu-images", temp)
        setResource("gtk3", "gtk-menu-images", temp)
        changes = True

    #Ensure that the last char in all files is a newline
    homeDir = os.path.expanduser('~')
    endOnNewline(homeDir + "/.gtkrc-2.0")
    endOnNewline(homeDir + "/.config/gtk-3.0/settings.ini")
    endOnNewline(homeDir + "/.icons/default/index.theme")

    #Show completion message
    if changes : messagebox.showinfo(title = "Complete!", message = "Restart your applications for the settings to take effect.")
    else : messagebox.showinfo(title = "Complete!", message = "Settings files were already up to date. No changes were made.")

class UI() :
    def __init__(self, parent) :
        parent.title("Set GTK+ theme")
        l1 = Label(parent, text = "Set the theme for GTK+ 2 and 3 applications", pady = 5, padx = 5, relief = RAISED)
        l1.grid(row = 1, column = 1, columnspan = 2)

        #List of resource vars. Positions format is as follows:
        #0 = GTK+ 2 theme, 1 = GTK+ 3 theme, 2 = Font, 3 = Icons, 4 = Cursors, 5 = Button images, 6 = Menu images
        rVars = []

        #GTK+ 2 section
        l2 = Label(parent, text = "GTK+ 2 app theme:", pady = 7, padx = 5).grid(row = 2, column = 1, sticky = W)
        varOpG2 = StringVar(parent)
        rVars.append(varOpG2)
        varOpG2.set(getResource("gtk2", "gtk-theme-name"))
        themesG2 = findThemes("gtk2")
        m1 = OptionMenu(parent, varOpG2, *themesG2).grid(row = 2, column = 2, sticky = W)

        #GTK+ 3 section
        l3 = Label(parent, text = "GTK+ 3 app theme:", pady = 7, padx = 5).grid(row = 3, column = 1, sticky = W)
        varOpG3 = StringVar(parent)
        rVars.append(varOpG3)
        varOpG3.set(getResource("gtk3", "gtk-theme-name"))
        themesG3 = findThemes("gtk3")
        m2 = OptionMenu(parent, varOpG3, *themesG3).grid(row = 3, column = 2, sticky = W)

        #Hereafter, we're not supporting seperate settings for GTK+ 2 and GTK+ 3.
        #For displaying the current setting, we only check the GTK+ 2 settings file.

        #Font section
        l4 = Label(parent, text = "GTK+ font:", pady = 7, padx = 5).grid(row = 4, column = 1, sticky = W)
        fontField = Entry(parent)
        rVars.append(fontField)
        fontField.grid(row = 4, column = 2, sticky = W)
        fontField.insert(0, getResource("gtk2", "gtk-font-name"))

        #Icons section
        l5 = Label(parent, text = "GTK+ icons:", pady = 7, padx = 5).grid(row = 5, column = 1, sticky = W)
        varOpIcons = StringVar(parent)
        rVars.append(varOpIcons)
        varOpIcons.set(getResource("gtk2", "gtk-icon-theme-name"))
        icons = findIcons("icons")
        m3 = OptionMenu(parent, varOpIcons, *icons).grid(row = 5, column = 2, sticky = W)

        #Cursors section
        l6 = Label(parent, text = "GTK+ cursors:", pady = 7, padx = 5).grid(row = 6, column = 1, sticky = W)
        varOpCursors = StringVar(parent)
        rVars.append(varOpCursors)
        varOpCursors.set(getResource("xdg_cursor", "Inherits"))
        cursors = findIcons("cursors")
        m4 = OptionMenu(parent, varOpCursors, *cursors).grid(row = 6, column = 2, sticky = W)

        #Button and menu images section
        varOpButtonImages = BooleanVar(parent)
        varOpMenuImages = BooleanVar(parent)
        rVars.append(varOpButtonImages)
        rVars.append(varOpMenuImages)
        varOpButtonImages.set(getResource("gtk2", "gtk-button-images"))
        varOpMenuImages.set(getResource("gtk2", "gtk-menu-images"))
        imgMenuButton = Checkbutton(parent, variable = varOpButtonImages, text = "Images in buttons").grid(row = 7, column = 1, sticky = W)
        imgMenuButton = Checkbutton(parent, variable = varOpMenuImages, text = "Images in menus").grid(row = 7, column = 2, sticky = W)

        #Buttons
        b1 = Button(parent, text = "Close", padx = 5, pady = 5, bd = 3, command = parent.destroy).grid(row = 8, column = 1)
        b2 = Button(parent, text = "Update", padx = 5, pady = 5, bd = 3, command = lambda : update(rVars)).grid(row = 8, column = 2)

top = Tk()
ui = UI(top)
top.mainloop()
<|endoftext|>


<commit_before>'''Text progress bar library for Python.

A text progress bar is typically used to display the progress of a long
running operation, providing a visual cue that processing is underway.

The ProgressBar class manages the current progress, and the format of the line
is given by a number of widgets. A widget is an object that may display
differently depending on the state of the progress bar.

The progressbar module is very easy to use, yet very powerful. It will also
automatically enable features like auto-resizing when the system supports it.
'''

__title__ = 'Python Progressbar'
__package_name__ = 'progressbar2'
__author__ = 'Rick van Hattem (Wolph)'
__description__ = ' '.join('''
A Python Progressbar library to provide visual (yet text based) progress to
long running operations.
'''.strip().split())
__email__ = 'wolph@wol.ph'
__version__ = '3.55.0'
__license__ = 'BSD'
__copyright__ = 'Copyright 2015 Rick van Hattem (Wolph)'
__url__ = 'https://github.com/WoLpH/python-progressbar'
<commit_msg>Incrementing version to v4.0.0<commit_after>'''Text progress bar library for Python.

A text progress bar is typically used to display the progress of a long
running operation, providing a visual cue that processing is underway.

The ProgressBar class manages the current progress, and the format of the line
is given by a number of widgets. A widget is an object that may display
differently depending on the state of the progress bar.

The progressbar module is very easy to use, yet very powerful. It will also
automatically enable features like auto-resizing when the system supports it.
'''

__title__ = 'Python Progressbar'
__package_name__ = 'progressbar2'
__author__ = 'Rick van Hattem (Wolph)'
__description__ = ' '.join('''
A Python Progressbar library to provide visual (yet text based) progress to
long running operations.
'''.strip().split())
__email__ = 'wolph@wol.ph'
__version__ = '4.0.0'
__license__ = 'BSD'
__copyright__ = 'Copyright 2015 Rick van Hattem (Wolph)'
__url__ = 'https://github.com/WoLpH/python-progressbar'
<|endoftext|>