<commit_before># -*- coding: utf-8 -*-
"""
================
Global variables
================

"""
from cea.demand import thermal_loads

__author__ = "Jimeno A. Fonseca"
__copyright__ = "Copyright 2015, Architecture and Building Systems - ETH Zurich"
__credits__ = ["Jimeno A. Fonseca", "Daren Thomas"]
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = "Daren Thomas"
__email__ = "thomas@arch.ethz.ch"
__status__ = "Production"

class GlobalVariables(object):
    def __init__(self):
        self.date_start = '1/1/2016' #d/m/yyyy
        self.seasonhours = [3216, 6192]
        self.Z = 3  # height of basement for every building in m
        self.Bf = 0.7  # it calculates the coefficient of reduction in transmittance for surfaces in contact with the ground according to values of SIA 380/1
        self.his = 3.45  # heat transfer coefficient between air and the surfacein W/(m2K)
        self.hms = 9.1  # heat transfer coefficient between nodes m and s in W/m2K
        self.g_gl = 0.9 * 0.75  # solar energy transmittance assuming a reduction factor of 0.9 and most of the windows due to double glazing (0.75)
        self.F_f = 0.3  # Frame area faction coefficient
        self.D = 20  # in mm the diameter of the pipe to calculate losses
        self.hf = 3  # average height per floor in m
        self.Pwater = 998  # water density kg/m3
        self.PaCa = 1200  # Air constant J/m3K
        self.Cpw = 4.184  # heat capacity of water in kJ/kgK
        self.Flowtap = 0.036  # in m3/min == 12 l/min during 3 min every tap opening
        # constant values for HVAC
        self.nrec_N = 0.75  # possilbe recovery
        self.NACH_inf_non_occ = 0.2  # num air exchanges due to infiltration when no occupied
        self.NACH_inf_occ = 0.5  # num air exchanges due to infiltration when occupied
        self.C1 = 0.054  # assumed a flat plate heat exchanger (-)
        self.Vmax = 3  # maximum estimated flow in m3/s
        self.Pair = 1.2  # air density in kg/m3
        self.Cpv = 1.859  # specific heat capacity of water vapor in KJ/kgK
        self.Cpa = 1.008  # specific heat capacity of air in KJ/kgK
        self.U_dhwtank = 0.225  # tank insulation heat transfer coefficient in W/m2-K, value taken from SIA 385
        self.AR = 3.3  # tank height aspect ratio, H=(4*V*AR^2/pi)^(1/3), taken from commercial tank geometry (jenni.ch)
        self.lvapor = 2257  # latent heat of air kJ/kg
        self.Tww_setpoint = 60  # dhw tank set point temperature in C
        # constant variables for pumping operation
        self.hoursop = 5  # assuming around 2000 hours of operation per year. It is charged to the electrical system from 11 am to 4 pm
        self.gr = 9.81  # m/s2 gravity
        self.effi = 0.6  # efficiency of pumps
        self.deltaP_l = 0.1  # delta of pressure
        self.fsr = 0.3  # factor for pressure calculation
        # grey emssions
        self.fwratio = 1.5  # conversion component's area to floor area
        self.sl_materials = 60  # service life of standard building components and materials
        self.sl_services = 40  # service life of technical instalations
        # constant variables for air conditioning fan
        self.Pfan = 0.55 # specific fan consumption in W/m3/h

        # ==============================================================================================================
        # ventilation
        # ==============================================================================================================
        self.shielding_class = 2  # according to ISO 16798-7, 0 = open terrain, 1 = partly shielded from wind,
        #  2 = fully shielded from wind
        self.delta_p_dim = 5  # (Pa) dimensioning differential pressure for multi-storey building shielded from wind,
        # according to DIN 1946-6

        # ==============================================================================================================
        # HVAC
        # ==============================================================================================================
        self.temp_sup_heat_hvac = 36  # (°C)
        self.temp_sup_cool_hvac = 16  # (°C)

        # ==============================================================================================================
        # Comfort
        # ==============================================================================================================
        self.temp_comf_max = 26  # (°C) TODO: include to building properties and get from building properties
        self.rhum_comf_max = 70  # (%)

        # ==============================================================================================================
        # Initial temperatures for demand calculation
        # ==============================================================================================================
        self.initial_temp_air_prev = 21
        self.initial_temp_m_prev = 16

        # here is where we plug in the models to use for calculations
        self.models = {'calc-thermal-loads': thermal_loads.calc_thermal_loads}  # functions.CalcThermalLoads

        # use multiprocessing / parallel execution if possible
        self.multiprocessing = True

        # here is where we decide whether full excel reports of the calculations are generated
        self.testing = False  # if true: reports are generated, if false: not

        self.report_variables = {
            'calc-thermal-loads': {
                'Building properties':
                    ['Name',                'Af',                   'Aef',          'sys_e_heating',
                     'sys_e_cooling',       'Occupants',            'Am',           'Atot',
                     'Awall_all',           'Cm',                   'Ll',           'Lw',
                     'Retrofit',            'Sh_typ',               'Year',         'footprint',
                     'nf_ag',               'nfp',                  'Lcww_dis',     'Lsww_dis',
                     'Lv',                  'Lvww_dis',             'Tcs_re_0',     'Tcs_sup_0',
                     'Ths_re_0',            'Ths_sup_0',            'Tww_re_0',     'Tww_sup_0',
                     'Y',                   'fforma'],
                'Thermal loads hourly':
                    ['ta_hs_set',           'ta_cs_set',            'people',       've',
                     'q_int',               'Eal_nove',             'Eprof',        'Edata',
                     'Qcdataf',             'Qcrefrif',             'vww',          'vw',
                     'Qcdata',              'Qcrefri',              'qv_req',       'Hve',
                     'Htr_is',              'Htr_ms',               'Htr_w',        'Htr_em',
                     'Htr_1',               'Htr_2',                'Htr_3',        'I_sol',
                     'I_int_sen',           'w_int',                'I_ia',         'I_m',
                     'I_st',                'uncomfort',            'Ta',           'Tm',
                     'Qhs_sen',             'Qcs_sen',              'Qhs_lat',      'Qcs_lat',
                     'Qhs_em_ls',           'Qcs_em_ls',            'QHC_sen',      'ma_sup_hs',
                     'Ta_sup_hs',           'Ta_re_hs',             'ma_sup_cs',    'Ta_sup_cs',
                     'Ta_re_cs',            'w_sup',                'w_re',         'Ehs_lat_aux',
                     'Qhs_sen_incl_em_ls',  'Qcs_sen_incl_em_ls',   't5',           'Tww_re',
                     'Top',                 'Im_tot',               'tHset_corr',   'tCset_corr',
                     'Tcs_re',              'Tcs_sup','Ths_re',     'Ths_sup',      'mcpcs',
                     'mcphs',               'Mww',                  'Qww',          'Qww_ls_st',
                     'Qwwf',                'Tww_st',               'Vw',           'Vww',
                     'mcpww',               'Eaux_cs',              'Eaux_fw',      'Eaux_ve',
                     'Eaux_ww',             'Eauxf',                'Occupancy',    'Waterconsumption']},
            'other-module-that-needs-logging': {'worksheet1': ['v1', 'v2', 'v3'],
                                                #'worksheet2': [('v4', 'm'), ('v5', 'Mwh'), ('v6', 'MJ')]}}
                                                'worksheet2': ['v4', 'v5', 'v6']}}

    def report(self, template, variables, output_folder, basename):
        """Use vars to fill worksheets in an excel file $destination_template based on the template.
        The template references self.report_variables. The destination_template may contain date format codes that
        will be updated with the current datetime."""
        if self.testing:
            from cea.utilities import reporting
            reporting.full_report_to_xls(template, variables, output_folder, basename, self)

    def log(self, msg, **kwargs):
        print msg % kwargs

    def is_heating_season(self, timestep):

        if self.seasonhours[0]+1 <= timestep < self.seasonhours[1]:
            return False
        else:
            return True
<commit_msg>fixing sollar collector model<commit_after># -*- coding: utf-8 -*-
"""
================
Global variables
================

"""
from cea.demand import thermal_loads

__author__ = "Jimeno A. Fonseca"
__copyright__ = "Copyright 2015, Architecture and Building Systems - ETH Zurich"
__credits__ = ["Jimeno A. Fonseca", "Daren Thomas"]
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = "Daren Thomas"
__email__ = "thomas@arch.ethz.ch"
__status__ = "Production"

