コード例 #1
0
class logger:
    config = config()
    logpath = config['log']['logpath']
    logsize = int(config['log']['logsize'])
    lognum = int(config['log']['lognum'])
    logname = os.path.join(logpath,
                           sys.argv[0].split('/')[-1].split('.')[0]) + '.log'
    logger = logging.getLogger()
    formatter = logging.Formatter('[%(asctime)s][%(levelname)s] %(message)s',
                                  '%Y-%m-%d %H:%M:%S')
    fh = logging.handlers.RotatingFileHandler(logname,
                                              maxBytes=logsize,
                                              backupCount=lognum,
                                              encoding='utf-8')
    ch = logging.StreamHandler()
    fh.setFormatter(formatter)
    ch.setFormatter(formatter)

    logger.addHandler(fh)
    logger.addHandler(ch)
    logger.setLevel(level=logging.INFO)

    @classmethod
    def info(cls, msg):
        cls.logger.info(msg)

    @classmethod
    def warning(cls, msg):
        cls.logger.warning(msg)

    @classmethod
    def error(cls, msg):
        cls.logger.error(msg)
コード例 #2
0
ファイル: client.py プロジェクト: obale/tweetC2
 def __init__(self, username, password):
     cfg = config.config()
     self.accounts = cfg.getAccounts()
     self.prefix = cfg.getCommandPrefix()
     if password is None:
         password = self.getPassword(username)
     if password is None:
         helper.printErrorVerbose("No password for the user found!")
         sys.exit(0)
     self.api = twitter.Api(username, password)
コード例 #3
0
ファイル: ambiance.py プロジェクト: flexy2dd/storm-cloud
    def getAmbiance(self):
        if os.path.isfile(self.ambianceConf):
            oAmbiance = config.config()
            oAmbiance.read(self.ambianceConf)

            if oAmbiance.has_option('general', 'title'):
                generalTitle = oAmbiance.get('general', 'title')

            return oAmbiance

        return False
コード例 #4
0
ファイル: ambiance.py プロジェクト: flexy2dd/storm-cloud
    def setEventPos(self, delta):
        if os.path.isfile(self.ambianceConf):
            ambiance = config.config()
            ambiance.read(self.ambianceConf)

            ambiance.set('event', 'pos', str(delta))

            with open(self.ambianceConf, 'w') as configfile:
                ambiance.write(configfile)

            return True

        return False
コード例 #5
0
ファイル: ambiance.py プロジェクト: flexy2dd/storm-cloud
    def setThunderDeltas(self, thunderDeltas):
        if os.path.isfile(self.ambianceConf):
            ambiance = config.config()
            ambiance.read(self.ambianceConf)

            ambiance.set('thunder', 'deltaMax', str(thunderDeltas['max']))
            ambiance.set('thunder', 'deltaMin', str(thunderDeltas['min']))
            with open(self.ambianceConf, 'w') as configfile:
                ambiance.write(configfile)

            return True

        return False
コード例 #6
0
ファイル: ambiance.py プロジェクト: flexy2dd/storm-cloud
    def setRainSelect(self, iRain, rainSelect):
        if os.path.isfile(self.ambianceConf):
            ambiance = config.config()
            ambiance.read(self.ambianceConf)

            ambiance.set('rain', 'selected-' + str(iRain), str(rainSelect))

            with open(self.ambianceConf, 'w') as configfile:
                ambiance.write(configfile)

            return True

        return False
コード例 #7
0
ファイル: ambiance.py プロジェクト: flexy2dd/storm-cloud
    def setPlaying(self, background):
        if os.path.isfile(self.ambianceConf):
            ambiance = config.config()
            ambiance.read(self.ambianceConf)

            ambiance.set('play', 'background', str(background))

            with open(self.ambianceConf, 'w') as configfile:
                ambiance.write(configfile)

            return True

        return False
コード例 #8
0
ファイル: ambiance.py プロジェクト: flexy2dd/storm-cloud
    def setSnooze(self, snooze):
        if os.path.isfile(self.ambianceConf):
            ambiance = config.config()
            ambiance.read(self.ambianceConf)

            ambiance.set('general', 'snooze', str(snooze))
            self.debug('set snooze ' + str(snooze))

            with open(self.ambianceConf, 'w') as configfile:
                ambiance.write(configfile)

            return True

        return False
