Ejemplo n.º 1
0
    def __init__(self):

        try:  # some builds fails mysteriously

            self.logger = logging.Logger(level=LOG_LEVEL)

            self.prices = SettingsGroup()
            self.prices.beer = None
            self.prices.radler = None
            self.prices.mate = None
            self.prices.pali = None
            self.prices.spezi = None
            self.kueche = None
            self.read_settings_file(SETTINGS_FILE)

            self.today = datetime.datetime.now().strftime('%d.%m.%Y')

            self.drinker = []  # every person

            self._build_GUI()

        except Exception as ex:
            handle_excep(ex)
            logging.static_critical("Could not build GUI from this path, copy to local system and retry!")
            print("CRITICAL: Could not build GUI from this path, start with START.bat or copy to local system and retry!")
            print("Alternatively, start tool via the terminal")
            print("\t1) Open the terminal with 'cmd' in startmenu")
            print("\t2) navigate to scriptpath with command: 'pushd [Scriptpath]'")
            print("\t3) Start tool with command: Bierliste_Tool.py")
            print("\t4) If no Python version is installed please try START.bat")
            print("")
            os.system("pause")
Ejemplo n.º 2
0
 def __init__(self, username, uri=None):
     kwargs = {}
     if uri:  # leave as unspecified to use default
         kwargs['uri'] = uri
     self.client = TravisPy(**kwargs)
     self.username = username
     self.logger = logger.Logger('travis_ci')
Ejemplo n.º 3
0
    def __init__(self):
        super(GameLogic, self).__init__()
        self.logger = logger.Logger(self.__class__.__name__, logger.INFO)

        self.words = []
        self.remaining_words = []
        self.choices = []
        self.found_players_count = 0

        self.game_data = GameData()
        self.paint_buffer = []

        self.current_word = ""
        self.bonus_rules = {1: 25, 2: 15, 3: 5}

        self.choosing_timer = QtCore.QTimer(self)
        self.choosing_timer.setSingleShot(True)
        self.choosing_timer.timeout.connect(self.end_choosing)

        self.drawing_timer = QtCore.QTimer(self)
        self.drawing_timer.setSingleShot(True)
        self.drawing_timer.timeout.connect(self.end_drawing)

        self.hints_timer = QtCore.QTimer(self)
        self.hints_timer.timeout.connect(self.add_hint)

        self.choosing_phase = False
        self.drawing_phase = False
Ejemplo n.º 4
0
    def __init__(self, name, room='', balance=0, beers=0, radler=0, mate=0, pali=0, spezi=0):
        """

        :param name: String, name
        :param room: String, roomnumber
        :param balance: Float, money account
        :param beers: Integer, number of beers
        :param radler: Integer, number of radler
        :param mate: Integer, number of mate
        :param pali: Integer, number of pali
        :param spezi: Integer, number of spezi
        """
        self.updated = False
        self.logger = logging.Logger()

        self.ID = id(self)
        self.name = name.strip()
        self.room = str(room).strip()
        # self.id = self.generate_id()  # some obsolete approach, use id() instead
        self.balance = balance
        self.beers = beers
        self.radler = radler
        self.mate = mate
        self.pali = pali
        self.spezi = spezi
        self.new_beer = 0
        self.new_radler = 0
        self.new_mate = 0
        self.new_pali = 0
        self.new_spezi = 0