class GlobalVariables(object):
    def __init__(self):
        self.date_start = '1/1/2016' #d/m/yyyy
        self.seasonhours = [3216, 6192]
        self.Z = 3  # height of basement for every building in m
        self.Bf = 0.7  # it calculates the coefficient of reduction in transmittance for surfaces in contact with the ground according to values of SIA 380/1
        self.his = 3.45  # heat transfer coefficient between air and the surfacein W/(m2K)
        self.hms = 9.1  # heat transfer coefficient between nodes m and s in W/m2K
        self.g_gl = 0.9 * 0.75  # solar energy transmittance assuming a reduction factor of 0.9 and most of the windows due to double glazing (0.75)
        self.F_f = 0.3  # Frame area faction coefficient
        self.D = 20  # in mm the diameter of the pipe to calculate losses
        self.hf = 3  # average height per floor in m
        self.Pwater = 998  # water density kg/m3
        self.PaCa = 1200  # Air constant J/m3K
        self.Cpw = 4.184  # heat capacity of water in kJ/kgK
        self.Flowtap = 0.036  # in m3/min == 12 l/min during 3 min every tap opening
        # constant values for HVAC
        self.nrec_N = 0.75  # possilbe recovery
        self.NACH_inf_non_occ = 0.2  # num air exchanges due to infiltration when no occupied
        self.NACH_inf_occ = 0.5  # num air exchanges due to infiltration when occupied
        self.C1 = 0.054  # assumed a flat plate heat exchanger (-)
        self.Vmax = 3  # maximum estimated flow in m3/s
        self.Pair = 1.2  # air density in kg/m3
        self.Cpv = 1.859  # specific heat capacity of water vapor in KJ/kgK
        self.Cpa = 1.008  # specific heat capacity of air in KJ/kgK
        self.U_dhwtank = 0.225  # tank insulation heat transfer coefficient in W/m2-K, value taken from SIA 385
        self.AR = 3.3  # tank height aspect ratio, H=(4*V*AR^2/pi)^(1/3), taken from commercial tank geometry (jenni.ch)
        self.lvapor = 2257  # latent heat of air kJ/kg
        self.Tww_setpoint = 60  # dhw tank set point temperature in C
        # constant variables for pumping operation
        self.hoursop = 5  # assuming around 2000 hours of operation per year. It is charged to the electrical system from 11 am to 4 pm
        self.gr = 9.81  # m/s2 gravity
        self.effi = 0.6  # efficiency of pumps
        self.deltaP_l = 0.1  # delta of pressure
        self.fsr = 0.3  # factor for pressure calculation
        # grey emssions
        self.fwratio = 1.5  # conversion component's area to floor area
        self.sl_materials = 60  # service life of standard building components and materials
        self.sl_services = 40  # service life of technical instalations
        # constant variables for air conditioning fan
        self.Pfan = 0.55 # specific fan consumption in W/m3/h

        # ==============================================================================================================
        # solar thermal collector
        # ==============================================================================================================

        self.Tin = 75  # average temeperature
        self.module_lenght = 2  # m # 1 for PV and 2 for solar collectors
        self.min_production = 0.75  # points are selected with at least a minimum production of this % from the maximum in the area.
        self.grid_side = 2  # in a rectangular grid of points, one side of the square. this cannot be changed if the solra potential was made with this.
        self.worst_hour = 8744  # first hour of sun on the solar solstice
        self.angle_north = 122.5
        self.type_SCpanel = 1  # Flatplate collector

        # ==============================================================================================================
        # ventilation
        # ==============================================================================================================
        self.shielding_class = 2  # according to ISO 16798-7, 0 = open terrain, 1 = partly shielded from wind,
        #  2 = fully shielded from wind
        self.delta_p_dim = 5  # (Pa) dimensioning differential pressure for multi-storey building shielded from wind,
        # according to DIN 1946-6

        # ==============================================================================================================
        # HVAC
        # ==============================================================================================================
        self.temp_sup_heat_hvac = 36  # (°C)
        self.temp_sup_cool_hvac = 16  # (°C)

        # ==============================================================================================================
        # Comfort
        # ==============================================================================================================
        self.temp_comf_max = 26  # (°C) TODO: include to building properties and get from building properties
        self.rhum_comf_max = 70  # (%)

        # ==============================================================================================================
        # Initial temperatures for demand calculation
        # ==============================================================================================================
        self.initial_temp_air_prev = 21
        self.initial_temp_m_prev = 16

        # here is where we plug in the models to use for calculations
        self.models = {'calc-thermal-loads': thermal_loads.calc_thermal_loads}  # functions.CalcThermalLoads

        # use multiprocessing / parallel execution if possible
        self.multiprocessing = True

        # here is where we decide whether full excel reports of the calculations are generated
        self.testing = False  # if true: reports are generated, if false: not

        self.report_variables = {
            'calc-thermal-loads': {
                'Building properties':
                    ['Name',                'Af',                   'Aef',          'sys_e_heating',
                     'sys_e_cooling',       'Occupants',            'Am',           'Atot',
                     'Awall_all',           'Cm',                   'Ll',           'Lw',
                     'Retrofit',            'Sh_typ',               'Year',         'footprint',
                     'nf_ag',               'nfp',                  'Lcww_dis',     'Lsww_dis',
                     'Lv',                  'Lvww_dis',             'Tcs_re_0',     'Tcs_sup_0',
                     'Ths_re_0',            'Ths_sup_0',            'Tww_re_0',     'Tww_sup_0',
                     'Y',                   'fforma'],
                'Thermal loads hourly':
                    ['ta_hs_set',           'ta_cs_set',            'people',       've',
                     'q_int',               'Eal_nove',             'Eprof',        'Edata',
                     'Qcdataf',             'Qcrefrif',             'vww',          'vw',
                     'Qcdata',              'Qcrefri',              'qv_req',       'Hve',
                     'Htr_is',              'Htr_ms',               'Htr_w',        'Htr_em',
                     'Htr_1',               'Htr_2',                'Htr_3',        'I_sol',
                     'I_int_sen',           'w_int',                'I_ia',         'I_m',
                     'I_st',                'uncomfort',            'Ta',           'Tm',
                     'Qhs_sen',             'Qcs_sen',              'Qhs_lat',      'Qcs_lat',
                     'Qhs_em_ls',           'Qcs_em_ls',            'QHC_sen',      'ma_sup_hs',
                     'Ta_sup_hs',           'Ta_re_hs',             'ma_sup_cs',    'Ta_sup_cs',
                     'Ta_re_cs',            'w_sup',                'w_re',         'Ehs_lat_aux',
                     'Qhs_sen_incl_em_ls',  'Qcs_sen_incl_em_ls',   't5',           'Tww_re',
                     'Top',                 'Im_tot',               'tHset_corr',   'tCset_corr',
                     'Tcs_re',              'Tcs_sup','Ths_re',     'Ths_sup',      'mcpcs',
                     'mcphs',               'Mww',                  'Qww',          'Qww_ls_st',
                     'Qwwf',                'Tww_st',               'Vw',           'Vww',
                     'mcpww',               'Eaux_cs',              'Eaux_fw',      'Eaux_ve',
                     'Eaux_ww',             'Eauxf',                'Occupancy',    'Waterconsumption']},
            'other-module-that-needs-logging': {'worksheet1': ['v1', 'v2', 'v3'],
                                                #'worksheet2': [('v4', 'm'), ('v5', 'Mwh'), ('v6', 'MJ')]}}
                                                'worksheet2': ['v4', 'v5', 'v6']}}

    def report(self, template, variables, output_folder, basename):
        """Use vars to fill worksheets in an excel file $destination_template based on the template.
        The template references self.report_variables. The destination_template may contain date format codes that
        will be updated with the current datetime."""
        if self.testing:
            from cea.utilities import reporting
            reporting.full_report_to_xls(template, variables, output_folder, basename, self)

    def log(self, msg, **kwargs):
        print msg % kwargs

    def is_heating_season(self, timestep):

        if self.seasonhours[0]+1 <= timestep < self.seasonhours[1]:
            return False
        else:
            return True
<|endoftext|>


<commit_before>import numpy as np
import yaml
from hydromet.disaggregate import monthly_to_daily

def load_model_config(filename):
    with open(filename) as yml_file:
        config = yaml.load(yml_file)

    return config

def get_idx(config, typ):
    if typ == 'all':
        idx = slice()
    elif typ == 'calibration':
        idx = slice(config['calibration']['start_date'], config['calibration']['end_date'])

    return idx

def read_predictors(db, config, station_id, typ = 'all', idx = None):
    if idx is None:
        idx = get_idx(config, typ)
    return __read_predict(db, config['predictors'], station_id, idx)

def read_predictands(db, config, station_id, typ = 'all', idx = None):
    if idx is None:
        idx = get_idx(config, typ)
    return __read_predict(db, config['predictands'], station_id, idx)

def __read_predict(db, config, station_id, idx):
    predicts = {}
    for predict, attrs in config.items():
        predicts[predict] = __resample(db.read(station_id, attrs['source_freq'], **attrs['db_attrs']), attrs['source_freq'], attrs['model_freq']).ix[idx]

    return predicts

def __resample(series, source_freq, model_freq, how = 'sum'):
    if source_freq == model_freq:
        return series
    elif source_freq == 'MS' and model_freq == 'D':
        return monthly_to_daily(series)
    elif source_freq == 'D' and model_freq == 'MS':
        return series.resample(model_freq, how = how)
    else:
        raise NotImplementedError("Source frequency '{0}' can not be converted to model frequency '{1}' at this time.".format(source_freq, model_freq))
<commit_msg>Be more flexible on accepted predictor index types<commit_after>import numpy as np
import yaml
from hydromet.disaggregate import monthly_to_daily

def load_model_config(filename):
    with open(filename) as yml_file:
        config = yaml.load(yml_file)

    return config

def get_idx(config, typ):
    if typ is None:
        idx = slice()
    else:
        idx = slice(config[typ]['start_date'], config[typ]['end_date'])

    return idx

def read_predictors(db, config, station_id, typ = None, idx = None):
    if idx is None:
        idx = get_idx(config, typ)
    return __read_predict(db, config['predictors'], station_id, idx)

def read_predictands(db, config, station_id, typ = None, idx = None):
    if idx is None:
        idx = get_idx(config, typ)
    return __read_predict(db, config['predictands'], station_id, idx)

def __read_predict(db, config, station_id, idx):
    predicts = {}
    for predict, attrs in config.items():
        predicts[predict] = __resample(db.read(station_id, attrs['source_freq'], **attrs['db_attrs']), attrs['source_freq'], attrs['model_freq']).ix[idx]

    return predicts

def __resample(series, source_freq, model_freq, how = 'sum'):
    if source_freq == model_freq:
        return series
    elif source_freq == 'MS' and model_freq == 'D':
        return monthly_to_daily(series)
    elif source_freq == 'D' and model_freq == 'MS':
        return series.resample(model_freq, how = how)
    else:
        raise NotImplementedError("Source frequency '{0}' can not be converted to model frequency '{1}' at this time.".format(source_freq, model_freq))