コード例 #9
0
ファイル: ambiance.py プロジェクト: flexy2dd/storm-cloud
    def setThunderVolume(self, volume):
        if os.path.isfile(self.ambianceConf):
            ambiance = config.config()
            ambiance.read(self.ambianceConf)

            ambiance.set('thunder', 'volume', str(volume))
            self.debug('set volume ' + str(volume))

            with open(self.ambianceConf, 'w') as configfile:
                ambiance.write(configfile)

            return True

        return False
コード例 #10
0
ファイル: ambiance.py プロジェクト: flexy2dd/storm-cloud
    def setLight(self, thunderlight):
        if os.path.isfile(self.ambianceConf):
            ambiance = config.config()
            ambiance.read(self.ambianceConf)

            if int(thunderlight) in [
                    constant.THUNDERLIGHT_ON, constant.THUNDERLIGHT_OFF
            ]:
                ambiance.set('thunder', 'light', str(thunderlight))

                with open(self.ambianceConf, 'w') as configfile:
                    ambiance.write(configfile)

                return True

        return False
コード例 #11
0
ファイル: ambiance.py プロジェクト: flexy2dd/storm-cloud
    def setRain(self, rain):
        if os.path.isfile(self.ambianceConf):
            ambiance = config.config()
            ambiance.read(self.ambianceConf)

            if int(rain) in [
                    constant.RAIN_LEVEL_NONE, constant.RAIN_LEVEL_LIGHT,
                    constant.RAIN_LEVEL_MODERATE, constant.RAIN_LEVEL_HEAVY
            ]:
                ambiance.set('rain', 'rain', str(rain))

                with open(self.ambianceConf, 'w') as configfile:
                    ambiance.write(configfile)

                return True

        return False
コード例 #12
0
ファイル: rainfall.py プロジェクト: mrworf/rainfall
 def __init__(self, useVirtual=False, accelerateTime=False):
   Thread.__init__(self)
   self.daemon = True
   self._sprinklers = []
   self._sprinklerid = 0
   if useVirtual:
     from modules.virtualdrv import virtualdrv
     self.gpiodrv = virtualdrv(self.onChange)
   else:
     from modules.gpiodrv import gpiodrv
     self.gpiodrv = gpiodrv(self.onChange)
   self.config = config()
   self.events = []
   self.delayer = Event()
   self.programRunning = False
   self.accelerateTime = accelerateTime
   if self.accelerateTime:
     logging.warning('Accelerating wallclock')
コード例 #13
0
ファイル: ambiance.py プロジェクト: flexy2dd/storm-cloud
    def setThunder(self, thunderstorm):
        if os.path.isfile(self.ambianceConf):
            ambiance = config.config()
            ambiance.read(self.ambianceConf)

            if int(thunderstorm) in [
                    constant.THUNDERSTORM_LEVEL_NONE,
                    constant.THUNDERSTORM_LEVEL_LIGHT,
                    constant.THUNDERSTORM_LEVEL_MODERATE,
                    constant.THUNDERSTORM_LEVEL_HEAVY
            ]:
                ambiance.set('thunder', 'thunder', str(thunderstorm))

                with open(self.ambianceConf, 'w') as configfile:
                    ambiance.write(configfile)

                return True

        return False
コード例 #14
0
ファイル: menu.py プロジェクト: Kloxx/metro_cadaver_boy
#!/usr/bin/env python2.7

import pygame
from modules import config

pygame.init()

# Import config
cfg = config.config()

fullscreen = cfg.fullscreen
width = cfg.width
height = cfg.height
resolution = (width, height)

# Define colors
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)

# Set screen
screen = pygame.display.set_mode(resolution, pygame.DOUBLEBUF|pygame.HWSURFACE)

# Menus
class menu(object):
    def __init__(self, title, background, width, height, rect):
        self.title = title
        self.font_size = height / rect.height
        self.index = 0
コード例 #15
0
 def test_connection_fails(self):
     CUSTOM_CONFIG = config()
     CUSTOM_CONFIG['Connection']['dbname'] = 'doesnotexist'
     with self.assertRaises(OperationalError):
         db.test_connection(CUSTOM_CONFIG)