Ejemplo n.º 5
0
    def __init__(self, num_leds=32, spidev='/dev/spidev0.0', simulate_mode=False):
        threading.Thread.__init__(self)
        self.logger = logger.Logger('Strand')
        self.terminate = False
        self.lock = threading.Lock()
        self.update_event = threading.Event()

        if num_leds < 1:
            raise InputError('num_leds must be greater than zero')
        self.num_leds = num_leds
        self.sleep_interval_s = 0.030
        if simulate_mode:
            self.sleep_interval_s = 3.000
        self.simulate_mode = simulate_mode
        self.spidev = spidev
        self.spi = None

        self.gamma = bytearray(256)
        for i in range(256):
            # Color calculations from http://learn.adafruit.com/light-painting-with-raspberry-pi
            self.gamma[i] = 0x80 | int(pow(float(i) / 255.0, 2.5) * 127.0 + 0.5)
        self.led_colour = [bytearray(3) for x in range(self.num_leds)]
        self.buffer = [[0.0, 0.0, 0.0] for x in range(self.num_leds)]
        self.blink = [False for x in range(self.num_leds)]
        self.blink_step = [[0.0, 0.0, 0.0] for x in range(self.num_leds)]
        self.blink_direction = [True for x in range(self.num_leds)]

        if not self.simulate_mode:
            self.spi = open(self.spidev, 'wb')
        self.fill(0, 0, 0)

        signal.signal(signal.SIGTERM, self._handle_signals)
        signal.signal(signal.SIGINT, self._handle_signals)
Ejemplo n.º 6
0
    def __init__(self, socket, server, parent=None):
        super(Connection, self).__init__(parent)
        self.logger = logger.Logger(self.__class__.__name__, logger.DEBUG)

        self.socket = socket
        self.server = server

        self.thread = None
Ejemplo n.º 7
0
    def __init__(self, ip="", port=5555):
        super(Server, self).__init__()
        self.logger = logger.Logger(self.__class__.__name__)

        self.ip = ip
        self.port = port

        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        self.connections = []
Ejemplo n.º 8
0
 def __init__(self, jobs, translator, first_job_as_trigger=True, sound_player=None):
     self.logger = logger.Logger('JenkinsAwsSqsMonitor')
     self.translator = translator
     self.first_job_as_trigger = first_job_as_trigger
     self.sound_player = sound_player
     self.pipeline = jobs
     tmplist = list(list_utils.flatten_list(jobs))
     self.jobs = dict.fromkeys(tmplist)
     # initialize status to Unknown state
     for name in self.jobs:
         self.jobs[name] = job2light_translator.STATUS.UNKNOWN
Ejemplo n.º 9
0
    def __init__(self, ip=None, port=None):
        super(Client, self).__init__()
        self.logger = logger.Logger(self.__class__.__name__, logger.DEBUG)

        self.host = ip or socket.gethostname()
        self.port = port or 5555

        self.socket = socket.socket()

        self.listening_thread = ListeningThread(self)
        self.listening_thread.message_received.connect(self._process_message)
Ejemplo n.º 10
0
 def __init__(self,
              monitor,
              sqs_region,
              sqs_queue_name,
              aws_access_key_id=None,
              aws_secret_access_key=None):
     self.logger = logger.Logger('AwsSqsPoller')
     self.sqs_region = sqs_region
     self.sqs_queue_name = sqs_queue_name
     self.aws_access_key_id = aws_access_key_id
     self.aws_secret_access_key = aws_secret_access_key
     self.monitor = monitor
Ejemplo n.º 11
0
    def __init__(self, jobs, strand):
        self.logger = logger.Logger('JenkinsPoller')
        self.strand = strand

        # order of the jobs is important
        self.jobs = list(list_utils.flatten_list(jobs))
        if len(self.jobs) == 0 or len(self.jobs) > self.strand.num_leds:
            raise InputError('Unable to map ' + str(len(self.jobs)) + ' jobs to ' + str(self.strand.num_leds) + ' LEDs')
        self.offset = dict.fromkeys(self.jobs)
        self.leds_per_job = int(self.strand.num_leds / len(self.jobs))

        index = self.leds_per_job * len(self.jobs)
        for name in self.jobs:
            index = index - self.leds_per_job
            self.offset[name] = index