<|endoftext|>


<commit_before>
""" Strings used in the class view. """

def chooseClass():
    return "Choose a class you want to see."

def noPermission():
    return "You don't have permissions to see this."

""" String messages used as level tips in the game view. """

def buttons():
    return "Use the buttons in the left bottom part of the screen to create a path that " \
        + "will lead the van to the destination."

def dragAndDrop():
    return "
Drag the blocks from the left to the white space and connect them with one " \
        + "another to create series of commands that will guide the driver to the destination. " \
        + "To remove an instruction place it back in the gray area. Remember to start from the " \
        + "start block."

def description_level_default():
    return description_overall() + dragAndDrop()

def description_overall():
    return "Help the van deliver the order to the customers in the house.

"

def description_level1():
    return description_overall() + buttons()

def description_level2():
    message = "To connect two instructions stack them together on the white space. "
    return description_overall() + message + dragAndDrop()

def description_level3():
    message = "Turn right lets the driver know he has to turn right. "
    return description_overall() + message + dragAndDrop()

def description_level4():
    message = "Turning only right is really boring. Let's add turning left as well. Now you can " \
        + "also use Turn Left command. "
    return description_overall() + message

def description_level5():
    message = "Now you are ready for more complex paths!

"
    return message + description_overall()

def description_level6():
    message = "Manually adding repeating instructions is boring. That's why there is a " \
        + "repeat block. Repeat block executes the instructions attached inside it " \
        + "specified amount of times. Type into the light green box in the block a number of " \
        + "repetitions. "
    return description_overall() + message

def description_level7():
    message = "This road looks quite familiar, doesn't it?
 Use the repeat " \
        + "block to simplify your program which guides the driver. "
    return description_overall() + message

def description_level8():
    message = "While and until blocks are quite similar to the repeat one. But " \
        + "instead of specifying exact amount of repetitions, we append a condition. The blocks " \
        + "inside the while or until loops will be executed as long as the " \
        + "condition is true.
 Change the while block to the until and add " \
        + "the at destination condition.
 Use the modified set of blocks to create " \
        + "a program that guides the driver to the house."
    return description_overall() + message

def description_level9():
    message = "Use the until block together with the at destination condition " \
        + "to guide the van to the destination. "
    return description_overall() + message

def description_level10():
    message = "Usually there is no such thing as until. A while block with " \
        + "a negated condition can be used to achieve the same result.
 Use the not " \
        + "block to reverse the condition. "
    return description_overall() + message

def description_level11():
    message = "Use the while block to create a simpler program to guide the van. "
    return description_overall() + message

def description_level12():
    message = "In this level, we have a look at the if statement.
 If " \
        + "statements are used when we want a set of commands to be executed only if a condition " \
        + "holds. For example, 'if there is a turn right, turn right'. If the condition " \
        + "is false, the block is omitted.
 Use the if block to create a path " \
        + "for the driver to reach the destination. "
    return description_overall() + message

def description_level13():
    message = "The if statement is often used with the else clause. " \
        + "If the condition is true, the block in the if gap is executed, otherwise " \
        + "the one following else is.
 Use an if block together with " \
        + "else one to create a path for the driver. "
    return description_overall() + message

def description_level14():
    message = "Quite often we need to check more than one condition to know how to behave - " \
        + "there might not be a turn right, but we still don't know whether we can go forwards " \
        + "or we have to turn left first. Hence, we can append else if blocks " \
        + "to the if statement.
 Use the if together with else if " \
        + "and else to guide the driver to the customer. "
    return description_overall() + message

def description_level15():
    message = "Now you are ready!
 Use all your knowledge and the newly added conditions " \
        + "to guide the van to the house. "
    return description_overall() + message

def description_level16():
    message = "zomg! Junctions! "
    return description_overall() + message

def description_level17():
    message = "zomg! Loops! "
    return description_overall() + message

def description_level18():
    message = "zomg! Non-trivial loops! "
    return description_overall() + message

def description_level19():
    message = "Have fun! "
    return description_overall() + message

def description_level20():
    message = "Non-trivial loops??!? "
    return description_overall() + message

def description_level21():
    message = "zomg! I don't even know what to say! "
    return description_overall() + message

def hint_level_default():
    message = "There is no specific information I can give for this level.
Do your best to remember some of the things you have learnt in the previous levels. "
    return message

def hint_level1():
    message = "Drag and drop the move forwards block so that it is under the start block - close enough to be touching. "
    return message

def hint_level2():
    message = "A block can be placed next to another if the jigsaw pieces fit. A second move forwards block can be placed under the first move forwards block. "
    return message

def hint_level3():
    message = "A block can be placed next to another if the jigsaw pieces fit. A turn right block can be placed under the first move forwards block. "
    return message

def hint_level4():
    message = "This road starts by curving to the left. Then it curves to the right. "
    return message

def hint_level5():
    message = "Follow the road round. Doing this with the arrows next to the GO button will produce the instructions for you! "
    return message

def hint_level6():
    message = "A move forwards block can be placed inside of the repeat block (to the right of the word 'do').
Don't forget to change the number of times you need to repeat. "
    return message

def hint_level7():
    message = "This level can be broken down into 3 sets of: 'turn left, then turn right'. "
    return message

def hint_level8():
    message = "The blocks should read like a sentence: Repeat (the following) until at destination: move forwards. "
    return message

def hint_level9():
    message = "The blocks should read like a sentence: Repeat (the following) until at destination: turn left, (then) turn right. "
    return message

def hint_level10():
    message = "while not is the same as until.
The blocks should read like a sentence: Repeat (the following) while not at destination: move forwards. "
    return message

def hint_level11():
    message = "while not is the same as until.
The blocks should read like a sentence: Repeat (the following) while not at destination: turn left, (then) turn right. "
    return message

def hint_level12():
    message = "if a road exists forwards then move forwards. This instruction will need to be repeated to get to the destination. "
    return message

def hint_level13():
    message = "We need to check where the road is using an if-else block.
You can create an if-else block by clicking the star on the if block, and adding the else clause.
If the condition block is true, the blocks after if are executed, otherwise the blocks after else are.
if a road exists left, turn left. else (otherwise) turn right. "
    return message

def hint_level14():
    message = "We need to check where the road is using an if-else if block.
You can create an if-else if block by clicking the star on the if block, and adding the else if clause.
If the first condition block is true, the blocks after if are executed, otherwise if the second condition block is true, the blocks after else if are executed.
if a road exists left, turn left. else if a road exists right, turn right. else move forwards. "
    return message

def hint_level15():
    message = hint_level_default()
    return message

def hint_level16():
    message = "If the road is a dead end, you will need to turn around "
    return message

def hint_level17():
    message = hint_level_default()
    return message

def hint_level18():
    message = hint_level_default()
    return message

def hint_level19():
    message = hint_level_default()
    return message

def hint_level20():
    message = hint_level_default()
    return message

def hint_level21():
    message = hint_level_default()
    return message

<commit_msg>Reformatted messages to use up to 100 chacacters per line.<commit_after>""" String messages used on the settings page """

def chooseAvatar():
    return "Choose your avatar"

def uploadAvatar():
    return "Or upload your own"

def noLevelsToShow():
    return "It seems that you have not created any levels. How about creating one now?"

def noSharedLevels():
    return "No one shared a level with you yet."

""" Strings used in the class view. """

def chooseClass():
    return "Choose a class you want to see."

def noPermission():
    return "You don't have permissions to see this."

""" String messages used as level tips in the game view. """

def buttons():
    return "Use the buttons in the left bottom part of the screen to create a path that " \
        + "will lead the van to the destination."

def dragAndDrop():
    return "
Drag the blocks from the left to the white space and connect them with one " \
        + "another to create series of commands that will guide the driver to the destination. " \
        + "To remove an instruction place it back in the gray area. Remember to start from the " \
        + "start block."

def description_level_default():
    return description_overall() + dragAndDrop()

def description_overall():
    return "Help the van deliver the order to the customers in the house.

"

def description_level1():
    return description_overall() + buttons()

def description_level2():
    message = "To connect two instructions stack them together on the white space. "
    return description_overall() + message + dragAndDrop()

def description_level3():
    message = "Turn right lets the driver know he has to turn right. "
    return description_overall() + message + dragAndDrop()

def description_level4():
    message = "Turning only right is really boring. Let's add turning left as well. Now you can " \
        + "also use Turn Left command. "
    return description_overall() + message

def description_level5():
    message = "Now you are ready for more complex paths!

"
    return message + description_overall()

def description_level6():
    message = "Manually adding repeating instructions is boring. That's why there is a " \
        + "repeat block. Repeat block executes the instructions attached inside it " \
        + "specified amount of times. Type into the light green box in the block a number of " \
        + "repetitions. "
    return description_overall() + message

def description_level7():
    message = "This road looks quite familiar, doesn't it?
 Use the repeat " \
        + "block to simplify your program which guides the driver. "
    return description_overall() + message

def description_level8():
    message = "While and until blocks are quite similar to the repeat one. But " \
        + "instead of specifying exact amount of repetitions, we append a condition. The blocks " \
        + "inside the while or until loops will be executed as long as the " \
        + "condition is true.
 Change the while block to the until and add " \
        + "the at destination condition.
 Use the modified set of blocks to create " \
        + "a program that guides the driver to the house."
    return description_overall() + message

def description_level9():
    message = "Use the until block together with the at destination condition " \
        + "to guide the van to the destination. "
    return description_overall() + message

def description_level10():
    message = "Usually there is no such thing as until. A while block with " \
        + "a negated condition can be used to achieve the same result.
 Use the not " \
        + "block to reverse the condition. "
    return description_overall() + message