コード例 #16
0
import unittest
from modules import db
from modules.config import config
from psycopg2 import OperationalError
DEFAULT_CONFIG = config()
from tests import setup_tests


class TestDB(unittest.TestCase):
    def test_connection_successful(self):
        self.assertEquals(db.test_connection(DEFAULT_CONFIG), True)

    def test_connection_fails(self):
        CUSTOM_CONFIG = config()
        CUSTOM_CONFIG['Connection']['dbname'] = 'doesnotexist'
        with self.assertRaises(OperationalError):
            db.test_connection(CUSTOM_CONFIG)


if __name__ == '__main__':
    unittest.main()
コード例 #17
0
ファイル: log.py プロジェクト: tpakeman/looker_log_analysis
import logging
import os, sys
from datetime import datetime as dt
from modules import config

CONFIG = config.config()
LOG = logging.getLogger(CONFIG['App']['log_name'])
LOGDIR = CONFIG['App']['log_directory']
if not os.path.exists(LOGDIR):
    os.makedirs(LOGDIR)

file_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
stdout_format = logging.Formatter('%(levelname)s: %(message)s')

logging.basicConfig(filename=os.path.join(
    LOGDIR, f'looker-log-parsing-{dt.now():%Y-%m-%d}.log'),
                    format=file_format,
                    level=logging.DEBUG)

stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setLevel(logging.INFO)
stdout_handler.setFormatter(stdout_format)
LOG.addHandler(stdout_handler)
コード例 #18
0
from flask import Flask, render_template, make_response, redirect, request, session
import os
import time
from datetime import date, datetime, timedelta
from modules.config import config
from modules.account import account
from modules.tenant import tenant
from modules.contact import contact
from modules.oidc import google, microsoft
from modules.app_session import app_session
from modules.sfdc import sfdc
from modules.one_garden import one_garden
from modules.function import *

obj_config = config()

app = Flask(__name__, static_folder=obj_config.params['resources_path'])
app.secret_key = obj_config.params['flask_secret']


def header_template():
    context_header = {
        'lang_home': lang('Home'),
        'lang_setting': lang('Setting'),
        'link_home': link(''),
        'link_setting': link('setting'),
        'link_logout': link('logout'),
        'lang_logout': lang('Logout')
    }

    return context_header
コード例 #19
0
parser.add_argument("-v",
                    "--verbose",
                    help="verbose mode",
                    action='store_true')
parser.add_argument("-l", "--log", help="Log level")
args = parser.parse_args()

# ===========================================================================
# Logging
# ===========================================================================
logLevel = getattr(logging, 'ERROR', None)
if args.log:
    logLevel = getattr(logging, args.log.upper(), None)

if os.path.isfile(constant.AMBIANCE_CONF):
    confFile = config.config()
    confFile.read(constant.AMBIANCE_CONF)

    if confFile.has_option('general', 'debug'):
        logLevel = confFile.get('general', 'debug')
        logLevel = getattr(logging, logLevel.upper(), None)

logging.basicConfig(filename='/var/log/storm-cloud-manager.log',
                    level=logLevel)

# ===========================================================================
# Screen
# ===========================================================================
oScreen = screen.screen()
oScreen.cls()
oScreen.logger = logging
コード例 #20
0
ファイル: server.py プロジェクト: obale/tweetC2
from modules import twitterApi
from modules import commandParser
from modules import commandHandler
from modules import helper
from modules import p2p

def checkCommand(signum, frame):
    seconds = 30
    handler = commandHandler.commandHandler()
    handler.handleCommand()
    msg = 'Sleeping for ' + str(seconds) + ' seconds'
    helper.printInfoVerbose(msg)
    signal.alarm(seconds)

def quit(signum, frame):
    helper.printInfoVerbose('Shutting down...')
    sys.exit(0)

def mainloop():
    while True:
        time.sleep(300)

if __name__ == "__main__":
    signal.signal(signal.SIGALRM, checkCommand)
    signal.signal(signal.SIGINT, quit)
    cfgobj = config.config()
    helper = helper.helper()
    verbose = cfgobj.getVerbose()
    signal.alarm(1)
    mainloop()