Ejemplo n.º 12
0
    def __init__(self, config_file='config.json'):
        self.logger = logger.Logger('JsonConfig')
        self.config_file = config_file

        f = open(self.config_file, 'r')
        self.logger.log('Reading config file: %s', self.config_file)
        self.config = json.load(
            f, object_hook=json_custom_decode.decode_unicode_to_str_dict)
        f.close()

        for item in JsonConfig.mandatory_items:
            if not self.config.has_key(item):
                raise ConfigError('\"' + item + '\" not found in config file.')
        if not self.config['api'].has_key('type'):
            raise ConfigError('api \"type\" not found in config file.')
        if not self.config['light'].has_key('type'):
            raise ConfigError('light \"type\" not found in config file.')
        if not list_utils.list_items_unique(self.config['jobs']):
            raise ConfigError('jobs must be unique.')
Ejemplo n.º 13
0
import sys
import lib.accuracy
import lib.load
import lib.logger as lg
import lib.split
import lib.summary
import lib.predict
import lib.write

__author__ = "H.D. 'Chip' McCullough IV"

if __name__ == '__main__':
    log = lg.Logger("NBC", "main",
                    '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    try:
        log.logger.info("Loading data set from {0}".format(sys.argv[1]))
        dataset = lib.load.loadCSV(
            sys.argv[1])  # Load input from command line into NBC
        log.logger.info("Splitting data set using default parameters")
        train, test = lib.split.splitDataSet(dataset)  # Split data set
        log.logger.info("Summarizing training data")
        summaries = lib.summary.classSummary(train)  # Summarize training data
        log.logger.info("Predict probabilities of testing data")
        predictions = lib.predict.getPredictions(
            summaries, test)  # Estimate probabilities based on training set
        log.logger.info("Estimating accuracy of predictions")
        accuracy = lib.accuracy.accuracy(
            test, predictions)  # Calculate accuracy of model
        log.logger.info(
            "The model displayed {0}% accuracy when predicting class variables."
            .format(accuracy))
import lib.logger as lg

__author__ = "H.D. 'Chip' McCullough IV"

log = lg.Logger("NBC.separate", "separateClasses",
                '%(asctime)s - %(name)s - %(levelname)s - %(message)s')


def separateClasses(data):
    """
    Separate param:data by class variable, which is the last variable in the array of floats.
    :param data: data to be separated by class variable
    :return: dict{"classVar0": data, ..., "classVarN: data}
    """
    log.logger.info("Initializing empty dictionary")
    classMap = {}  # Initialize empty dictionary
    log.logger.info("Iterating through the data")
    for i in range(0, len(data)):  # Iterate through data
        vec = data[i]  # Pull a line from the data
        if vec[-1] not in classMap:  # Check if class variable has been mapped
            log.logger.info(
                "Adding class variable {0} to the dictionary".format(vec[-1]))
            classMap[vec[-1]] = []  # If it hasn't, add it to the map
        classMap[vec[-1]].append(
            vec)  # Add the line to the appropriate mapping
    log.logger.info("Done -- Returning data separated by class variables")
    return classMap
Ejemplo n.º 15
0
import math
import lib.logger as lg

__author__ = "H.D. 'Chip' McCullough IV"

log = lg.Logger("NBC.gaussian", "gaussian",
                '%(asctime)s - %(name)s - %(levelname)s - %(message)s')


def gaussian(x, mu, sigma):
    """
    Estimate probability of param:x based on Normal (Gaussian) distribution.
    :param x: Random Variable
    :param mu: Expected Value
    :param sigma: Standard Deviation
    :return: Probability (float)
    """
    log.logger.info("Gaussian: Estimating probability")
    exp = math.exp(-(math.pow(x - mu, 2) / (2 * math.pow(sigma, 2))))
    probability = (1 / (math.sqrt(2 * math.pi) * sigma)) * exp
    log.logger.info("Gaussian: Done -- Returning estimated probability")
    return probability
Ejemplo n.º 16
0
def main(vcf, data_source, sample_name, genes, popfreq, get_cnvs, cu, cl,
         get_fusions, fusion_threshold, outdir, keep_intermediate_files,
         noanno, rave_report, nocheck):

    global outdir_path, debug, verbose, log

    # Allow gzipped or bgzipped files to be processed. Since downstream helper
    # scripts in different languages and whatnot, just decompress for this
    # purpose and then dump the extra copy. Most files won't take up so much
    # file space that this is a real issue.
    gzipped_vcf = False
    if 'gzip' in subprocess.check_output(['file', vcf]).decode('utf-8'):
        gzipped_vcf = True
        vcf = utils.gunzip_vcf(vcf)

    if sample_name is None:
        sample_name = get_name_from_vcf(vcf)

    # Set up the logger.
    if verbose:
        debug = True
    level = 'debug' if debug else 'error'
    logfile = 'moma_reporter_{}_{}.log'.format(sample_name, utils.today())

    # By default logger is set to quiet. If we want both logfile and stdout
    # output, then change this arg.
    log = logger.Logger(loglevel=level,
                        colored_output=True,
                        dest=logfile,
                        quiet=quiet)

    # Get some usage stats
    cmd = [os.path.join(scripts_dir, 'usage.sh')]
    run(cmd, 'Collect usage information')

    if not os.path.exists(vcf):
        log.write_log(
            'error', f'VCF file {vcf} can not be processed! '
            'No such file or directory!')
        sys.exit(1)

    # Write out welcome and header
    pipeline_version = ''
    with open(os.path.join(package_root, '_version.py')) as fh:
        pipeline_version = fh.readline().rstrip("'\n'").split("'")[1]
    welcome_str = (
        '{0}\n:::::  Running the MoCha Oncogenic Mutation Annotator '
        '(MOMA) pipeline - v{1}  :::::\n{0}\n'.format('=' * 97,
                                                      pipeline_version))
    log.write_log('header', welcome_str)

    # Verify the VCF source is correct for the VCF that we've loaded.
    if nocheck:
        log.write_log(
            'warn', f"Passing VCF of type '{data_source}' without "
            'verification.')
    data_source = __verify_vcf(vcf, data_source, noanno, nocheck)

    if debug or noanno:
        log.write_log(
            'unformatted', '\n\u001b[33m{decor}  TEST VERSION!  {decor}'
            '\u001b[0m\n\n'.format(decor='=' * 25))

    log.write_log('info', f'Processing sample: {sample_name}')

    if noanno:
        log.write_log(
            'unformatted',
            '\u001b[33m\t\t===>  Running without Annovar annotation  <===\u001b[0m\n\n'
        )
        annovar_file = vcf
        outdir_path = os.getcwd()
    else:
        if outdir is None:
            outdir_path = os.path.join(outdir_path, f'{sample_name}_out')
        else:
            outdir_path = os.path.join(outdir_path, outdir)

        log.write_log('info',
                      f'Selected destination dir for data is: {outdir_path}')

        if not os.path.exists(outdir_path):
            os.mkdir(os.path.abspath(outdir_path), 0o755)

        # Simplify the VCF
        if data_source == 'oca':
            log.write_log('info', 'Simplifying the VCF file.')
            num_vars, simple_vcf = simplify_vcf(vcf, outdir_path, 'ion')
            log.write_log(
                'info', 'Done simplifying VCF file. There are %s '
                'variants in this specimen.' % str(num_vars))
        elif data_source == 'wes_mutect':
            log.write_log(
                'info', 'MuTect2 Tumor / Normal run detected. Need '
                'to remove normal data from the VCF.')
            num_vars, simple_vcf = simplify_vcf(vcf, outdir_path, 'mutect')
            log.write_log(
                'info', 'Done simplifying VCF file. There are %s '
                'somatic variants in this specimen.' % str(num_vars))
        elif data_source == 'wes_strelka':
            log.write_log(
                'info', 'Strelka2 run detected. Need to pre-process '
                'the data.')
            num_vars, simple_vcf = simplify_vcf(vcf, outdir_path, 'strelka')
            log.write_log(
                'info', 'Done pre-processing VCF. There are {} '
                'somatic variants in this specimen.'.format(str(num_vars)))
        else:
            log.write_log('info', 'VCF already ready for processing with '
                          'Annovar.')
            simple_vcf = vcf

        # Run Mutational Signature QC to determine Ts/Tv and deamination score.
        log.write_log(
            'info', 'Generating Ts/Tv, Deamination Score, and '
            'SBS-6 information for sample.')
        outfile = f'{outdir_path}/{sample_name}_sbs_metrics.csv'
        sbs_input_vcf = simple_vcf if data_source != 'oca' else vcf
        run_var_sig(sbs_input_vcf, data_source, outfile)

        # Annotate the vcf with ANNOVAR.
        log.write_log('info', 'Annotating the simplified VCF file with '
                      'Annovar.')
        annovar_file = run_annovar(simple_vcf, sample_name)

    # Implement the MOMA here.
    log.write_log(
        'info', 'Running OncoKB Filter rules on data to look for '
        'oncogenic variants.')
    oncokb_annotated_data = oncokb_annotate(annovar_file, data_source, popfreq)

    # Generate a filtered CSV file of results for the report.
    mutation_report = os.path.join(
        outdir_path, f'{sample_name}_mocha_snv_indel_report.csv')
    log.write_log('info', f'Writing report data to {mutation_report}.')
    generate_report(oncokb_annotated_data, genes, mutation_report)

    # Generate a CNV report if we're asking for one.
    cnv_report = None
    oncokb_cnv_data = []
    if get_cnvs:
        log.write_log(
            'info', f"Generating a CNV report for sample '{sample_name}'.\n")
        cnv_report = os.path.join(outdir_path,
                                  f'{sample_name}_mocha_cnv_report.csv')
        log.write_log('info', f'Writing report data to {cnv_report}.')

        # We need different files depending on the assay.
        cnv_data_file = ''
        if data_source == 'oca':
            cnv_data_file = vcf
        elif data_source == 'tso500':
            cnv_data_file = '{}.cnv.fc.txt'.format(vcf.replace('.vcf', ''))

        if not os.path.exists(cnv_data_file):
            log.write_log(
                'error', f'CNV file "{cnv_data_file}" can not be found.'
                'Make sure the file is in the same location as the VCF.')
            sys.exit(1)

        oncokb_cnv_data = gen_cnv_report(cnv_data_file, cu, cl, genelist,
                                         cnv_report, data_source)
        log.write_log('info', 'Done with CNV report.')

    # Generate a Fusions report if we've asked for one.
    fusion_report = None
    oncokb_fusion_data = []
    if get_fusions:

        units = '%' if data_source == 'tso500' else ' reads'

        log.write_log(
            'info', 'Generating a Fusions report for sample {}. Using '
            'threshold of {}{}.'.format(sample_name, fusion_threshold, units))
        fusion_report = os.path.join(outdir_path,
                                     f'{sample_name}_mocha_fusion_report.csv')
        log.write_log('info', f'Writing report data to {fusion_report}.')

        if data_source == 'oca':
            fusion_data_file = vcf
        elif data_source == 'tso500':
            fusion_data_file = '{}.fusion.txt'.format(vcf.replace('.vcf', ''))

        oncokb_fusion_data = gen_fusion_report(fusion_data_file,
                                               fusion_threshold, genelist,
                                               fusion_report)
        log.write_log('info', "Done with Fusions report.")

    # Combine the three reports into one master report.
    moma_report = combine_reports(sample_name, mutation_report, cnv_report,
                                  fusion_report, outdir_path)

    # If we need a Rave report, generate one now.
    if rave_report:
        log.write_log(
            'info', 'Generating a CSV file that can be uploaded '
            'into Theradex Rave.')
        run_moma2rave(moma_report, outdir_path, rave_report)

    # Generate a JSON blob of data for databasing and other purposes
    json_out = os.path.join(outdir_path, f'{sample_name}_moma_data.json')
    __jsonify_moma_data(sample_name,
                        snv_data=oncokb_annotated_data,
                        cnv_data=oncokb_cnv_data,
                        fusion_data=oncokb_fusion_data,
                        outfile=json_out)

    # Clean up and move the logfile to data dir.
    contents = [os.path.join(outdir_path, f) for f in os.listdir(outdir_path)]
    if not keep_intermediate_files:
        for f in contents:
            if any(
                    f.endswith(x)
                    for x in ('truncmaf', 'avinput', 'oncokb.maf',
                              'simple.vcf', 'snv_indel_report.csv',
                              'cnv_report.csv', 'fusion_report.csv')):
                log.write_log('debug', f'Removing {f}.')
                os.remove(f)

    # If we deompresssed the VCF for this run, get rid of the decompressed file
    # to save space
    if gzipped_vcf is True:
        print('removing decomp vcf.')
        log.write_log('debug', 'Removing decompressed VCF.')
        os.remove(vcf)

    # Move our logfile into the output dir now that we're done.
    shutil.move(os.path.abspath(logfile), os.path.join(outdir_path, logfile))

    log.write_log(
        'info', 'MoCha OncoKB Annotator Pipeline completed '
        'successfully! Data can be found in %s.' % outdir_path)

    if debug:
        sys.stderr.write('\u001b[33m{decor}\u001b[0m\n'.format(decor='=' * 67))
        sys.exit()
import math
import lib.logger as lg

__author__ = "H.D. 'Chip' McCullough IV"

log = lg.Logger("NBC.statistics", "stats",
                '%(asctime)s - %(name)s - %(levelname)s - %(message)s')


def mean(nums):
    """
    Calculate Expected Value of param:nums
    :param nums: Numbers to find Expected Value of
    :type nums: float[]
    :return: Expected Value (float)
    """
    log.logger.info("Mean: Calculating Expected Value")
    numerator = sum(nums)  # Sum the entries of param:nums
    denominator = float(len(nums))  # Count the number of entries in param:nums
    log.logger.info("Mean: Done -- Returning Expected Value")
    return numerator / denominator


def var(nums):
    """
    Calculate Variance of param:nums using N-1 formula
    :param nums: Numbers to find Variance of
    :type nums: float[]
    :return: Variance (float)
    """
    log.logger.info("Variance: Calculating Variance")
Ejemplo n.º 18
0
    # Set current state of air controller and declare the time we last sent a
    # state update to the ground station
    state = State()
    state_last_sent = 0

    # Timing / counting variables
    time_chute_deployed = 0
    freefall_counter = 0
    apogee_counter = 0

    ###########################################################################
    ## Initialize our external devices
    ###########################################################################

    # Define logger but don't initialize a new log file here
    logger = lgr.Logger(init_log=False, init_camera=False, init_debug=True)

    # Define debug function
    def debug(text):
        if LOG_DEBUG: logger.write(text, lgr.DEBUG)

    # Initialize telemetry radio for communication with ground station
    radio = Telemetry()
    debug("Initialized telemetry.")

    # Initialize the IMU and barometer sensors so that we can read from them
    sensor = Sensor()
    debug("Initialized sensor.")
    sensor.start()  # start reading from IMU in a new thread

    # Initialize the GPIO pins so that we can write them high or low
Ejemplo n.º 19
0
 def __init__(self, sound_clips_directory, player_bin='mpg321'):
     self.logger = logger.Logger('SoundPlayer')
     self.sound_clips_directory = sound_clips_directory
     self.player_bin = player_bin
     self.player_proc = None
Ejemplo n.º 20
0
from lib import logger
import time

log = logger.Logger("../Log")

log.log("Some text")
log.log("More text in red", "error")
log.log("Even more text in cyan", "info")
log.log("Text in yellow", "warning")

time.sleep(10)
log.stop()
Ejemplo n.º 21
0
from motor.motor_asyncio import AsyncIOMotorClient
from lib import logger as _logger

import json
import os
import praw

with open(os.path.join(os.getcwd(), "data", "config.json"), "rb") as f:
    config = json.load(f)

redditConfig = config['apis']['reddit']
client = AsyncIOMotorClient(
    f"mongodb+srv://{config['database']['user']}:{config['database']['password']}@aprime-tnuy3.mongodb.net/test?retryWrites=true&w=majority"
)
db = client.aprime
logger = _logger.Logger(loggingFile=os.path.join(os.getcwd(), "data",
                                                 "main.log"),
                        database=db)
reddit = praw.Reddit(client_id=redditConfig['client_id'],
                     client_secret=redditConfig['client_secret'],
                     user_agent=redditConfig['user_agent'],
                     username=redditConfig['username'],
                     password=redditConfig['password'])
Ejemplo n.º 22
0
 def __init__(self):
     self._client = bot.Bot()
     self._json_file = jsonfile.JSONFile('config.json')
     self._bot_config = self._json_file.get_json_file()
     self._token = self._bot_config['token']
     self._logger = logger.Logger('astarotte.py')
Ejemplo n.º 23
0
import sys
sys.path.append(current_dir)

import signal
import getopt
import importlib

from lib import daemonize
from lib import logger
from lib import list_utils
from lib.constants import STATUS
from config import json_config
from lights import job2ledstrip

default_config_file = 'config.json'
dlogger = logger.Logger('light_controller')
light = None


class LightController:
    def _write_pid(self, filename):
        global dlogger

        try:
            pidfile = open(filename, "w")
            pidfile.write("%d\n" % os.getpid())
            pidfile.close()
        except IOError, e:
            dlogger.log("ERROR: unable to write pid file %s: %s" %
                        (filename, str(e)))
Ejemplo n.º 24
0
 def __init__(self, url, monitor):
     self.logger = logger.Logger('JenkinsPoller')
     self.url = url
     self.monitor = monitor
Ejemplo n.º 25
0
 def __init__(self, bot):
     self._bot = bot
     self._logger = logger.Logger('owner.py')
Ejemplo n.º 26
0
import lib.logger as lg

__author__ = "H.D. 'Chip' McCullough IV"

log = lg.Logger("NBC.accuracy", "accuracy",
                '%(asctime)s - %(name)s - %(levelname)s - %(message)s')


def accuracy(testSet, predictions):
    """
    Determine model accuracy based on test data set class variables and correlating predicted class variables
    :param testSet: Test set used to estimate predictions
    :param predictions: Class predictions
    :return: Accuracy (float)
    """
    log.logger.info("Accuracy: Running accuracy checks against test set")
    num_correct = 0
    for x in range(0, len(testSet)):
        if testSet[x][-1] == predictions[x]:
            num_correct += 1
            log.logger.info("Accuracy: Number correct increased to {0}".format(
                num_correct))
    acc = (num_correct / float(len(testSet))) * 100.0
    log.logger.info("Accuracy: Done -- Returning accuracy of model")
    return acc
Ejemplo n.º 27
0
 def __init__(self, api_token, username, endpoint=None):
     self.client = CircleClient(api_token, endpoint)
     self.username = username
     self.logger = logger.Logger('circle_ci')
import lib.gaussian
import lib.logger as lg

__author__ = "H.D. 'Chip' McCullough IV"

log = lg.Logger("NBC.probability", "classProbability",
                '%(asctime)s - %(name)s - %(levelname)s - %(message)s')


def classProbabilities(summary, inputVec):
    """
    Estimate class probabilities using lib.gaussian.gaussian()
    :param summary: Summary (mean, variance, st.dev) dictionary
    :type summary: dict
    :param inputVec: input row of data
    :type inputVec: array
    :return: Probabilities dict{"class": float[]}
    """
    log.logger.info("classProbabilities: Initializing probability dictionary")
    probabilities = {}
    log.logger.info("classProbabilities: Estimating probabilities")
    for classValue, classSummary in summary.items():
        probabilities[classValue] = 1
        for i in range(0, len(classSummary)):
            mean, var, stdev = classSummary[i]
            x = inputVec[i]
            probabilities[classValue] *= lib.gaussian.gaussian(x, mean, stdev)
    log.logger.info(
        "classProbabilities: Done -- Returning probabilities by class")
    return probabilities
Ejemplo n.º 29
0
def main():
    """Startup tasks, mainloop entry, and shutdown tasks.
    """
    # Load the configuration.
    config = _config.ConfigManager(single=False)
    builtins.CONFIG = config

    print("Welcome to {0}, Multi-Player Server.".format(_config.VERSION))
    print("Starting up...")

    # Initialize the logger.
    logger.init(config)
    log = logger.Logger("server")

    # Rotate database backups, if enabled.
    # Unfortunately this has to be done before loading the database, because Windows.
    if os.path.exists(config["database"]["filename"]):
        try:
            if config["database"]["backups"]:
                backupnumbers = sorted(range(1, config["database"]["backups"]),
                                       reverse=True)
                for bn in backupnumbers:
                    if os.path.exists("{0}.bk{1}".format(
                            config["database"]["filename"], bn)):
                        shutil.copyfile(
                            "{0}.bk{1}".format(config["database"]["filename"],
                                               bn),
                            "{0}.bk{1}".format(config["database"]["filename"],
                                               bn + 1))
                shutil.copyfile(
                    config["database"]["filename"],
                    "{0}.bk1".format(config["database"]["filename"]))
        except:
            log.error("Could not finish rotating backups for database: {file}",
                      file=config["database"]["filename"])
            log.error(traceback.format_exc(1))

    # Initialize the Database Manager and load the world database.
    log.info("Initializing database manager...")
    dbman = database.DatabaseManager(config["database"]["filename"],
                                     config.defaults)
    _dbres = dbman._startup()
    if not _dbres:
        # On failure, only remove the lockfile if its existence wasn't the cause.
        if _dbres is not None:
            dbman._unlock()
        return 3
    log.info("Finished initializing database manager.")

    # Initialize the router.
    router = Router(config, dbman)

    # initialize the command shell.
    command_shell = shell.Shell(dbman, router)
    router.shell = command_shell

    # Start the services.
    log.info("Initializing services...")
    if not init_services(config, router, log):
        dbman._unlock()
        return 4
    log.info("Finished initializing services.")

    # Graceful shutdown on SIGINT (ctrl-c).
    # The shutdown command does the same thing.
    # To shut down quickly but cleanly, send the TERM signal.
    def shutdown(signal_received, frame):
        if not router.shutting_down:
            if config["shutdown_delay"]:
                command_shell.broadcast(
                    "<<<DENNIS IS SHUTTING DOWN IN {0} SECONDS>>>".format(
                        config["shutdown_delay"]))
            else:
                command_shell.broadcast("<<<DENNIS IS SHUTTING DOWN>>>")
            reactor.callLater(config["shutdown_delay"], reactor.stop)
            router.shutting_down = True

    signal.signal(signal.SIGINT, shutdown)

    # Start the Twisted Reactor.
    log.info("Finished startup tasks.")
    router._reactor = reactor
    reactor.run()

    # Shutting down.
    dbman._unlock()
    print("End Program.")
    return 0
Ejemplo n.º 30
0
 def __init__(self, bot):
     self._bot = bot
     self._logger = logger.Logger('startup.py')