def description_level11():
    message = "Use the while block to create a simpler program to guide the van. "
    return description_overall() + message

def description_level12():
    message = "In this level, we have a look at the if statement.
 If " \
        + "statements are used when we want a set of commands to be executed only if a condition " \
        + "holds. For example, 'if there is a turn right, turn right'. If the condition " \
        + "is false, the block is omitted.
 Use the if block to create a path " \
        + "for the driver to reach the destination. "
    return description_overall() + message

def description_level13():
    message = "The if statement is often used with the else clause. " \
        + "If the condition is true, the block in the if gap is executed, otherwise " \
        + "the one following else is.
 Use an if block together with " \
        + "else one to create a path for the driver. "
    return description_overall() + message

def description_level14():
    message = "Quite often we need to check more than one condition to know how to behave - " \
        + "there might not be a turn right, but we still don't know whether we can go forwards " \
        + "or we have to turn left first. Hence, we can append else if blocks " \
        + "to the if statement.
 Use the if together with else if " \
        + "and else to guide the driver to the customer. "
    return description_overall() + message

def description_level15():
    message = "Now you are ready!
 Use all your knowledge and the newly added conditions " \
        + "to guide the van to the house. "
    return description_overall() + message

def description_level16():
    message = "zomg! Junctions! "
    return description_overall() + message

def description_level17():
    message = "zomg! Loops! "
    return description_overall() + message

def description_level18():
    message = "zomg! Non-trivial loops! "
    return description_overall() + message

def description_level19():
    message = "Have fun! "
    return description_overall() + message

def description_level20():
    message = "Non-trivial loops??!? "
    return description_overall() + message

def description_level21():
    message = "zomg! I don't even know what to say! "
    return description_overall() + message

def hint_level_default():
    message = "There is no specific information I can give for this level.
Do your best to " \
        + "remember some of the things you have learnt in the previous levels. "
    return message

def hint_level1():
    message = "Drag and drop the move forwards block so that it is under the start " \
        + "block - close enough to be touching. "
    return message

def hint_level2():
    message = "A block can be placed next to another if the jigsaw pieces fit. A second move " \
        + "forwards block can be placed under the first move forwards block. "
    return message

def hint_level3():
    message = "A block can be placed next to another if the jigsaw pieces fit. A turn " \
        + "right block can be placed under the first move forwards block. "
    return message

def hint_level4():
    message = "This road starts by curving to the left. Then it curves to the right. "
    return message

def hint_level5():
    message = "Follow the road round. Doing this with the arrows next to the GO button " \
        + "will produce the instructions for you! "
    return message

def hint_level6():
    message = "A move forwards block can be placed inside of the repeat block (to " \
        + "the right of the word 'do').
Don't forget to change the number of times you need " \
        + "to repeat. "
    return message

def hint_level7():
    message = "This level can be broken down into 3 sets of: 'turn left, then turn right'. "
    return message

def hint_level8():
    message = "The blocks should read like a sentence: Repeat (the following) until at " \
        + "destination: move forwards. "
    return message

def hint_level9():
    message = "The blocks should read like a sentence: Repeat (the following) until at " \
        + "destination: turn left, (then) turn right. "
    return message

def hint_level10():
    message = "while not is the same as until.
The blocks should read like a " \
        + "sentence: Repeat (the following) while not at destination: move " \
        + "forwards. "
    return message

def hint_level11():
    message = "while not is the same as until.
The blocks should read like a " \
        + "sentence: Repeat (the following) while not at destination: turn " \
        + "left, (then) turn right. "
    return message

def hint_level12():
    message = "if a road exists forwards then move forwards. This "\
        + "instruction will need to be repeated to get to the destination. "
    return message

def hint_level13():
    message = "We need to check where the road is using an if-else block.
You can " \
        + "create an if-else block by clicking the star on the if block, and " \
        + "adding the else clause.
If the condition block is true, the blocks after " \
        + "if are executed, otherwise the blocks after else are.
if a " \
        + "road exists left, turn left. else (otherwise) turn right. "
    return message

def hint_level14():
    message = "We need to check where the road is using an if-else if block.
You can " \
        + "create an if-else if block by clicking the star on the if block, and " \
        + "adding the else if clause.
If the first condition block is true, the " \
        + "blocks after if are executed, otherwise if the second condition block is true, " \
        + "the blocks after else if are executed.
if a road exists " \
        + "left, turn left. else if a road exists right, turn right. " \
        + "else move forwards. "
    return message

def hint_level15():
    message = hint_level_default()
    return message

def hint_level16():
    message = "If the road is a dead end, you will need to turn around "
    return message

def hint_level17():
    message = hint_level_default()
    return message

def hint_level18():
    message = hint_level_default()
    return message

def hint_level19():
    message = hint_level_default()
    return message

def hint_level20():
    message = hint_level_default()
    return message

def hint_level21():
    message = hint_level_default()
    return message

<|endoftext|>


<commit_before>import json
import logging
import random
import Algorithmia
import nltk

from textblob import TextBlob
from text_corpus import TextCorpus
from aylienapiclient import textapi
import tensorflow as tf

logger = logging.getLogger(__name__)

class RtmEventHandler(object):
    def __init__(self, slack_clients, msg_writer):
        self.clients = slack_clients
        self.msg_writer = msg_writer
        #self.trump_corpus = trump_corpus

    def handle(self, event):

        if 'type' in event:
            self._handle_by_type(event['type'], event)

    def _handle_by_type(self, event_type, event):
        # See https://api.slack.com/rtm for a full list of events
        # if event_type == 'error':
            # error
            # ignore self.msg_writer.write_error(event['channel'], json.dumps(event))
        if event_type == 'message':
            # message was sent to channel
            self._handle_message(event)
        elif event_type == 'channel_joined':
            # you joined a channel
            self.msg_writer.send_message(event['channel'], "Let's make America great again!")
        elif event_type == 'group_joined':
            # you joined a private group
            self.msg_writer.write_help_message(event['channel'])
        elif event_type == 'file_shared':
            self.msg_writer.send_message(event['channel'], "Got your file, thanks!")
        else:
            pass

    def _handle_message(self, event):
        # Filter out messages from the bot itself
        if not self.clients.is_message_from_me(event['user']):

            msg_txt = event['text']

            #if self.clients.is_bot_mention(msg_txt) or self._is_direct_message(event['channel']):
                #txt_b = TextBlob(msg_txt)

            #if self.clients.is_bot_mention(msg_txt) or self._is_direct_message(event['channel']):
                # e.g. user typed: "@pybot tell me a joke!"
            if 'sentiment' in msg_txt:
                client = textapi.Client("a19bb245", "2623b77754833e2711998a0b0bdad9db")
                sentiment = client.Sentiment({"text": msg_txt})
                str = sentiment['polarity']
                str2 = " - %3.3f" % sentiment['polarity_confidence']
                str += str2
                self.msg_writer.send_message(event['channel'], str)
            elif 'tag' in msg_txt:
                #self.msg_writer.write_analytics(event['channel'], msg_txt)
                #if self.clients.is_bot_mention(msg_txt) or self._is_direct_message(event['channel']):
                #txt_b = TextBlob(msg_txt)