コード例 #21
0
ファイル: ambiance.py プロジェクト: flexy2dd/storm-cloud
    def loadEvents(self):
        oAmbianceConf = config.config()
        oAmbianceConf.read(self.ambianceConf)

        eventsDict = {}

        self.currentThunderLevel = self.getThunder()
        #int(oAmbianceConf.get('general', 'thunder', fallback=constant.THUNDERSTORM_LEVEL_NONE))

        if self.currentThunderLevel > 0:
            iAmbianceVolume = int(
                oAmbianceConf.get('general', 'volume', fallback=50))
            oThunderlight = thunderlight.thunderlight()

            # default values
            fDefaultVolume = 100.00
            iDefaultLightOffset = 0
            iDefaultLightDelay = int(oThunderlight.getDelayFactor())
            iDefaultLightStrike = int(oThunderlight.getStrikeFactor())
            iDefaultLightBright = int(oThunderlight.getBrightFactor())

            oEventDefaultConf = config.config()
            eventFileDefaultConf = 'sounds/thunder/thunder.conf'
            if os.path.isfile(eventFileDefaultConf):
                oEventDefaultConf.read(eventFileDefaultConf)
                fDefaultVolume = oEventDefaultConf.getfloat(
                    'general-' + str(self.currentThunderLevel),
                    'volume',
                    fallback=fDefaultVolume)
                iDefaultLightOffset = oEventDefaultConf.getint(
                    'light-' + str(self.currentThunderLevel),
                    'offset',
                    fallback=iDefaultLightOffset)
                iDefaultLightDelay = oEventDefaultConf.getint(
                    'light-' + str(self.currentThunderLevel),
                    'delay',
                    fallback=iDefaultLightDelay)
                iDefaultLightStrike = oEventDefaultConf.getint(
                    'light-' + str(self.currentThunderLevel),
                    'force',
                    fallback=iDefaultLightStrike)
                iDefaultLightBright = oEventDefaultConf.getint(
                    'light-' + str(self.currentThunderLevel),
                    'bright',
                    fallback=iDefaultLightBright)

            regexp = r".*/(thunder-" + self.thunderToStr(
                self.currentThunderLevel) + "-.*)\.(wav|mp3)"
            eventIndex = 0
            for file in glob.glob('sounds/thunder/*'):
                result = re.match(regexp, str(file))
                if result is not None:

                    self.debug('find event ' + file)

                    fileRoot = result.groups()[0]
                    fileExt = result.groups()[1]

                    oEventConf = config.config()

                    eventFileConf = 'sounds/thunder/' + fileRoot + '.conf'
                    if os.path.isfile(eventFileConf):
                        oEventConf.read(eventFileConf)

                    fVolume = fDefaultVolume
                    if oEventConf.has_option('general', 'volume'):
                        fVolume = oEventConf.getfloat('general',
                                                      'volume',
                                                      fallback=fDefaultVolume)

                    iVolume = ((iAmbianceVolume * fVolume) / 100) / 100

                    iLightOffset = int(
                        oEventConf.get('light',
                                       'offset',
                                       fallback=iDefaultLightOffset))
                    iLightDelay = int(
                        oEventConf.get('light',
                                       'delay',
                                       fallback=iDefaultLightDelay))
                    iLightStrike = int(
                        oEventConf.get('light',
                                       'force',
                                       fallback=iDefaultLightStrike))
                    iLightBright = int(
                        oEventConf.get('light',
                                       'bright',
                                       fallback=iDefaultLightBright))

                    eventFile = '%s/../sounds/thunder/%s.%s' % (
                        os.path.dirname(__file__), fileRoot, fileExt)
                    self.debug('load event ' + eventFile)

                    oEvent = pygame.mixer.Sound(eventFile)
                    oEvent.set_volume(iVolume)

                    self.debug('..loaded ' + str(eventIndex) + '(duration:' +
                               str(oEvent.get_length()) + ', volume:' +
                               str(iVolume) + ')')
                    eventsDict[eventIndex] = {
                        'file': eventFile,
                        'oEvent': oEvent,
                        'duration': oEvent.get_length(),
                        'volume': iVolume,
                        'lightOffset': iLightOffset,
                        'lightDelay': iLightDelay,
                        'lightStrike': iLightStrike,
                        'lightBright': iLightBright
                    }

                    eventIndex += 1
                else:
                    self.debug('..not found')

        self.debug('has ' + str(len(eventsDict)) + ' event(s) loaded')

        return eventsDict