#                   response = txt_b.tags
#                   self.msg_writer.send_message(event['channel'], response)
                count = 0;
                client = Algorithmia.client('sim3x6PzEv6m2icRR+23rqTTcOo1')
                algo = client.algo('nlp/AutoTag/1.0.0')
                tags = algo.pipe(msg_txt)
                str_final = ""
                #print entities.result
                for item in tags.result:
                    if count == 0:
                        pass
                    else:
                        str_final += item
                        str_final += ", "
                    count = count + 1
                self.msg_writer.send_message(event['channel'], str_final)
                #algo = client.algo('StanfordNLP/NamedEntityRecognition/0.2.0')
                #entities = algo.pipe(msg_txt)
            elif 'tensor' in msg_txt:
                hello = tf.constant('Hello, TensorFlow!')
                sess = tf.Session()
                value = sess.run(hello)
                self.msg_writer.send_message(event['channel'], value)
            elif 'entity' in msg_txt or 'Entity' in msg_txt or 'ENTITY' in msg_txt:
                client = Algorithmia.client('sim3x6PzEv6m2icRR+23rqTTcOo1')
                msg_txt = msg_txt.split(' ', 1)[1]
                algo = client.algo('StanfordNLP/NamedEntityRecognition/0.2.0')
                entities = algo.pipe(msg_txt)
                str_final = ""
                #print entities.result
                for inner_l in entities.result:
                    for item in inner_l:
                        str = item[0] + " - " + item[1] + ", "
                        str_final += str
                self.msg_writer.send_message(event['channel'], str_final)
                #algo = client.algo('StanfordNLP/NamedEntityRecognition/0.2.0')
                #entities = algo.pipe(msg_txt)
            elif 'IMAGE' in msg_txt or 'Image' in msg_txt or 'image' in msg_txt:
                import re
                msg_txt = msg_txt.split(' ', 1)[1]
                msg_txt = msg_txt[1:-1]
                url = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', msg_txt)
                url = ''.join(url)
                client = Algorithmia.client('sim3x6PzEv6m2icRR+23rqTTcOo1')
                algo = client.algo('deeplearning/InceptionNet/1.0.2')
                tags = algo.pipe(url).result['tags'][0]['class']
                import unicodedata
                tags = unicodedata.normalize('NFKD', tags).encode('ascii','ignore')
                self.msg_writer.send_message(event['channel'], tags)

            elif 'POS' in msg_txt:

                msg_txt = msg_txt.split(' ', 1)[1]
                s = msg_txt

                from nltk import Tree
                from nltk.draw.util import CanvasFrame
                from nltk.draw import TreeWidget
                from nltk.corpus import treebank
                from nltk.tree import Tree
                from nltk.draw.tree import TreeView
                cf = CanvasFrame()
                t = Tree.fromstring(s)
                tc = TreeWidget(cf.canvas(),t)
                cf.add_widget(tc,10,10) # (10,10) offsets
                cf.print_to_file('tree.ps')
                cf.destroy()
                import os
                os.system('convert output.ps output.png')
                txt = "Grammar Tree:"
                attachment = {
                    "pretext": "Based on NLTK",
                    "title": "Grammar tree frm text provided",
                    "title_link": "https://nltk.org",
                    "text": txt,
                    "fallback": txt,
                    "image_url": "output.png",
                    "color": "#7CD197",
                }
                self.clients.web.chat.post_message(channel_id, txt, attachments=[attachment], as_user='true')

                from pattern.en import parse
                s = parse(s, relations=True, lemmata=True)
                self.msg_writer.send_message(event['channel'], s)

            elif 'classify' in msg_txt:
                client = textapi.Client("a19bb245", "2623b77754833e2711998a0b0bdad9db")
                classifications = client.ClassifyByTaxonomy({"text": msg_txt, "taxonomy": "iab-qag"})
                sent_str = ""
                for category in classifications['categories']:
                    sent_str += category['label'] + ", "
                sent_str = sent_str[:-1]
                response = sent_str
                self.msg_writer.send_message(event['channel'], response)

            elif 'hash' in msg_txt:
                client = textapi.Client("a19bb245", "2623b77754833e2711998a0b0bdad9db")
                msg_txt = msg_txt.split(' ', 1)[1]
                msg_txt = msg_txt[1:-1]
                url = msg_txt
                import re
                url = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', url)
                hashtags = client.Hashtags({"url": url})
                response = ', '.join(hashtags['hashtags'])
                str = ""
                list = response.split(' ')
                for i in range(0, 5):
                    str += list[i]
                    str += " "
                self.msg_writer.send_message(event['channel'], str)

            elif 'help' in msg_txt:
                self.msg_writer.write_help_message(event['channel'])
            elif 'joke' in msg_txt:
                self.msg_writer.write_joke(event['channel'])
            elif 'attachment' in msg_txt:
                self.msg_writer.demo_attachment(event['channel'])
            elif 'echo' in msg_txt:
                self.msg_writer.send_message(event['channel'], msg_txt)
            else:
                pass

            return

        def _is_direct_message(self, channel_id):
            client = Algorithmia.client('sim3x6PzEv6m2icRR+23rqTTcOo1')
            algo = client.algo('StanfordNLP/NamedEntityRecognition/0.2.0')
            entities = algo.pipe(msg_txt)
            str_final = ""
            count = 0;
            for inner_l in entities.result:
                for item in inner_l:
                    if count == 0:
                        pass
                    else:
                        str = item[0] + " - " + item[1] + ", "
                    str_final += str
                    count = count + 1
            self.msg_writer.send_message(event['channel'], str_final)
            return channel_id.startswith('D')
<commit_msg>Update event_handler.py<commit_after>import json
import logging
import random
import Algorithmia
import nltk

from textblob import TextBlob
from text_corpus import TextCorpus
from aylienapiclient import textapi
import tensorflow as tf

logger = logging.getLogger(__name__)

class RtmEventHandler(object):
    def __init__(self, slack_clients, msg_writer):
        self.clients = slack_clients
        self.msg_writer = msg_writer
        #self.trump_corpus = trump_corpus

    def handle(self, event):

        if 'type' in event:
            self._handle_by_type(event['type'], event)

    def _handle_by_type(self, event_type, event):
        # See https://api.slack.com/rtm for a full list of events
        # if event_type == 'error':
            # error
            # ignore self.msg_writer.write_error(event['channel'], json.dumps(event))
        if event_type == 'message':
            # message was sent to channel
            self._handle_message(event)
        elif event_type == 'channel_joined':
            # you joined a channel
            self.msg_writer.send_message(event['channel'], "Let's make America great again!")
        elif event_type == 'group_joined':
            # you joined a private group
            self.msg_writer.write_help_message(event['channel'])
        elif event_type == 'file_shared':
            self.msg_writer.send_message(event['channel'], "Got your file, thanks!")
        else:
            pass

    def _handle_message(self, event):
        # Filter out messages from the bot itself
        if not self.clients.is_message_from_me(event['user']):

            msg_txt = event['text']

            #if self.clients.is_bot_mention(msg_txt) or self._is_direct_message(event['channel']):
                #txt_b = TextBlob(msg_txt)

            #if self.clients.is_bot_mention(msg_txt) or self._is_direct_message(event['channel']):
                # e.g. user typed: "@pybot tell me a joke!"
            if 'sentiment' in msg_txt:
                client = textapi.Client("a19bb245", "2623b77754833e2711998a0b0bdad9db")
                sentiment = client.Sentiment({"text": msg_txt})
                str = sentiment['polarity']
                str2 = " - %3.3f" % sentiment['polarity_confidence']
                str += str2
                self.msg_writer.send_message(event['channel'], str)
            elif 'tag' in msg_txt:
                #self.msg_writer.write_analytics(event['channel'], msg_txt)
                #if self.clients.is_bot_mention(msg_txt) or self._is_direct_message(event['channel']):
                #txt_b = TextBlob(msg_txt)
#                   response = txt_b.tags
#                   self.msg_writer.send_message(event['channel'], response)
                count = 0;
                client = Algorithmia.client('sim3x6PzEv6m2icRR+23rqTTcOo1')
                algo = client.algo('nlp/AutoTag/1.0.0')
                tags = algo.pipe(msg_txt)
                str_final = ""
                #print entities.result
                for item in tags.result:
                    if count == 0:
                        pass
                    else:
                        str_final += item
                        str_final += ", "
                    count = count + 1
                self.msg_writer.send_message(event['channel'], str_final)
                #algo = client.algo('StanfordNLP/NamedEntityRecognition/0.2.0')
                #entities = algo.pipe(msg_txt)
            elif 'tensor' in msg_txt:
                hello = tf.constant('Hello, TensorFlow!')
                sess = tf.Session()
                value = sess.run(hello)
                self.msg_writer.send_message(event['channel'], value)
            elif 'entity' in msg_txt or 'Entity' in msg_txt or 'ENTITY' in msg_txt:
                client = Algorithmia.client('sim3x6PzEv6m2icRR+23rqTTcOo1')
                msg_txt = msg_txt.split(' ', 1)[1]
                algo = client.algo('StanfordNLP/NamedEntityRecognition/0.2.0')
                entities = algo.pipe(msg_txt)
                str_final = ""
                #print entities.result
                for inner_l in entities.result:
                    for item in inner_l:
                        str = item[0] + " - " + item[1] + ", "
                        str_final += str
                self.msg_writer.send_message(event['channel'], str_final)
                #algo = client.algo('StanfordNLP/NamedEntityRecognition/0.2.0')
                #entities = algo.pipe(msg_txt)
            elif 'IMAGE' in msg_txt or 'Image' in msg_txt or 'image' in msg_txt:
                import re
                msg_txt = msg_txt.split(' ', 1)[1]
                msg_txt = msg_txt[1:-1]
                url = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', msg_txt)
                url = ''.join(url)
                client = Algorithmia.client('sim3x6PzEv6m2icRR+23rqTTcOo1')
                algo = client.algo('deeplearning/InceptionNet/1.0.2')
                tags = algo.pipe(url).result['tags'][0]['class']
                import unicodedata
                tags = unicodedata.normalize('NFKD', tags).encode('ascii','ignore')
                self.msg_writer.send_message(event['channel'], tags)

            elif 'POS' in msg_txt:

                msg_txt = msg_txt.split(' ', 1)[1]
                s = msg_txt

                from nltk import Tree
                from nltk.draw.util import CanvasFrame
                from nltk.draw import TreeWidget
                from nltk.corpus import treebank
                from nltk.tree import Tree
                from nltk.draw.tree import TreeView
                import nltk.compat
                try:
                    import tkinter
                except ImportError:
                    import warnings
                    warnings.warn("nltk.draw package not loaded "
                                  "(please install Tkinter library).")
                else:
                    from nltk.draw.cfg import ProductionList, CFGEditor, CFGDemo
                    from nltk.draw.tree import (TreeSegmentWidget, tree_to_treesegment,
                                      TreeWidget, TreeView, draw_trees)
                    from nltk.draw.table import Table

                from nltk.draw.dispersion import dispersion_plot
                cf = CanvasFrame()
                t = Tree.fromstring(s)
                tc = TreeWidget(cf.canvas(),t)
                cf.add_widget(tc,10,10) # (10,10) offsets
                cf.print_to_file('tree.ps')
                cf.destroy()
                import os
                os.system('convert output.ps output.png')
                txt = "Grammar Tree:"
                attachment = {
                    "pretext": "Based on NLTK",
                    "title": "Grammar tree frm text provided",
                    "title_link": "https://nltk.org",
                    "text": txt,
                    "fallback": txt,
                    "image_url": "output.png",
                    "color": "#7CD197",
                }
                self.clients.web.chat.post_message(channel_id, txt, attachments=[attachment], as_user='true')

                from pattern.en import parse
                s = parse(s, relations=True, lemmata=True)
                self.msg_writer.send_message(event['channel'], s)

            elif 'classify' in msg_txt:
                client = textapi.Client("a19bb245", "2623b77754833e2711998a0b0bdad9db")
                classifications = client.ClassifyByTaxonomy({"text": msg_txt, "taxonomy": "iab-qag"})
                sent_str = ""
                for category in classifications['categories']:
                    sent_str += category['label'] + ", "
                sent_str = sent_str[:-1]
                response = sent_str
                self.msg_writer.send_message(event['channel'], response)

            elif 'hash' in msg_txt:
                client = textapi.Client("a19bb245", "2623b77754833e2711998a0b0bdad9db")
                msg_txt = msg_txt.split(' ', 1)[1]
                msg_txt = msg_txt[1:-1]
                url = msg_txt
                import re
                url = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', url)
                hashtags = client.Hashtags({"url": url})
                response = ', '.join(hashtags['hashtags'])
                str = ""
                list = response.split(' ')
                for i in range(0, 5):
                    str += list[i]
                    str += " "
                self.msg_writer.send_message(event['channel'], str)

            elif 'help' in msg_txt:
                self.msg_writer.write_help_message(event['channel'])
            elif 'joke' in msg_txt:
                self.msg_writer.write_joke(event['channel'])
            elif 'attachment' in msg_txt:
                self.msg_writer.demo_attachment(event['channel'])
            elif 'echo' in msg_txt:
                self.msg_writer.send_message(event['channel'], msg_txt)
            else:
                pass

            return

        def _is_direct_message(self, channel_id):
            client = Algorithmia.client('sim3x6PzEv6m2icRR+23rqTTcOo1')
            algo = client.algo('StanfordNLP/NamedEntityRecognition/0.2.0')
            entities = algo.pipe(msg_txt)
            str_final = ""
            count = 0;
            for inner_l in entities.result:
                for item in inner_l:
                    if count == 0:
                        pass
                    else:
                        str = item[0] + " - " + item[1] + ", "
                    str_final += str
                    count = count + 1
            self.msg_writer.send_message(event['channel'], str_final)
            return channel_id.startswith('D')
<|endoftext|>


<commit_before>#     Copyright 2019, Kay Hayen, mailto:kay.hayen@gmail.com
#
#     Part of "Nuitka", an optimizing Python compiler that is compatible and
#     integrates with CPython, but also works on its own.
#
#     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.
#
""" Utils to work with shebang lines.

"""
import os
import re

def getShebangFromSource(source_code):
    if source_code.startswith("#!"):
        shebang = re.match(r"^#!\s*(.*?)\n", source_code)

        if shebang is not None:
            shebang = shebang.group(0).rstrip("\n")
    else:
        shebang = None

    return shebang

def getShebangFromFile(filename):
    with open(filename) as f:
        return getShebangFromSource(f.readline())

def parseShebang(shebang):
    parts = shebang.split()

    if os.path.basename(parts[0]) == "env":
        # This attempts to handle env with arguments and options.
        del parts[0]

        while parts[0].startswith("-"):
            del parts[0]

        while "=" in parts[0]:
            del parts[0]

    return parts[0][2:].lstrip(), parts[1:]
<commit_msg>Doc: Added API doc for the Shebang module.<commit_after>#     Copyright 2019, Kay Hayen, mailto:kay.hayen@gmail.com
#
#     Part of "Nuitka", an optimizing Python compiler that is compatible and
#     integrates with CPython, but also works on its own.
#
#     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.
#
""" Utils to work with shebang lines.

"""
import os
import re

def getShebangFromSource(source_code):
    """ Given source code, extract the shebang (#!) part.

    Notes:
        This function is less relevant on Windows, because it will not use
        this method of determining the execution. Still scripts aimed at
        multiple platforms will contain it and it can be used to e.g. guess
        the Python version expected, if it is a Python script at all.

        There are variants of the function that will work on filenames instead.
    Args:
        source_code: The source code as a unicode string
    Returns:
        The binary and arguments that the kernel will use (Linux and compatible).
    """

    if source_code.startswith("#!"):
        shebang = re.match(r"^#!\s*(.*?)\n", source_code)

        if shebang is not None:
            shebang = shebang.group(0).rstrip("\n")
    else:
        shebang = None

    return shebang

def getShebangFromFile(filename):
    """ Given a filename, extract the shebang (#!) part from it.

    Notes:
        This function is less relevant on Windows, because it will not use
        this method of determining the execution. Still scripts aimed at
        multiple platforms will contain it and it can be used to e.g. guess
        the Python version expected, if it is a Python script at all.

        There are variants of the function that will work on file content
        instead.
    Args:
        filename: The filename to get the shebang of
    Returns:
        The binary that the kernel will use (Linux and compatible).
    """

    with open(filename) as f:
        return getShebangFromSource(f.readline())

def parseShebang(shebang):
    """ Given a concrete shebang value, it will extract the binary used.

    Notes:
        This function is less relevant on Windows, because it will not use
        this method of determining the execution.

        This handles that many times people use `env` binary to search the
        PATH for an actual binary, e.g. `/usr/bin/env python3.7` where we
        would care most about the `python3.7` part and want to see through
        the `env` usage.
    Args:
        shebang: The shebang extracted with one of the methods to do so.
    Returns:
        The binary the kernel will use (Linux and compatible).
    """

    parts = shebang.split()

    if os.path.basename(parts[0]) == "env":
        # This attempts to handle env with arguments and options.
        del parts[0]

        while parts[0].startswith("-"):
            del parts[0]

        while "=" in parts[0]:
            del parts[0]

    return parts[0][2:].lstrip(), parts[1:]
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Author: Timo Denissen
E-Mail: timo@communtu.com
About this program:
Todo: - Edit the source files accordingly to the changes
      - Give the possibility to change the key name
      - GUI
'''

import yaml

def arbeit():
    '''Working with the file.'''
    mydict = yaml.load(template_yml)
#    print mydict
#    print type(mydict)
    template_yml.close()
    new_dict = switch_keyvalue(mydict['de'])
#    print new_dict
    check_dict(new_dict)
    print 'Exit'

def check_dict(dict):
    '''Check if there are multiple values for one key.'''
    print 'Please solve the following conflicts:'
    for key, value in dict.iteritems():
        if len(value) > 1:
            multiple_string = value
            print value, ':', key ,'\n'
            ask_string(multiple_string)
        else:
            pass

def ask_string(string):
    '''Ask user which string to use in templaye.yml'''
    temp_dict = {}
    x = 1
    for item in string:
        temp_dict[x] = item
        print x, item
        x += 1
#    print temp_dict
    ask_number = input('Enter the number of the correct key: ')
    newkey = temp_dict[ask_number]
#    print newkey
#    print 'type(newkey)'
#    print type(newkey)
    string.remove(newkey)
    oldkey_temp = string
#    print 'type(oldkey_temp)'
#    print type(oldkey_temp)
#    print oldkey_temp
    edit_files(oldkey_temp, newkey)

def edit_files(oldkey, newkey):
    '''Using "sed" to remove oldkey from source files.'''
    for item in oldkey:
#        print item
#        print type(item)
        oldkey = item
        sed = 'find app lib -name "*rb" -exec sed -i \'s/t(:' + oldkey + '\([^:alnum:_]\)/t(:' + newkey + '\1/g\' {} \;'
        print sed
    print '----------'

def switch_keyvalue(dict):
    '''Switching the key:value pairs in the template.yml file.'''
    new_dict = {}
    for key, value in dict.iteritems():
        if value in new_dict:
            new_dict[value].append(key)
        else:
            new_dict[value] = [key]
    return new_dict

'''Choosing the file to work with.'''
print 'This program is beta.'
print 'THIS IS NOT MEANT FOR PRODUCTIVE USAGE!!! YOU HAVE BEEN WARNED!'
print 'Using file "config/locales/template.yml"'
template_yml = open('config/locales/template_short.yml')
arbeit()
<commit_msg>added functions to edit source files and template.yml, not working right now, DO NOT USE!!!<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Author: Timo Denissen
E-Mail: timo@communtu.com
About this program:
Todo: - Edit the source files accordingly to the changes
      - Give the possibility to change the key name
      - GUI
'''

import yaml
import codecs

def arbeit():
    '''Working with the file.'''
    mydict = yaml.safe_load(template_yml)
    template_yml.close()
    new_dict = switch_keyvalue(mydict['de'])
    check_dict(new_dict)
    print 'Exit'

def check_dict(dict):
    '''Check if there are multiple values for one key.'''
    for key, value in dict.iteritems():
        if len(value) > 1:
            print 'Please solve this conflict:'
            multiple_string = value
            print value, ':', key ,'\n'
            ask_string(multiple_string)
        else:
            pass

def ask_string(string):
    '''Ask user which string to use in templaye.yml'''
    temp_dict = {}
    x = 1
    for item in string:
        temp_dict[x] = item
        print x, item
        x += 1
    ask_number = input('Enter the number of the correct key: ')
    newkey = temp_dict[ask_number]
    string.remove(newkey)
    oldkey_temp = string
    edit_files(oldkey_temp, newkey)

def edit_files(oldkey, newkey):
    '''Using "sed" to remove oldkey from source files.'''
    for item in oldkey:
        oldkey = item
        sed = 'find app lib -name "*rb" -exec sed -i \'s/t(:' + oldkey + '\([^:alnum:_]\)/t(:' + newkey + '\1/g\' {} \;'
        print sed
        edit_template(item)
    print '----------'

def edit_template(key):
    '''Editing the template.yml and removing multiple key:value pairs.'''
    template_yml = codecs.open('config/locales/template_short.yml', 'r', 'utf-8')
    template_dict_full = yaml.safe_load(template_yml)
    template_dict = template_dict_full['de']
    template_yml.close()
    template_yml = codecs.open('config/locales/template_short.yml', 'w', 'utf-8')
    del template_dict[key]
    template_yml.write(yaml.dump(template_dict_full, default_flow_style=False, encoding='utf-8'))
    template_yml.close()