コード例 #22
0
ファイル: ambiance.py プロジェクト: flexy2dd/storm-cloud
    def playBackground(self):
        oAmbianceConf = config.config()
        oAmbianceConf.read(self.ambianceConf)

        self.currentRainLevel = self.getRain()
        #int(oAmbianceConf.get('rain', 'rain', fallback=constant.RAIN_LEVEL_NONE))

        if self.currentRainLevel > 0:

            iAmbianceVolume = int(
                oAmbianceConf.get('general', 'volume', fallback=50))

            fDefaultVolume = 100.00
            iDefaultDeltaMin = constant.AMBIANCE_DELTAMIN
            iDefaultDeltaMax = constant.AMBIANCE_DELTAMAX
            oDefaultConf = config.config()
            fileDefaultConf = 'sounds/rain/rain.conf'
            if os.path.isfile(fileDefaultConf):
                oDefaultConf.read(fileDefaultConf)
                fDefaultVolume = oDefaultConf.getfloat(
                    'general-' + str(self.currentRainLevel),
                    'volume',
                    fallback=fDefaultVolume)
                iDefaultDeltaMin = oDefaultConf.getint(
                    'general-' + str(self.currentRainLevel),
                    'deltaMin',
                    fallback=iDefaultDeltaMin)
                iDefaultDeltaMax = oDefaultConf.getint(
                    'general-' + str(self.currentRainLevel),
                    'deltaMax',
                    fallback=iDefaultDeltaMax)

            regexp = r".*/(rain-" + self.rainToStr(
                self.currentRainLevel) + "-.*)\.(wav|mp3)"
            rainFiles = []
            for file in glob.glob('sounds/rain/*'):
                result = re.match(regexp, str(file))
                if result is not None:
                    rainFiles.append({
                        'file': file,
                        'root': result.groups()[0],
                        'ext': result.groups()[1]
                    })

            if len(rainFiles) <= 0:
                return False

            iIdx = 0

            self.currentRainSelected = self.getRainSelected(
                self.currentRainLevel)
            if self.currentRainSelected != 'random':
                for iIdx, item in enumerate(rainFiles):
                    print(item)
                    print(iIdx)
                    if item['root'] == self.currentRainSelected:
                        break

            if iIdx <= 0:
                if len(rainFiles) > 1:
                    iIdx = random.randrange(0, len(rainFiles) - 1)

            rainFile = rainFiles[iIdx]

            oBackgroundConf = config.config()

            backgroundFileConf = 'sounds/rain/' + rainFile['root'] + '.conf'
            if os.path.isfile(backgroundFileConf):
                oBackgroundConf.read(backgroundFileConf)

            fVolume = fDefaultVolume
            if oBackgroundConf.has_option('general', 'volume'):
                fVolume = oBackgroundConf.getfloat('general',
                                                   'volume',
                                                   fallback=fDefaultVolume)

            self.currentBackgroundVolume = fVolume
            iVolume = ((iAmbianceVolume * fVolume) / 100) / 100
            self.currentVolume = iVolume

            deltas = self.getThunderDeltas()
            self.currentDeltaMin = deltas['min']
            self.currentDeltaMax = deltas['max']

            #      self.currentDeltaMin = oBackgroundConf.getint('general', 'deltaMin', fallback=iDefaultDeltaMin)
            #      self.currentDeltaMax = oBackgroundConf.getint('general', 'deltaMax', fallback=iDefaultDeltaMax)

            backgroundFile = '%s/../sounds/rain/%s.%s' % (
                os.path.dirname(__file__), rainFile['root'], rainFile['ext'])
            self.debug('load background ' + backgroundFile)

            if os.path.isfile(backgroundFile):
                oBackground = pygame.mixer.Sound(backgroundFile)

                self.debug('play background ' + backgroundFile + ' (volume:' +
                           str(iVolume) + ')')

                self.setPlaying(rainFile['root'])
                self.currentBackgroundName = backgroundFile
                self.currentBackground = oBackground
                oBackground.set_volume(iVolume)
                oBackground.play(-1)