def switch_keyvalue(dict):
    '''Switching the key:value pairs in the template.yml file.'''
    new_dict = {}
    for key, value in dict.iteritems():
        if value in new_dict:
            new_dict[value].append(key)
        else:
            new_dict[value] = [key]
    return new_dict

'''Choosing the file to work with.'''
print 'This program is beta.'
print 'THIS IS NOT MEANT FOR PRODUCTIVE USAGE!!! YOU HAVE BEEN WARNED!!!'
print 'Using file "config/locales/template.yml"'
template_yml = codecs.open('config/locales/template_short.yml', 'r', 'utf-8')
arbeit()
<|endoftext|>


<commit_before>#!/usr/bin/python2.5
#
# Copyright 2008 the Melange authors.
#
# 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.

"""Views for the User's own profiles.
"""

__authors__ = [
    '"Sverre Rabbelier" <sverre@rabbelier.nl>',
    '"Pawel Solyga" <pawel.solyga@gmail.com>',
  ]

from google.appengine.api import users

from django import forms
from django import http
from django.utils.translation import ugettext_lazy

from soc.logic import dicts
from soc.logic import validate
from soc.logic.models import user as user_logic
from soc.views import helper
from soc.views import out_of_band
from soc.views.helper import access
from soc.views.models import base

import soc.models.linkable
import soc.models.user
import soc.views.helper

class UserForm(helper.forms.BaseForm):
  """Django form displayed when creating or editing a User.
  """
  class Meta:
    """Inner Meta class that defines some behavior for the form.
    """
    #: db.Model subclass for which the form will gather information
    model = soc.models.user.User

    #: list of model fields which will *not* be gathered by the form
    exclude = ['account', 'former_accounts', 'is_developer']

  def clean_link_id(self):
    link_id = self.cleaned_data.get('link_id').lower()
    if not validate.isLinkIdFormatValid(link_id):
      raise forms.ValidationError("This link ID is in wrong format.")

    user = user_logic.logic.getForFields({'link_id': link_id},
                                          unique=True)

    # Get the currently logged in user account
    current_account = users.get_current_user()

    if user:
      if current_account != user.account:
        raise forms.ValidationError("This link ID is already in use.")

    return link_id

class View(base.View):
  """View methods for the User model.
  """

  DEF_USER_ACCOUNT_INVALID_MSG_FMT = ugettext_lazy(
    'The %(email)s account cannot be used with this site, for'
    ' one or more of the following reasons:'
    '
'
    '
the account is invalid
'
    '
the account is already attached to a User profile and cannot be'
    ' used to create another one
'
    '
the account is a former account that cannot be used again
'
    '
')

  def __init__(self, params=None):
    """Defines the fields and methods required for the base View class
    to provide the user with list, public, create, edit and delete views.

    Params:
      params: a dict with params for this View
    """

    rights = {}
    rights['unspecified'] = [access.deny]
    rights['any_access'] = [access.allow]
    rights['edit'] = [access.checkIsLoggedIn]
    rights['roles'] = [access.checkIsUser]
    rights['signIn'] = [access.checkNotLoggedIn]
    rights['notification'] = [access.checkIsUser]

    new_params = {}
    new_params['rights'] = rights
    new_params['logic'] = user_logic.logic

    new_params['name'] = "User"
    new_params['module_name'] = "user_self"
    new_params['url_name'] = "user"

    new_params['sidebar_heading'] = 'User (self)'
    new_params['sidebar'] = [
        (users.create_login_url("/user/edit"), 'Sign In', 'signIn'),
        ('/' + new_params['url_name'] + '/edit', 'Profile', 'edit'),
        ('/' + new_params['url_name'] + '/roles', 'Roles', 'roles'),
        ('/' + 'notification/list', 'Notifications', 'notification'),
        ]

    patterns = []

    page_name = "Profile"
    patterns += [(r'^%(url_name)s/(?P<access_type>edit)$',
                  'soc.views.models.%(module_name)s.edit', page_name)]

    page_name = "Requests Overview"
    patterns += [(r'^%(url_name)s/(?P<access_type>roles)$',
                   'soc.views.models.request.list_self', page_name)]

    new_params['django_patterns_defaults'] = patterns

    params = dicts.merge(params, new_params)

    super(View, self).__init__(params=params)

  EDIT_SELF_TMPL = 'soc/user/edit_self.html'

  def edit(self, request, access_type,
           page_name=None, params=None, seed=None, **kwargs):
    """Displays User self edit page for the entity specified by **kwargs.

    Args:
      request: the standard Django HTTP request object
      page_name: the page name displayed in templates as page and header title
      params: a dict with params for this View
      kwargs: The Key Fields for the specified entity
    """

    new_params = {}
    new_params['edit_template'] = self.EDIT_SELF_TMPL

    params = dicts.merge(params, new_params)
    params = dicts.merge(params, self._params)

    try:
      access.checkAccess(access_type, request, params['rights'])
    except out_of_band.Error, error:
      return helper.responses.errorResponse(error, request,
          template=self.EDIT_SELF_TMPL)

    account = users.get_current_user()
    properties = {'account': account}

    user = user_logic.logic.getForFields(properties, unique=True)

    # create default template context for use with any templates
    context = helper.responses.getUniversalContext(request)

    if request.method == 'POST':
      form = UserForm(request.POST)

      if form.is_valid():
        new_link_id = form.cleaned_data.get('link_id')
        properties = {
          'link_id': new_link_id,
          'name': form.cleaned_data.get("name"),
          'account': account,
        }

        # check if user account is not in former_accounts
        # if it is show error message that account is invalid
        if user_logic.logic.isFormerAccount(account):
          msg = self.DEF_USER_ACCOUNT_INVALID_MSG_FMT % {
            'email': account.email()}
          error = out_of_band.Error(msg)
          return helper.responses.errorResponse(
              error, request, template=self.EDIT_SELF_TMPL, context=context)

        user = user_logic.logic.updateOrCreateFromFields(
            properties, {'link_id': new_link_id})

        # redirect to /user/profile?s=0
        # (causes 'Profile saved' message to be displayed)
        return helper.responses.redirectToChangedSuffix(
            request, None, params=params['edit_params'])
    else: # request.method == 'GET'
      if user:
        # is 'Profile saved' parameter present, but referrer was not ourself?
        # (e.g. someone bookmarked the GET that followed the POST submit)
        if (request.GET.get(params['submit_msg_param_name'])
            and (not helper.requests.isReferrerSelf(request))):
          # redirect to aggressively remove 'Profile saved' query parameter
          return http.HttpResponseRedirect(request.path)

        # referrer was us, so select which submit message to display
        # (may display no message if ?s=0 parameter is not present)
        context['notice'] = (
            helper.requests.getSingleIndexedParamValue(
                request, params['submit_msg_param_name'],
                values=params['save_message']))

        # populate form with the existing User entity
        form = UserForm(instance=user)
      else:
        if request.GET.get(params['submit_msg_param_name']):
          # redirect to aggressively remove 'Profile saved' query parameter
          return http.HttpResponseRedirect(request.path)

        # no User entity exists for this Google Account, so show a blank form
        form = UserForm()

    context['form'] = form

    template = params['edit_template']

    return helper.responses.respond(request, template, context)

  def _editGet(self, request, entity, form):
    """See base.View._editGet().
    """

    # fill in the email field with the data from the entity
    form.fields['email'].initial = entity.account.email()

    super(View, self)._editGet(request, entity, form)

  def _editPost(self, request, entity, fields):
    """See base.View._editPost().
    """

    # fill in the account field with the user created from email
    fields['account'] = users.User(fields['email'])

    super(View, self)._editPost(request, entity, fields)

view = View()

edit = view.edit
<commit_msg>Add an unread count indication next to the notification link<commit_after>#!/usr/bin/python2.5
#
# Copyright 2008 the Melange authors.
#
# 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.

"""Views for the User's own profiles.
"""

__authors__ = [
    '"Sverre Rabbelier" <sverre@rabbelier.nl>',
    '"Pawel Solyga" <pawel.solyga@gmail.com>',
  ]

from google.appengine.api import users

from django import forms
from django import http
from django.utils.encoding import force_unicode
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy

from soc.logic import dicts
from soc.logic import validate
from soc.logic import models as model_logic
from soc.logic.models import user as user_logic
from soc.views import helper
from soc.views import out_of_band
from soc.views.helper import access
from soc.views.models import base

import soc.models.linkable
import soc.models.user
import soc.views.helper

class UserForm(helper.forms.BaseForm):
  """Django form displayed when creating or editing a User.
  """
  class Meta:
    """Inner Meta class that defines some behavior for the form.
    """
    #: db.Model subclass for which the form will gather information
    model = soc.models.user.User

    #: list of model fields which will *not* be gathered by the form
    exclude = ['account', 'former_accounts', 'is_developer']

  def clean_link_id(self):
    link_id = self.cleaned_data.get('link_id').lower()
    if not validate.isLinkIdFormatValid(link_id):
      raise forms.ValidationError("This link ID is in wrong format.")

    user = user_logic.logic.getForFields({'link_id': link_id},
                                          unique=True)

    # Get the currently logged in user account
    current_account = users.get_current_user()

    if user:
      if current_account != user.account:
        raise forms.ValidationError("This link ID is already in use.")

    return link_id

class View(base.View):
  """View methods for the User model.
  """

  DEF_USER_ACCOUNT_INVALID_MSG_FMT = ugettext_lazy(
    'The %(email)s account cannot be used with this site, for'
    ' one or more of the following reasons:'
    '
'
    '
the account is invalid
'
    '
the account is already attached to a User profile and cannot be'
    ' used to create another one
'
    '
the account is a former account that cannot be used again
'
    '
')

  def __init__(self, params=None):
    """Defines the fields and methods required for the base View class
    to provide the user with list, public, create, edit and delete views.

    Params:
      params: a dict with params for this View
    """

    rights = {}
    rights['unspecified'] = [access.deny]
    rights['any_access'] = [access.allow]
    rights['edit'] = [access.checkIsLoggedIn]
    rights['roles'] = [access.checkIsUser]
    rights['signIn'] = [access.checkNotLoggedIn]
    rights['notification'] = [access.checkIsUser]

    new_params = {}
    new_params['rights'] = rights
    new_params['logic'] = user_logic.logic

    new_params['name'] = "User"
    new_params['module_name'] = "user_self"
    new_params['url_name'] = "user"

    new_params['sidebar_heading'] = 'User (self)'
    new_params['sidebar'] = [
        (users.create_login_url("/user/edit"), 'Sign In', 'signIn'),
        ('/' + new_params['url_name'] + '/edit', 'Profile', 'edit'),
        ('/' + new_params['url_name'] + '/roles', 'Roles', 'roles'),
        ]

    patterns = []

    page_name = "Profile"
    patterns += [(r'^%(url_name)s/(?P<access_type>edit)$',
                  'soc.views.models.%(module_name)s.edit', page_name)]

    page_name = "Requests Overview"
    patterns += [(r'^%(url_name)s/(?P<access_type>roles)$',
                   'soc.views.models.request.list_self', page_name)]

    new_params['django_patterns_defaults'] = patterns

    params = dicts.merge(params, new_params)

    super(View, self).__init__(params=params)

  EDIT_SELF_TMPL = 'soc/user/edit_self.html'

  def edit(self, request, access_type,
           page_name=None, params=None, seed=None, **kwargs):
    """Displays User self edit page for the entity specified by **kwargs.

    Args:
      request: the standard Django HTTP request object
      page_name: the page name displayed in templates as page and header title
      params: a dict with params for this View
      kwargs: The Key Fields for the specified entity
    """

    new_params = {}
    new_params['edit_template'] = self.EDIT_SELF_TMPL

    params = dicts.merge(params, new_params)
    params = dicts.merge(params, self._params)

    try:
      access.checkAccess(access_type, request, params['rights'])
    except out_of_band.Error, error:
      return helper.responses.errorResponse(error, request,
          template=self.EDIT_SELF_TMPL)

    account = users.get_current_user()
    properties = {'account': account}

    user = user_logic.logic.getForFields(properties, unique=True)

    # create default template context for use with any templates
    context = helper.responses.getUniversalContext(request)

    if request.method == 'POST':
      form = UserForm(request.POST)

      if form.is_valid():
        new_link_id = form.cleaned_data.get('link_id')
        properties = {
          'link_id': new_link_id,
          'name': form.cleaned_data.get("name"),
          'account': account,
        }

        # check if user account is not in former_accounts
        # if it is show error message that account is invalid
        if user_logic.logic.isFormerAccount(account):
          msg = self.DEF_USER_ACCOUNT_INVALID_MSG_FMT % {
            'email': account.email()}
          error = out_of_band.Error(msg)
          return helper.responses.errorResponse(
              error, request, template=self.EDIT_SELF_TMPL, context=context)

        user = user_logic.logic.updateOrCreateFromFields(
            properties, {'link_id': new_link_id})

        # redirect to /user/profile?s=0
        # (causes 'Profile saved' message to be displayed)
        return helper.responses.redirectToChangedSuffix(
            request, None, params=params['edit_params'])
    else: # request.method == 'GET'
      if user:
        # is 'Profile saved' parameter present, but referrer was not ourself?
        # (e.g. someone bookmarked the GET that followed the POST submit)
        if (request.GET.get(params['submit_msg_param_name'])
            and (not helper.requests.isReferrerSelf(request))):
          # redirect to aggressively remove 'Profile saved' query parameter
          return http.HttpResponseRedirect(request.path)

        # referrer was us, so select which submit message to display
        # (may display no message if ?s=0 parameter is not present)
        context['notice'] = (
            helper.requests.getSingleIndexedParamValue(
                request, params['submit_msg_param_name'],
                values=params['save_message']))

        # populate form with the existing User entity
        form = UserForm(instance=user)
      else:
        if request.GET.get(params['submit_msg_param_name']):
          # redirect to aggressively remove 'Profile saved' query parameter
          return http.HttpResponseRedirect(request.path)

        # no User entity exists for this Google Account, so show a blank form
        form = UserForm()

    context['form'] = form

    template = params['edit_template']

    return helper.responses.respond(request, template, context)

  def _editGet(self, request, entity, form):
    """See base.View._editGet().
    """

    # fill in the email field with the data from the entity
    form.fields['email'].initial = entity.account.email()

    super(View, self)._editGet(request, entity, form)

  def _editPost(self, request, entity, fields):
    """See base.View._editPost().
    """

    # fill in the account field with the user created from email
    fields['account'] = users.User(fields['email'])

    super(View, self)._editPost(request, entity, fields)

  def getSidebarMenus(self, request, params=None):
    """See base.View.getSidebarMenus()
    """

    link_title = ugettext_lazy('Notifications')

    user = user_logic.logic.getForCurrentAccount()

    filter = {
        'scope': user,
        'unread': True,
        }

    notifications = model_logic.notification.logic.getForFields(filter)
    count = len(list(notifications))

    if count > 0:
      link_title = '%s (%d)' % (force_unicode(link_title), count)
      link_title = mark_safe(link_title)

    items = [('/' + 'notification/list', link_title, 'notification')]

    new_params = {}
    new_params['sidebar'] = items

    params = dicts.merge(params, new_params)

    return super(View, self).getSidebarMenus(request, params=params)

view = View()

edit = view.edit
<|endoftext|>


<commit_before>import sys
import logging
from django.conf import settings

class NullHandler(logging.Handler):
    def emit(self, record):
        pass

h = NullHandler()

_logger = logging.getLogger("south")
_logger.addHandler(h)
_logger.setLevel(logging.DEBUG)
# TODO: Add a log formatter?

def get_logger():
    debug_on = getattr(settings, "SOUTH_LOGGING_ON", False)
    logging_file = getattr(settings, "SOUTH_LOGGING_FILE", False)

    if debug_on:
        if logging_file:
            _logger.addHandler( logging.FileHandler(logging_file) )
            _logger.setLevel(logging.DEBUG)
        else:
            raise IOError, "SOUTH_LOGGING_ON is True. You also need a SOUTH_LOGGING_FILE setting."
    return _logger

def close_logger():
    "Closes the logger handler for the file, so we can remove the file after a test."
    for handler in _logger.handlers:
        _logger.removeHandler(handler)
        if isinstance(handler, logging.FileHandler):
            handler.close()<commit_msg>Fix #386 (too many file handlers)<commit_after>import sys
import logging
from django.conf import settings

# Create a dummy handler to use for now.
class NullHandler(logging.Handler):
    def emit(self, record):
        pass

_logger = logging.getLogger("south")
_logger.addHandler(NullHandler())
_logger.setLevel(logging.DEBUG)

def get_logger():
    "Attach a file handler to the logger if there isn't one already."
    debug_on = getattr(settings, "SOUTH_LOGGING_ON", False)
    logging_file = getattr(settings, "SOUTH_LOGGING_FILE", False)

    if debug_on:
        if logging_file and len(_logger.handlers) < 2:
            _logger.addHandler(logging.FileHandler(logging_file))
            _logger.setLevel(logging.DEBUG)
        else:
            raise IOError, "SOUTH_LOGGING_ON is True. You also need a SOUTH_LOGGING_FILE setting."

    return _logger

def close_logger():
    "Closes the logger handler for the file, so we can remove the file after a test."
    for handler in _logger.handlers:
        _logger.removeHandler(handler)
        if isinstance(handler, logging.FileHandler):
            handler.close()<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Addons modules by CLEARCORP
#    Copyright (C) 2009-TODAY (<http://clearcorp.co.cr>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
	'name': 'Rent',
	'version': '1.1',
	'url': 'http://launchpad.net/openerp-ccorp-addons',
	'author': 'ClearCorp S.A.',
	'website': 'http://clearcorp.co.cr',
	'category': 'Rent',
	'description': """ClearCorp 'rent' module for real estate business.
	""",
	'depends': [
		'account',
		],
	'init_xml': [],
	'demo_xml': [],
	'update_xml': [
					'wizard/rent_make_group.xml',
					'rent_sequence.xml',
					'rent_view.xml',
					'rent_data.xml',
					'rent_workflow.xml',
					'rent_contract_report.xml',
					'security/rent_security.xml',
					'security/ir.model.access.csv',
				],
	'license': 'AGPL-3',
	'installable': True,
	'active': False,
}
<commit_msg>[FIX] rent: class reference fix<commit_after># -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Addons modules by CLEARCORP
#    Copyright (C) 2009-TODAY (<http://clearcorp.co.cr>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
	'name': 'Rent',
	'version': '1.1',
	'url': 'http://launchpad.net/openerp-ccorp-addons',
	'author': 'ClearCorp S.A.',
	'website': 'http://clearcorp.co.cr',
	'category': 'Rent',
	'description': """ClearCorp 'rent' module for real estate business.
	""",
	'depends': [
		'account',
		'base_contact',
		],
	'init_xml': [],
	'demo_xml': [],
	'update_xml': [
					'wizard/rent_make_group.xml',
					'rent_sequence.xml',
					'rent_view.xml',
					'rent_data.xml',
					'rent_workflow.xml',
					'rent_contract_report.xml',
					'security/rent_security.xml',
					'security/ir.model.access.csv',
				],
	'license': 'AGPL-3',
	'installable': True,
	'active': False,
}
<|endoftext|>