<commit_before>import smbus
import time
import pygame
from gpiozero import DistanceSensor
import const
from os import sys

print(const.projectName)

# for RPI version 1, use "bus = smbus.SMBus(0)"
bus = smbus.SMBus(1)

# This is the address we setup in the Arduino Program
address = 0x04

stopped = False

distance = 0
manual = True

# Initialise the pygame library
pygame.init()

# Connect to the first JoyStick
j = pygame.joystick.Joystick(0)
j.init()

ultrasonic = DistanceSensor(echo=17, trigger=4, max_distance=4)

def writeNumber(value):
  bus.write_byte(address, value)
  # bus.write_byte_data(address, 0, value)
  return -1

def readNumber():
  number = bus.read_byte(address)
  # number = bus.read_byte_data(address, 1)
  return number

def setSpeed(speed):
    writeNumber(speed)
    time.sleep(0.1)

def getJoystickXValue():
    events = pygame.event.get()
    for event in events:
        if event.type == pygame.JOYAXISMOTION:
            if event.axis == 1:
                value = event.value
    return value

def manualDrive():
    driveV = getJoystickXValue()

    driveV = int(driveV * 128) * -1
    driveV = driveV + 75
    if driveV > 128:
        driveV = 128

    return driveV

def cruiseControl():
    stopDif = const.cruiseMaxStopDistance - const.cruiseMinStopDistance
    stopDistance = (currentSpeed - const.motorZeroSpeed) * 14.8148148148

    if stopDistance < const.cruiseMinStopDistance:
        stopDistance = const.cruiseMinStopDistance
    if stopDistance > const.cruiseMaxStopDistance:
        stopDistance = const.cruiseMaxStopDistance

    distance = ultrasonic.distance

    if distance < stopDistance:
        driveV = const.motorZeroSpeed
    elif distance <= 4 and distance > stopDistance:
        driveV = int(distance/0.3) + const.motorZeroSpeed
    else:
        if driveV + const.cruiseSpeedIncrement < const.cruiseTopSpeed:
            driveV += const.cruiseSpeedIncrement

    return driveV

def stopDrive():
    stopped = True
    writeNumber(0)
    print("Stopping ...")
    j.quit()
    pygame.quit()
    sys.exit()

def startDrive():
    try:
        while not stopped:
            if not manual:
                driveV = cruiseControl()
            else:
                driveV = manualDrive()

            if not driveV and driveV is not 0:
                continue

            if driveV > const.motorMaxSpeed:
                setSpeed(const.motorMaxSpeed)
                continue

            if driveV >= const.motorZeroSpeed:
      	        setSpeed(driveV)

            if j.get_button(3):
                manual = True

            if j.get_button(16):
                stopDrive()
    except KeyboardInterrupt:
        writeNumber(0)
        j.quit()#!/usr/bin/env python
        pygame.quit()
<commit_msg>global variables added<commit_after>import smbus
import time
import pygame
from gpiozero import DistanceSensor
import const
from os import sys

print(const.projectName)

# for RPI version 1, use "bus = smbus.SMBus(0)"
bus = smbus.SMBus(1)

# This is the address we setup in the Arduino Program
address = 0x04

stopped = False

distance = 0
manual = True

# Initialise the pygame library
pygame.init()

# Connect to the first JoyStick
j = pygame.joystick.Joystick(0)
j.init()

ultrasonic = DistanceSensor(echo=17, trigger=4, max_distance=4)

def writeNumber(value):
  bus.write_byte(address, value)
  # bus.write_byte_data(address, 0, value)
  return -1

def readNumber():
  number = bus.read_byte(address)
  # number = bus.read_byte_data(address, 1)
  return number

def setSpeed(speed):
    writeNumber(speed)
    time.sleep(0.1)

def getJoystickXValue():
    events = pygame.event.get()
    for event in events:
        if event.type == pygame.JOYAXISMOTION:
            if event.axis == 1:
                value = event.value
    return value

def manualDrive():
    driveV = getJoystickXValue()

    driveV = int(driveV * 128) * -1
    driveV = driveV + 75
    if driveV > 128:
        driveV = 128

    return driveV

def cruiseControl():
    stopDif = const.cruiseMaxStopDistance - const.cruiseMinStopDistance
    stopDistance = (currentSpeed - const.motorZeroSpeed) * 14.8148148148

    if stopDistance < const.cruiseMinStopDistance:
        stopDistance = const.cruiseMinStopDistance
    if stopDistance > const.cruiseMaxStopDistance:
        stopDistance = const.cruiseMaxStopDistance

    distance = ultrasonic.distance

    if distance < stopDistance:
        driveV = const.motorZeroSpeed
    elif distance <= 4 and distance > stopDistance:
        driveV = int(distance/0.3) + const.motorZeroSpeed
    else:
        if driveV + const.cruiseSpeedIncrement < const.cruiseTopSpeed:
            driveV += const.cruiseSpeedIncrement

    return driveV

def stopDrive():
    global stopped
    stopped = True
    writeNumber(0)
    print("Stopping ...")
    j.quit()
    pygame.quit()
    sys.exit()

def startDrive():
    global stopped
    global manual
    try:
        while not stopped:
            if not manual:
                driveV = cruiseControl()
            else:
                driveV = manualDrive()

            if not driveV and driveV is not 0:
                continue

            if driveV > const.motorMaxSpeed:
                setSpeed(const.motorMaxSpeed)
                continue

            if driveV >= const.motorZeroSpeed:
      	        setSpeed(driveV)

            if j.get_button(3):
                manual = True

            if j.get_button(16):
                stopDrive()
    except KeyboardInterrupt:
        writeNumber(0)
        j.quit()#!/usr/bin/env python
        pygame.quit()
<|endoftext|>


<commit_before>import bohrium as np
import bohrium.examples.jacobi_stencil as js
import util

B = util.Benchmark()
H = B.size[0]
W = B.size[1]
I = B.size[2]

ft = js.freezetrap(H,W,dtype=B.dtype,bohrium=B.bohrium)

B.start()
#ft = js.solve(ft,max_iterations=I)
ft = js.iterate(ft, I)
B.stop()
B.pprint()
<commit_msg>benchmark-jacoby-py: Added use of the verbose flag.<commit_after>import bohrium as np
import bohrium.examples.jacobi_stencil as js
import util

B = util.Benchmark()
H = B.size[0]
W = B.size[1]
I = B.size[2]

ft = js.freezetrap(H,W,dtype=B.dtype,bohrium=B.bohrium)

B.start()
#ft = js.solve(ft,max_iterations=I)
ft = js.iterate(ft, I)
B.stop()
if B.verbose:
    print ft
B.pprint()
<|endoftext|>


<commit_before>#!/bin/env python
#
# qc_report.py: generate report file for qc run
#
import sys
import os
import optparse

# Put ../share onto Python search path for modules
SHARE_DIR = os.path.abspath(
    os.path.normpath(
        os.path.join(os.path.dirname(sys.argv[0]),'..','share')))
sys.path.append(SHARE_DIR)
try:
    import Pipeline
except ImportError, ex:
    print "Error importing modules: %s" % ex
    print "Check PYTHONPATH"
    sys.exit(1)

class QCReport:

    def __init__(self,dirn):
        """Make a new QCReport instance
        """
        self.__dirn = dirn
        self.__qc_dir = os.path.join(self.__dirn,'qc')
        self.__samples = []
        # Get primary data files
        primary_data = Pipeline.GetSolidDataFiles(self.__dirn)
        for data in primary_data:
            sample = os.path.splitext(data[0])[0]
            self.__samples.append(QCSample(sample,data[0],data[1]))
        # Get QC files
        if not os.path.isdir(self.__qc_dir):
            print "%s not found" % self.__qc_dir
            return
        qc_files = os.listdir(self.__qc_dir)
        # Associate QC outputs with sample names
        for sample in self.__samples:
            for f in qc_files:
                # Boxplots
                if f.startswith(sample.name) or f.startswith(sample.qual):
                    if f.endswith('_boxplot.png'): sample.addBoxplot(f)
                # Screens
                if f.startswith(sample.name):
                    if f.endswith('_screen.png'): sample.addScreen(f)

    def write(self):
        """Write the report
        """
        for sample in self.__samples:
            print "Sample: %s" % sample
            # Boxplots
            boxplots = sample.boxplots()
            if boxplots:
                print "\tBoxplots:"
                for b in boxplots:
                    print "\t\t%s" % b
            else:
                print "\tNo boxplots found"
            # Screens
            screens = sample.screens()
            if screens:
                print "\tScreens:"
                for s in screens:
                    print "\t\t%s" % s
            else:
                print "\tNo screens found"

    def html(self):
        """Write the HTML report
        """
        html = HTMLPageWriter("QC for %s" % os.path.basename(self.__dirn))
        # Title
        html.add("
QC for %s
" % os.path.basename(self.__dirn))
        # Index
        html.add("
Samples in %s
" % self.__dirn)
        html.add("
")
        for sample in self.__samples:
            html.add("
%s
" % (sample.name,sample.name))
        html.add("
")
        # QC plots etc
        for sample in self.__samples:
            html.add("
%s
" % (sample.name,sample.name))
            html.add("

")
            # Boxplots
            html.add("")
            if sample.boxplots():
                html.add("
Boxplots
")
                for b in sample.boxplots():
                    html.add("" % b)
            else:
                html.add("No boxplots found")
            html.add("	")
            # Screens
            html.add("")
            if sample.screens():
                html.add("
Screens
")
                for s in sample.screens():
                    html.add("\n" % s)
            else:
                html.add("No screens found")
            html.add("	")
            html.add("

")
        html.write(os.path.join(self.__qc_dir,'index.html'))

class QCSample:

    def __init__(self,name,csfasta,qual):
        self.name = name
        self.csfasta = csfasta
        self.qual = qual
        self.__boxplots = []
        self.__screens = []

    def addBoxplot(self,boxplot):
        self.__boxplots.append(boxplot)

    def addScreen(self,screen):
        self.__screens.append(screen)

    def boxplots(self):
        """Return list of boxplots for a sample
        """
        return self.__boxplots

    def screens(self):
        """Return list of screens for a sample
        """
        return self.__screens

class HTMLPageWriter:

    def __init__(self,title=''):
        self.__page_title = str(title)
        self.__content = []
        self.__css_rules = []

    def add(self,content):
        """Add content to page body
        """
        self.__content.append(str(content))

    def addCSSRule(self,css_rule):
        """Add CSS rule
        """
        self.__css_rules.append(str(css_rule))

    def write(self,filen):
        """Write the HTML content to a file
        """
        fp = open(filen,'w')
        fp.write("\n")
        # Header
        fp.write("\n")
        fp.write("<title>%s</title>\n" % self.__page_title)
        # CSS rules
        if self.__css_rules:
            fp.write("\n")
        fp.write("\n")
        # Body and content
        fp.write("\n")
        fp.write('\n'.join(self.__content))
        fp.write("\n")
        # Finish
        fp.write("\n")
        fp.close()

if __name__ == "__main__":
    # Set up command line parser
    p = optparse.OptionParser(usage="%prog [options] DIR [ DIR ...]",
                              description=
                              "Generate QC report for each directory DIR.")

    # Deal with command line
    options,arguments = p.parse_args()

    # Check arguments
    if len(arguments) < 1:
        p.error("Takes at least one argument (one or more directories)")
    else:
        for d in arguments:
            ##QCReport(d).write()
            QCReport(d).html()

<commit_msg>QC-pipeline/qc_report.py: add some styling to the QC report HTML page.<commit_after>#!/bin/env python
#
# qc_report.py: generate report file for qc run
#
import sys
import os
import optparse

# Put ../share onto Python search path for modules
SHARE_DIR = os.path.abspath(
    os.path.normpath(
        os.path.join(os.path.dirname(sys.argv[0]),'..','share')))
sys.path.append(SHARE_DIR)
try:
    import Pipeline
except ImportError, ex:
    print "Error importing modules: %s" % ex
    print "Check PYTHONPATH"
    sys.exit(1)

class QCReport:

    def __init__(self,dirn):
        """Make a new QCReport instance
        """
        self.__dirn = dirn
        self.__qc_dir = os.path.join(self.__dirn,'qc')
        self.__samples = []
        # Get primary data files
        primary_data = Pipeline.GetSolidDataFiles(self.__dirn)
        for data in primary_data:
            sample = os.path.splitext(data[0])[0]
            self.__samples.append(QCSample(sample,data[0],data[1]))
        # Get QC files
        if not os.path.isdir(self.__qc_dir):
            print "%s not found" % self.__qc_dir
            return
        qc_files = os.listdir(self.__qc_dir)
        # Associate QC outputs with sample names
        for sample in self.__samples:
            for f in qc_files:
                # Boxplots
                if f.startswith(sample.name) or f.startswith(sample.qual):
                    if f.endswith('_boxplot.png'): sample.addBoxplot(f)
                # Screens
                if f.startswith(sample.name):
                    if f.endswith('_screen.png'): sample.addScreen(f)

    def write(self):
        """Write the report
        """
        for sample in self.__samples:
            print "Sample: %s" % sample
            # Boxplots
            boxplots = sample.boxplots()
            if boxplots:
                print "\tBoxplots:"
                for b in boxplots:
                    print "\t\t%s" % b
            else:
                print "\tNo boxplots found"
            # Screens
            screens = sample.screens()
            if screens:
                print "\tScreens:"
                for s in screens:
                    print "\t\t%s" % s
            else:
                print "\tNo screens found"

    def html(self):
        """Write the HTML report
        """
        html = HTMLPageWriter("QC for %s" % os.path.basename(self.__dirn))
        # Title
        html.add("
QC for %s
" % os.path.basename(self.__dirn))
        # Add styles
        html.addCSSRule("h1 { background-color: grey; }")
        html.addCSSRule("h2 { background-color: lightgrey; display: inline-block; }")
        html.addCSSRule(".sample { margin: 10 10; border: solid 1px grey; padding: 5px; }")
        html.addCSSRule("td { vertical-align: top; }")
        # Index
        html.add("
Samples in %s
" % self.__dirn)
        html.add("
")
        for sample in self.__samples:
            html.add("
%s
" % (sample.name,sample.name))
        html.add("
")
        # QC plots etc
        for sample in self.__samples:
            html.add("
")
            html.add("
%s
" % (sample.name,sample.name))
            html.add("

")
            # Boxplots
            html.add("")
            if sample.boxplots():
                html.add("
Boxplots
")
                for b in sample.boxplots():
                    html.add("" % b)
            else:
                html.add("No boxplots found")
            html.add("	")
            # Screens
            html.add("")
            if sample.screens():
                html.add("
Screens
")
                for s in sample.screens():
                    html.add("" % s)
            else:
                html.add("No screens found")
            html.add("	")
            html.add("

")
            html.add("
")
        html.write(os.path.join(self.__qc_dir,'index.html'))

class QCSample:

    def __init__(self,name,csfasta,qual):
        self.name = name
        self.csfasta = csfasta
        self.qual = qual
        self.__boxplots = []
        self.__screens = []

    def addBoxplot(self,boxplot):
        self.__boxplots.append(boxplot)

    def addScreen(self,screen):
        self.__screens.append(screen)

    def boxplots(self):
        """Return list of boxplots for a sample
        """
        return self.__boxplots

    def screens(self):
        """Return list of screens for a sample
        """
        return self.__screens

class HTMLPageWriter:

    def __init__(self,title=''):
        self.__page_title = str(title)
        self.__content = []
        self.__css_rules = []

    def add(self,content):
        """Add content to page body
        """
        self.__content.append(str(content))

    def addCSSRule(self,css_rule):
        """Add CSS rule
        """
        self.__css_rules.append(str(css_rule))

    def write(self,filen):
        """Write the HTML content to a file
        """
        fp = open(filen,'w')
        fp.write("\n")
        # Header
        fp.write("\n")
        fp.write("<title>%s</title>\n" % self.__page_title)
        # CSS rules
        if self.__css_rules:
            fp.write("\n")
        fp.write("\n")
        # Body and content
        fp.write("\n")
        fp.write('\n'.join(self.__content))
        fp.write("\n")
        # Finish
        fp.write("\n")
        fp.close()

if __name__ == "__main__":
    # Set up command line parser
    p = optparse.OptionParser(usage="%prog [options] DIR [ DIR ...]",
                              description=
                              "Generate QC report for each directory DIR.")

    # Deal with command line
    options,arguments = p.parse_args()

    # Check arguments
    if len(arguments) < 1:
        p.error("Takes at least one argument (one or more directories)")
    else:
        for d in arguments:
            ##QCReport(d).write()
            QCReport(d).html()

<|endoftext|>


<commit_before>import logging

import numpy as NP
import pandas as PD

from repository import get_data_frame, get_root
from ..util.date import toJ2000

"""
J. J. Love and J. L. Gannon, "Revised Dst and the epicycles of
magnetic disturbance: 1958--2009", Ann. Geophys., vol 27,
pp. 3101--3131, 2009.
"""

SAMPLES = {'min': 60 * 24}
"""
Mapping between the number of samples per day for a given sampling
period.
"""

def quiet_days(series,
               n_days=5,
               period='min'):
    """
    Given a pandas time series *series*, return a mapping between
    months and the *n_days* quietest days for that month. See (4) of
    Love and Gannon. The parameter *period* gives the sampling period
    (`'min'` = 1 measurement per minute).
    """
    quiet_day_map = {}
    delta_H_i = series.diff().abs().\
                groupby(PD.TimeGrouper(freq='D')).\
                filter(lambda x: x.isnull().sum() <= int(0.5 * SAMPLES[period])).\
                groupby(PD.TimeGrouper(freq='D')).mean()
    for month, delta_H_i_month in delta_H_i.groupby(PD.TimeGrouper(freq='M')):
        quiet_day_map[month] = delta_H_i_month.nsmallest(n_days).index
    return quiet_day_map

def chebyshev_fit(series,
                  quiet_day_map,
                  deg=20):
    """
    ???
    """
    fit_map = {}
    grouped_by_day = series.groupby(PD.TimeGrouper(freq='D'))
    for month_end in sorted(quiet_day_map):
        x = []
        y = []
        for quiet_day in quiet_day_map[month_end]:
            quiet_day_H = grouped_by_day.get_group(quiet_day)
            quiet_day_H = quiet_day_H[quiet_day_H.notnull()]
            x.extend([toJ2000(time_stamp.to_datetime()) for time_stamp in quiet_day_H.index])
            y.extend(quiet_day_H.values)
        fit_map[month_end] = NP.polynomial.chebyshev.chebfit(x, y, deg, full=True)
    return fit_map

def external_field_variation(series,
                             fit_map):
    """
    ???
    """
    E_series_list = []
    for month, group in series.groupby(PD.TimeGrouper(freq='M')):
        # NEED TO DO FIT QUALITY CONTROL!!!
        coeffs, _ = fit_map[month]
        j2000 = [toJ2000(time_stamp.to_datetime()) for time_stamp in group.index]
        poly_val = NP.polynomial.chebyshev.chebval(j2000, coeffs)
        # E_group = group.values - poly_val
        E_group = poly_val
        E_series_list.append(PD.Series(index=group.index, data=E_group))
    return PD.concat(E_series_list)

if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO)

    root = get_root()

    dataframe, _ = get_data_frame(root,
                                  'frd',
                                  0,
                                  columns=['time', 'H'],
                                  years=[2002])
    series = PD.Series(index=dataframe.time,
                       data=dataframe.H)

    quiet_day_map = quiet_days(series)

    fit_map = chebyshev_fit(series, quiet_day_map)

    E_series = external_field_variation(series,
                                        fit_map)

    # print(len(series))
    # print(len(E_series))

    import pylab as PL

    fig = PL.figure()

    PL.plot_date(series.index.to_datetime(),
                 series.values,
                 mec='None',
                 ms=1)

    PL.plot_date(E_series.index.to_datetime(),
                 E_series.values,
                 c='r',
                 mec='None',
                 ms=0.5)

    PL.show()
<commit_msg>Lots of cleanup required --- checking in current status.<commit_after>from __future__ import division

import logging
import math

import numpy as NP
import scipy.signal
import pandas as PD
import pynfftls

from repository import get_data_frame, get_root
from ..util.date import toJ2000

logger = logging.getLogger('pyrsss.mag.love_gannon')

"""
J. J. Love and J. L. Gannon, "Revised Dst and the epicycles of
magnetic disturbance: 1958--2009," Ann. Geophys., vol 27,
pp. 3101--3131, 2009.
"""

SAMPLES = {'min': 60 * 24}
"""
Mapping between the number of samples per day for a given sampling
period.
"""

def quiet_days(series,
               n_days=5,
               period='min'):
    """
    Given a pandas time series *series*, return a mapping between
    months and the *n_days* quietest days for that month. See (4) of
    Love and Gannon. The parameter *period* gives the sampling period
    (`'min'` = 1 measurement per minute).
    """
    quiet_day_map = {}
    delta_H_i = series.diff().abs().\
                groupby(PD.TimeGrouper(freq='D')).\
                filter(lambda x: x.isnull().sum() <= int(0.5 * SAMPLES[period])).\
                groupby(PD.TimeGrouper(freq='D')).mean()
    for month, delta_H_i_month in delta_H_i.groupby(PD.TimeGrouper(freq='M')):
        quiet_day_map[month] = delta_H_i_month.nsmallest(n_days).sort_index().index
    return quiet_day_map

def chebyshev_fit(series,
                  quiet_day_map,
                  deg=10):
    """
    ???
    """
    grouped_by_day = series.groupby(PD.TimeGrouper(freq='D'))
    x = []
    y = []
    for month_end in sorted(quiet_day_map):
        for quiet_day in quiet_day_map[month_end]:
            quiet_day_H = grouped_by_day.get_group(quiet_day)
            quiet_day_H = quiet_day_H[quiet_day_H.notnull()]
            x.extend([toJ2000(time_stamp.to_datetime()) for time_stamp in quiet_day_H.index])
            y.extend(quiet_day_H.values)
    return NP.polynomial.chebyshev.chebfit(x, y, deg, full=True)

def external_field_variation(series, coeffs):
    """
    ???
    """
    x = map(toJ2000, series.index.to_datetime())
    return PD.Series(index=series.index,
                     data=series.values - NP.polynomial.chebyshev.chebval(x, coeffs))

def remove_active_days(E_series):
    """
    ???
    """
    pass

if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO)

    # root = get_root()

    # logger.info('loading')
    # dataframe, _ = get_data_frame(root,
    #                               'frd',
    #                               0,
    #                               columns=['time', 'H'])
    #                               # years=[2002])

    # series = PD.Series(index=dataframe.time,
    #                    data=dataframe.H)

    # quiet_day_map = quiet_days(series)

    # logger.info('fitting')
    # c, info = chebyshev_fit(series, quiet_day_map)

    # logger.info('evaluating')
    # E_series = external_field_variation(series, c)

    # E_series.to_hdf('/tmp/E.hdf', 'E_frd', mode='w', complevel=9, complib='zlib')

    # import pylab as PL

    # fig = PL.figure()

    # PL.plot_date(E_series.index.to_datetime(),
    #              E_series.values,
    #              c='r',
    #              mec='None',
    #              ms=0.5)

    # PL.show()

    E_series = PD.read_hdf('/tmp/E.hdf')
    E_series = E_series[E_series.notnull()]

    N = 1024
    days_to_seconds = 60 * 60 * 24

    periods = NP.linspace(0.9 * days_to_seconds, 1.1 * days_to_seconds, N)
    freqs = 1 / periods
    angular_freqs = 2 * math.pi * freqs

    # time = [toJ2000(x.to_datetime()) for x in E_series.index]
    time = E_series.index.astype(NP.int64) / 1e9
    time -= time[0]

    # print(time[:10])

    # print(E_series.index[0])
    # print(toJ2000(E_series.index[0].to_datetime()))
    # print(toJ2000(E_series.index[1].to_datetime()))
    # # print(dir(E_series.index[0]))
    # # print(type(E_series.index[0]))
    # assert False

    # pgram = scipy.signal.lombscargle(time, E_series.values, angular_freqs)
    # normalized_pgram = NP.sqrt(4 * (pgram / len(E_series)))

    ofac = 2
    hifac = 1

    # print('begin nfftls')
    # (f_nfftls, p_nfftls) = pynfftls.period(time, E_series.values, ofac, hifac)
    # print('end nfftls')

    # from cPickle import dump
    # with open('/tmp/love_gannon.pkl', 'w') as fid:
    #     dump((f_nfftls, p_nfftls), fid, -1)

    from cPickle import load
    with open('/tmp/love_gannon.pkl') as fid:
        (f_nfftls, p_nfftls) = load(fid)

    import pylab as PL

    fig = PL.figure()
    # PL.plot(1 / f_nfftls / days_to_seconds,
    #         p_nfftls)
    PL.semilogy(1 / f_nfftls / days_to_seconds,
             p_nfftls)
    # PL.autoscale(axis='x', tight=True)
    # PL.xlim(0.9, 1.1)

    PL.show()
<|endoftext|>


<commit_before>"""
Define a default XML parser that avoids XXE injection.

Package :mod:`lxml` is employed directly even though some linters (e.g.: ``bandit``) report to employ ``defusedxml``
instead, because that package's extension with ``lxml`` is marked as deprecated.

.. seealso::
    https://pypi.org/project/defusedxml/#defusedxml-lxml

To use the module, import is as if importing ``lxml.etree``:

.. code-block:: python

    from weaver.xml_util import XML  # ElementTree
    from weaver import xml_util

    data = xml_util.fromstring("<xml>content</xml>")
"""

from typing import TYPE_CHECKING

from lxml import etree as lxml_etree  # nosec: B410  # flagged known issue, this is what the applied fix below is about

if TYPE_CHECKING:
    from lxml.etree._FeedParser import _FeedParser as Parser  # noqa # pylint: disable=W0212

XML_PARSER = lxml_etree.XMLParser(
    # security fix: XML external entity (XXE) injection
    #   https://lxml.de/parsing.html#parser-options
    #   https://nvd.nist.gov/vuln/detail/CVE-2021-39371
    # based on:
    #   https://github.com/geopython/pywps/pull/616
    resolve_entities=False,
    # avoid failing parsing if some characters are not correctly escaped
    # based on:
    #   https://stackoverflow.com/a/57450722/5936364
    recover=True,  # attempt, no guarantee
)

tostring = lxml_etree.tostring
Element = lxml_etree.Element
ParseError = lxml_etree.ParseError

# define this type here so that code can use it for actual logic without repeating 'noqa'
XML = lxml_etree._Element  # noqa

# save a local reference to method employed by OWSLib directly called
_lxml_fromstring = lxml_etree.fromstring

def fromstring(text, parser=XML_PARSER):
    # type: (str, Parser) -> XML
    """
    Drop in replacement for :func:`lxml.etree.fromstring` using a secure :term:`XML` parser.
    """
    return _lxml_fromstring(text, parser=parser)  # nosec: B410,B320  # safe use if using secure parser

def strip_namespace(tree):
    # type: (XML) -> None
    """
    Strip the namespace component from all tags in the specified :term:`XML` tree.
    """
    for node in tree.iter():
        try:
            has_namespace = node.tag.startswith("{")
        except AttributeError:
            continue  # node.tag is not a string (node is a comment or similar)
        if has_namespace:
            node.tag = node.tag.split("}", 1)[1]
<commit_msg>ignore protected import<commit_after>"""
Define a default XML parser that avoids XXE injection.

Package :mod:`lxml` is employed directly even though some linters (e.g.: ``bandit``) report to employ ``defusedxml``
instead, because that package's extension with ``lxml`` is marked as deprecated.

.. seealso::
    https://pypi.org/project/defusedxml/#defusedxml-lxml

To use the module, import is as if importing ``lxml.etree``:

.. code-block:: python

    from weaver.xml_util import XML  # ElementTree
    from weaver import xml_util

    data = xml_util.fromstring("<xml>content</xml>")
"""

from typing import TYPE_CHECKING

from lxml import etree as lxml_etree  # nosec: B410  # flagged known issue, this is what the applied fix below is about

if TYPE_CHECKING:
    from lxml.etree._FeedParser import _FeedParser as Parser  # noqa # pylint: disable=W0212

XML_PARSER = lxml_etree.XMLParser(
    # security fix: XML external entity (XXE) injection
    #   https://lxml.de/parsing.html#parser-options
    #   https://nvd.nist.gov/vuln/detail/CVE-2021-39371
    # based on:
    #   https://github.com/geopython/pywps/pull/616
    resolve_entities=False,
    # avoid failing parsing if some characters are not correctly escaped
    # based on:
    #   https://stackoverflow.com/a/57450722/5936364
    recover=True,  # attempt, no guarantee
)

tostring = lxml_etree.tostring
Element = lxml_etree.Element
ParseError = lxml_etree.ParseError

# define this type here so that code can use it for actual logic without repeating 'noqa'
XML = lxml_etree._Element  # noqa # pylint: disable=W0212

# save a local reference to method employed by OWSLib directly called
_lxml_fromstring = lxml_etree.fromstring

def fromstring(text, parser=XML_PARSER):
    # type: (str, Parser) -> XML
    """
    Drop in replacement for :func:`lxml.etree.fromstring` using a secure :term:`XML` parser.
    """
    return _lxml_fromstring(text, parser=parser)  # nosec: B410,B320  # safe use if using secure parser

def strip_namespace(tree):
    # type: (XML) -> None
    """
    Strip the namespace component from all tags in the specified :term:`XML` tree.
    """
    for node in tree.iter():
        try:
            has_namespace = node.tag.startswith("{")
        except AttributeError:
            continue  # node.tag is not a string (node is a comment or similar)
        if has_namespace:
            node.tag = node.tag.split("}", 1)[1]
<|endoftext|>


<commit_before>from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.utils.crypto import get_random_string
from models import MailerStorage

def get_storage():
    fs = None
    if getattr(settings, 'MAILQUEUE_STORAGE', False):
        fs = MailerStorage() if hasattr(settings, 'MAILQUEUE_ROOT') else FileSystemStorage(location=settings.MEDIA_ROOT)
    return fs

def upload_to(instance, filename):
    # Because instead of filesystem, email message can have multiple attachments with the same filename
    return 'mailqueue-attahcments/{0}_{1}'.format(get_random_string(length=24), filename)
<commit_msg>import twaeking<commit_after>from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.utils.crypto import get_random_string
from mailqueue.models import MailerStorage

def get_storage():
    fs = None
    if getattr(settings, 'MAILQUEUE_STORAGE', False):
        fs = MailerStorage() if hasattr(settings, 'MAILQUEUE_ROOT') else FileSystemStorage(location=settings.MEDIA_ROOT)
    return fs

def upload_to(instance, filename):
    # Because instead of filesystem, email message can have multiple attachments with the same filename
    return 'mailqueue-attahcments/{0}_{1}'.format(get_random_string(length=24), filename)
<|endoftext|>


<commit_before>extensions.remove('matplotlib.sphinxext.only_directives')
extensions.remove('matplotlib.sphinxext.mathmpl')
extensions.remove('matplotlib.sphinxext.plot_directive')
<commit_msg>documentation<commit_after>import mock

MOCK_MODULES = ['numpy', 'scipy', 'matplotlib', 'matplotlib.pyplot', 'scipy.interpolate','matplotlib.sphinxext.mathmpl']
for mod_name in MOCK_MODULES:
sys.modules[mod_name] = mock.Mock()
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
#
# Hybra documentation build configuration file, created by
# sphinx-quickstart on Sun Feb 19 22:14:15 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

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

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

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

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['sphinx.ext.autodoc',
    'sphinx.ext.doctest',
    'sphinx.ext.todo',
    'sphinx.ext.coverage',
    'sphinx.ext.viewcode',
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'Hybra'
copyright = u'2016- Helsinki Institute for Information Technology HIIT and Department of Computer Science, Aalto-University and University of Helsinki'
author = u'Matti Nelimarkka, Juho Pääkkönen, Arto Kekkonen'

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

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']

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

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True

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

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

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

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

# -- Options for HTMLHelp output ------------------------------------------

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

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

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

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

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

    # Latex figure (float) alignment
    #
    # 'figure_align': 'htbp',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
    (master_doc, 'Hybra.tex', u'Hybra Documentation',
     u'Matti Nelimarkka, Juho Pääkkönen, Arto Kekkone', 'manual'),
]

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

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    (master_doc, 'hybra', u'Hybra Documentation',
     [author], 1)
]

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

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
    (master_doc, 'Hybra', u'Hybra Documentation',
     author, 'Hybra', 'One line description of project.',
     'Miscellaneous'),
]
<commit_msg>Fix documentation path<commit_after># -*- coding: utf-8 -*-
#
# Hybra documentation build configuration file, created by
# sphinx-quickstart on Sun Feb 19 22:14:15 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

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

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

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

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['sphinx.ext.autodoc',
    'sphinx.ext.doctest',
    'sphinx.ext.todo',
    'sphinx.ext.coverage',
    'sphinx.ext.viewcode',
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'Hybra'
copyright = u'2016- Helsinki Institute for Information Technology HIIT and Department of Computer Science, Aalto-University and University of Helsinki'
author = u'Matti Nelimarkka, Juho Pääkkönen, Arto Kekkonen'

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

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']

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

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True

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

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

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

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

# -- Options for HTMLHelp output ------------------------------------------

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

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

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

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

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

    # Latex figure (float) alignment
    #
    # 'figure_align': 'htbp',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
    (master_doc, 'Hybra.tex', u'Hybra Documentation',
     u'Matti Nelimarkka, Juho Pääkkönen, Arto Kekkone', 'manual'),
]

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

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    (master_doc, 'hybra', u'Hybra Documentation',
     [author], 1)
]

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

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
    (master_doc, 'Hybra', u'Hybra Documentation',
     author, 'Hybra', 'One line description of project.',
     'Miscellaneous'),
]
<|endoftext|>


<commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-
###
# Copyright (2016-2017) Hewlett Packard Enterprise Development LP
#
# 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.
###
import unittest

from oneview_module_loader import IdPoolsIpv4SubnetModule
from hpe_test_utils import OneViewBaseTestCase

FAKE_MSG_ERROR = 'Fake message error'

DEFAULT_SUBNET_TEMPLATE = dict(
    name='Ipv4Subnet',
    uri='rest/subnet/test',
    type='Subnet',
    domain='example.com'
)

PARAMS_FOR_PRESENT = dict(
    config='config.json',
    state='present',
    data=dict(name=DEFAULT_SUBNET_TEMPLATE['name'])
)

PARAMS_FOR_PRESENT_WITH_URI = dict(
    config='config.json',
    state='present',
    data=dict(uri=DEFAULT_SUBNET_TEMPLATE['uri'])
)

PARAMS_WITH_CHANGES = dict(
    config='config.json',
    state='present',
    data=dict(name=DEFAULT_SUBNET_TEMPLATE['name'],
              domain='newdomain.com')
)

PARAMS_FOR_ABSENT = dict(
    config='config.json',
    state='absent',
    data=dict(name=DEFAULT_SUBNET_TEMPLATE['name'])
)

class IdPoolsIpv4SubnetModuleSpec(unittest.TestCase,
                                  OneViewBaseTestCase):
    """
    OneViewBaseTestCase provides the mocks used in this test case
    """

    def setUp(self):
        self.configure_mocks(self, IdPoolsIpv4SubnetModule)
        self.resource = self.mock_ov_client.id_pools_ipv4_subnets

    def test_should_create_new_id_pools_ipv4_subnet(self):
        self.resource.get_all.return_value = []
        self.resource.create.return_value = DEFAULT_SUBNET_TEMPLATE

        self.mock_ansible_module.params = PARAMS_FOR_PRESENT

        IdPoolsIpv4SubnetModule().run()

        self.mock_ansible_module.exit_json.assert_called_once_with(
            changed=True,
            msg=IdPoolsIpv4SubnetModule.MSG_CREATED,
            ansible_facts=dict(id_pools_ipv4_subnets=DEFAULT_SUBNET_TEMPLATE)
        )

    def test_should_not_update_when_data_is_equals(self):
        self.resource.get_all.return_value = [DEFAULT_SUBNET_TEMPLATE]

        self.mock_ansible_module.params = PARAMS_FOR_PRESENT

        IdPoolsIpv4SubnetModule().run()

        self.mock_ansible_module.exit_json.assert_called_once_with(
            changed=False,
            msg=IdPoolsIpv4SubnetModule.MSG_ALREADY_PRESENT,
            ansible_facts=dict(id_pools_ipv4_subnets=DEFAULT_SUBNET_TEMPLATE)
        )

    def test_should_get_the_same_resource_by_uri(self):
        self.resource.get.return_value = DEFAULT_SUBNET_TEMPLATE

        self.mock_ansible_module.params = PARAMS_FOR_PRESENT_WITH_URI

        IdPoolsIpv4SubnetModule().run()

        self.mock_ansible_module.exit_json.assert_called_once_with(
            changed=False,
            msg=IdPoolsIpv4SubnetModule.MSG_ALREADY_PRESENT,
            ansible_facts=dict(id_pools_ipv4_subnets=DEFAULT_SUBNET_TEMPLATE)
        )

    def test_update_when_data_has_modified_attributes(self):
        data_merged = DEFAULT_SUBNET_TEMPLATE.copy()
        data_merged['domain'] = 'newdomain.com'

        self.resource.get_all.return_value = [DEFAULT_SUBNET_TEMPLATE]
        self.resource.update.return_value = data_merged

        self.mock_ansible_module.params = PARAMS_WITH_CHANGES

        IdPoolsIpv4SubnetModule().run()

        self.mock_ansible_module.exit_json.assert_called_once_with(
            changed=True,
            msg=IdPoolsIpv4SubnetModule.MSG_UPDATED,
            ansible_facts=dict(id_pools_ipv4_subnets=data_merged)
        )

    def test_should_remove_id_pools_ipv4_subnet(self):
        self.resource.get_all.return_value = [DEFAULT_SUBNET_TEMPLATE]

        self.mock_ansible_module.params = PARAMS_FOR_ABSENT

        IdPoolsIpv4SubnetModule().run()

        self.mock_ansible_module.exit_json.assert_called_once_with(
            changed=True,
            msg=IdPoolsIpv4SubnetModule.MSG_DELETED
        )

    def test_should_do_nothing_when_id_pools_ipv4_subnet_not_exist(self):
        self.resource.get_all.return_value = []

        self.mock_ansible_module.params = PARAMS_FOR_ABSENT

        IdPoolsIpv4SubnetModule().run()

        self.mock_ansible_module.exit_json.assert_called_once_with(
            changed=False,
            msg=IdPoolsIpv4SubnetModule.MSG_ALREADY_ABSENT
        )

if __name__ == '__main__':
    unittest.main()
<commit_msg>Added test to check exception in IPV4 Subnets<commit_after>#!/usr/bin/python
# -*- coding: utf-8 -*-
###
# Copyright (2016-2017) Hewlett Packard Enterprise Development LP
#
# 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.
###
import unittest

from oneview_module_loader import IdPoolsIpv4SubnetModule
from hpe_test_utils import OneViewBaseTestCase

FAKE_MSG_ERROR = 'Fake message error'

DEFAULT_SUBNET_TEMPLATE = dict(
    name='Ipv4Subnet',
    uri='rest/subnet/test',
    type='Subnet',
    domain='example.com'
)

PARAMS_FOR_PRESENT = dict(
    config='config.json',
    state='present',
    data=dict(name=DEFAULT_SUBNET_TEMPLATE['name'])
)

PARAMS_FOR_PRESENT_WITH_URI = dict(
    config='config.json',
    state='present',
    data=dict(uri=DEFAULT_SUBNET_TEMPLATE['uri'])
)

PARAMS_FOR_INVALID = dict(
    config='config.json',
    state='present',
    data=dict(type=DEFAULT_SUBNET_TEMPLATE['type'])
)

PARAMS_WITH_CHANGES = dict(
    config='config.json',
    state='present',
    data=dict(name=DEFAULT_SUBNET_TEMPLATE['name'],
              domain='newdomain.com')
)

PARAMS_FOR_ABSENT = dict(
    config='config.json',
    state='absent',
    data=dict(name=DEFAULT_SUBNET_TEMPLATE['name'])
)

class IdPoolsIpv4SubnetModuleSpec(unittest.TestCase,
                                  OneViewBaseTestCase):
    """
    OneViewBaseTestCase provides the mocks used in this test case
    """

    def setUp(self):
        self.configure_mocks(self, IdPoolsIpv4SubnetModule)
        self.resource = self.mock_ov_client.id_pools_ipv4_subnets

    def test_should_create_new_id_pools_ipv4_subnet(self):
        self.resource.get_all.return_value = []
        self.resource.create.return_value = DEFAULT_SUBNET_TEMPLATE

        self.mock_ansible_module.params = PARAMS_FOR_PRESENT

        IdPoolsIpv4SubnetModule().run()

        self.mock_ansible_module.exit_json.assert_called_once_with(
            changed=True,
            msg=IdPoolsIpv4SubnetModule.MSG_CREATED,
            ansible_facts=dict(id_pools_ipv4_subnets=DEFAULT_SUBNET_TEMPLATE)
        )

    def test_should_not_update_when_data_is_equals(self):
        self.resource.get_all.return_value = [DEFAULT_SUBNET_TEMPLATE]

        self.mock_ansible_module.params = PARAMS_FOR_PRESENT

        IdPoolsIpv4SubnetModule().run()

        self.mock_ansible_module.exit_json.assert_called_once_with(
            changed=False,
            msg=IdPoolsIpv4SubnetModule.MSG_ALREADY_PRESENT,
            ansible_facts=dict(id_pools_ipv4_subnets=DEFAULT_SUBNET_TEMPLATE)
        )

    def test_should_get_the_same_resource_by_uri(self):
        self.resource.get.return_value = DEFAULT_SUBNET_TEMPLATE

        self.mock_ansible_module.params = PARAMS_FOR_PRESENT_WITH_URI

        IdPoolsIpv4SubnetModule().run()

        self.mock_ansible_module.exit_json.assert_called_once_with(
            changed=False,
            msg=IdPoolsIpv4SubnetModule.MSG_ALREADY_PRESENT,
            ansible_facts=dict(id_pools_ipv4_subnets=DEFAULT_SUBNET_TEMPLATE)
        )

    def test_should_fail_with_missing_required_attributes(self):
        self.mock_ansible_module.params = PARAMS_FOR_INVALID

        IdPoolsIpv4SubnetModule().run()

        self.mock_ansible_module.fail_json.assert_called_once_with(
            msg=IdPoolsIpv4SubnetModule.MSG_VALUE_ERROR
        )

    def test_update_when_data_has_modified_attributes(self):
        data_merged = DEFAULT_SUBNET_TEMPLATE.copy()
        data_merged['domain'] = 'newdomain.com'

        self.resource.get_all.return_value = [DEFAULT_SUBNET_TEMPLATE]
        self.resource.update.return_value = data_merged

        self.mock_ansible_module.params = PARAMS_WITH_CHANGES

        IdPoolsIpv4SubnetModule().run()

        self.mock_ansible_module.exit_json.assert_called_once_with(
            changed=True,
            msg=IdPoolsIpv4SubnetModule.MSG_UPDATED,
            ansible_facts=dict(id_pools_ipv4_subnets=data_merged)
        )

    def test_should_remove_id_pools_ipv4_subnet(self):
        self.resource.get_all.return_value = [DEFAULT_SUBNET_TEMPLATE]

        self.mock_ansible_module.params = PARAMS_FOR_ABSENT

        IdPoolsIpv4SubnetModule().run()

        self.mock_ansible_module.exit_json.assert_called_once_with(
            changed=True,
            msg=IdPoolsIpv4SubnetModule.MSG_DELETED
        )

    def test_should_do_nothing_when_id_pools_ipv4_subnet_not_exist(self):
        self.resource.get_all.return_value = []

        self.mock_ansible_module.params = PARAMS_FOR_ABSENT

        IdPoolsIpv4SubnetModule().run()

        self.mock_ansible_module.exit_json.assert_called_once_with(
            changed=False,
            msg=IdPoolsIpv4SubnetModule.MSG_ALREADY_ABSENT
        )

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


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

#-*- coding: utf-8 -*-
'''
Created on Jun 04, 2017

@author ujnzxw <ujnzxw@gmail.com>
'''

import urllib,re,sys,os,random,json
from   config    import momentumdash_output_file
from   utils     import set_background, get_desktop_environment

class MomentumdashManager():
    '''
    momentumdash.com background image manager
    '''

    def __init__(self):
        pass

    def get_bg_picture(self):
        '''
        get background picture from https://momentumdash.com
        '''

        '''
        background image json file:

        https://momentumdash.com/app/backgrounds.json
        '''
        index     = random.randint(0,13)
        json_url  = "https://momentumdash.com/app/backgrounds.json"
        response  = urllib.urlopen(json_url)
        json_data = json.loads(response.read())
        filename  = json_data['backgrounds'][index]['filename']

        imgurl = 'https://momentumdash.com/backgrounds/' + filename
        urllib.urlretrieve(imgurl, momentumdash_output_file)

    def run(self):
        ''' main function '''

        ''' get background picture from momentumdash.com '''

        print("Updating momentumdash image...")

        self.get_bg_picture()

        print("\nSaving to '%s'..." % (momentumdash_output_file))

        ''' set background picture as wallpaper '''
        if not set_background(momentumdash_output_file, "wallpaper"):
            exit("Your desktop environment '{}' is not supported.".format(get_desktop_environment()))

        print("Done!")

if __name__ == "__main__":
    b = MomentumdashManager()
    b.run()
<commit_msg>change mode from wallpaper to stretched<commit_after>#!/usr/bin/env python

#-*- coding: utf-8 -*-
'''
Created on Jun 04, 2017

@author ujnzxw <ujnzxw@gmail.com>
'''

import urllib,re,sys,os,random,json
from   config    import momentumdash_output_file
from   utils     import set_background, get_desktop_environment

class MomentumdashManager():
    '''
    momentumdash.com background image manager
    '''

    def __init__(self):
        pass

    def get_bg_picture(self):
        '''
        get background picture from https://momentumdash.com
        '''

        '''
        background image json file:

        https://momentumdash.com/app/backgrounds.json
        '''
        index     = random.randint(0,13)
        json_url  = "https://momentumdash.com/app/backgrounds.json"
        response  = urllib.urlopen(json_url)
        json_data = json.loads(response.read())
        filename  = json_data['backgrounds'][index]['filename']

        imgurl = 'https://momentumdash.com/backgrounds/' + filename
        urllib.urlretrieve(imgurl, momentumdash_output_file)

    def run(self):
        ''' main function '''

        ''' get background picture from momentumdash.com '''

        print("Updating momentumdash image...")

        self.get_bg_picture()

        print("\nSaving to '%s'..." % (momentumdash_output_file))

        ''' set background picture as wallpaper '''
        ''' scaled, wallpaper, stretched, spanned '''
        if not set_background(momentumdash_output_file, "stretched"):
            exit("Your desktop environment '{}' is not supported.".format(get_desktop_environment()))

        print("Done!")

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


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# gxf documentation build configuration file, created by
# sphinx-quickstart on Tue Jul  9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

import sys
import os

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

# Get the project root dir, which is the parent dir of this
cwd = os.getcwd()
project_root = os.path.dirname(cwd)

# Insert the project root dir as the first element in the PYTHONPATH.
# This lets us ensure that the source package is imported, and that its
# version is used.
sys.path.insert(0, project_root)

import gxf

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

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

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

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

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

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'gxf'
copyright = u'2014, Wannes `wapiflapi` Rombouts'

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

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

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

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

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

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

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

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

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

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

# If true, keep warnings as "system message" paragraphs in the built
# documents.
#keep_warnings = False

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass
# [howto/manual]).
latex_documents = [
    ('index', 'gxf.tex',
     u'gxf Documentation',
     u'Wannes `wapiflapi` Rombouts', 'manual'),
]

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

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

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

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

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

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

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

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    ('index', 'gxf',
     u'gxf Documentation',
     [u'Wannes `wapiflapi` Rombouts'], 1)
]

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

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

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

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

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

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

# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
<commit_msg>Use readthedocs theme localy if available.<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# gxf documentation build configuration file, created by
# sphinx-quickstart on Tue Jul  9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

import sys
import os

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

# Get the project root dir, which is the parent dir of this
cwd = os.getcwd()
project_root = os.path.dirname(cwd)

# Insert the project root dir as the first element in the PYTHONPATH.
# This lets us ensure that the source package is imported, and that its
# version is used.
sys.path.insert(0, project_root)

import gxf

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

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

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

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

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

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'gxf'
copyright = u'2014, Wannes `wapiflapi` Rombouts'

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

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

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

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

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

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

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

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

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

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

# If true, keep warnings as "system message" paragraphs in the built
# documents.
#keep_warnings = False

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

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

# if we are not on readthedocs.org we still load their theme cause its cool.
if not os.environ.get('READTHEDOCS', None) == 'True':

    try:
        import sphinx_rtd_theme
    except ImportError:
        pass

    html_theme = 'sphinx_rtd_theme'
    html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]

# otherwise, readthedocs.org uses their theme by default, so no need to specify its

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass
# [howto/manual]).
latex_documents = [
    ('index', 'gxf.tex',
     u'gxf Documentation',
     u'Wannes `wapiflapi` Rombouts', 'manual'),
]

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

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

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

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

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

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

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

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    ('index', 'gxf',
     u'gxf Documentation',
     [u'Wannes `wapiflapi` Rombouts'], 1)
]

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

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

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

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

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

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

# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
<|endoftext|>


<commit_before>import discord
from discord.ext import commands
import os
from .utils.dataIO import dataIO
import time
import asyncio
from random import randint

client = discord.Client()

class Russianroulette:
    """Russian Roulette"""

    def __init__(self, bot):
        self.bot = bot
        self.file_path = "data/russianroulette/russianroulette.json"
        self.json_data = dataIO.load_json(self.file_path)

    @commands.command(pass_context=True, aliases=["rr", "russian"])
    async def russianroulette(self, ctx, type):
        """Type = start or join"""

        #Your code will go here
        user = ctx.message.author
        bank = self.bot.get_cog("Economy").bank
        if type.lower() == "start":
            if self.json_data["System"]["Status"] == "Stopped":
                await self.betAmount(user, bank)
            elif self.json_data["System"]["Status"] == "Waiting":
                if user.id == self.json_data["Players"]["1"] and self.json_data["System"]["Player Count"] > 1:
                    totalPlayers = self.json_data["System"]["Player Count"]
                    await self.startGame(bank, ctx, totalPlayers)
                else:
                    await self.bot.say("Game has been made, to join it type `*rr join`. Only the creator of the roulette can start it and there must be more than 1 person")
            else:
                await self.bot.say("Game is in progress, please wait until it's finished")
        elif type.lower() == "join":
            if self.json_data["System"]["Status"] == "Waiting":
                await self.joinGame(user, bank)
            elif self.json_data["System"]["Status"] == "Stopped":
                await self.bot.say("No game to join, type `*rr start` to create a game")
            else:
                await self.bot.say("Game is in progress, please wait until it's finished")
        elif type.lower() == "stop":
            if self.json_data["System"]["Status"] == "Stopped":
                await self.bot.say("There is no game running to stop")
            elif self.json_data["System"]["Status"] == "Running":
                await self.bot.say("The game is running and can only be stopped when waiting in the lobby")
            if user.id == self.json_data["Players"]["1"]:
                self.json_data["Players"]["1"] = ""
                self.json_data["Players"]["2"] = ""
                self.json_data["Players"]["3"] = ""
                self.json_data["Players"]["4"] = ""
                self.json_data["Players"]["5"] = ""
                self.json_data["Players"]["6"] = ""
                self.json_data["System"]["Player Count"] = 0
                self.json_data["System"]["Status"] = "Stopped"
                self.json_data["System"]["Bet"] = 0
                f = "data/russianroulette/russianroulette.json"
                dataIO.save_json(f, self.json_data)
                await self.bot.say("The roulette has been cancelled")
            else:
                await self.bot.say("You must be the person who started the roulette and you must currently be waiting for people to join")
        else:
            await self.bot.say(user.mention + "This command only accepts `start` `stop` or `join`")

    @client.event
    async def betAmount(self, user, bank):
        await self.bot.say("How much would you like to put on the line: $")
        bet = await self.bot.wait_for_message(timeout=10, author=user)
        if bet is None:
            await self.bot.say("You didn't enter anything")
            return
        try:
            bet = int(str(bet.content))
        except ValueError:
            pass
        if isinstance(bet , int):
            if bank.account_exists(user):
                if bank.get_balance(user) > bet:
                    self.json_data["System"]["Bet"] = bet
                    self.json_data["Players"]["1"] = user.id
                    self.json_data["System"]["Player Count"] += 1
                    self.json_data["System"]["Status"] = "Waiting"
                    f = "data/russianroulette/russianroulette.json"
                    dataIO.save_json(f, self.json_data)
                    await self.bot.say("Bet placed at $" + str(bet) + "\nTo start the game you need atleast one another person to join with `*rr join`")
                    await self.timeOut()
                else:
                    await self.bot.say("You don't have enough to place a bet of $" + str(bet) + " You only have $" + str(bank.get_balance(user)))
            else:
                await self.bot.say("You don't have a bank account, create one first with `*bank register`")
                return
        else:
            await self.bot.say("You must enter a number")
            await self.betAmount(user, bank)

    async def joinGame(self, user, bank):
        bet = self.json_data["System"]["Bet"]
        if self.json_data["System"]["Player Count"] == 6:
            await self.bot.say("The game is full, please wait until it has finished to join")
        elif bank.account_exists(user):
            if user.id == self.json_data["Players"]["1"] or user.id == self.json_data["Players"]["2"] or user.id == self.json_data["Players"]["3"] or user.id == self.json_data["Players"]["4"] or user.id == self.json_data["Players"]["5"] or user.id == self.json_data["Players"]["6"]:
                await self.bot.say("You're already entered")
            else:
                if bank.get_balance(user) > bet:
                    await self.bot.say("The bet is set to: $" + str(bet) + "\nWould you still like to enter? Y/N")
                    answer = ""
                    answer = await self.bot.wait_for_message(timeout=10, author=user)
                    answer = str(answer.content)
                    if answer is None or answer.lower() == "n" or answer.lower() == "no":
                        await self.bot.say("Very well, you haven't been entered")
                        return
                    elif answer.lower() == "y" or answer.lower() == "yes":
                        self.json_data["System"]["Player Count"] += 1
                        self.json_data["Players"][str(self.json_data["System"]["Player Count"])] = user.id
                        f = "data/russianroulette/russianroulette.json"
                        dataIO.save_json(f, self.json_data)
                        await self.bot.say("You have been entered. You are in seat: " + str(self.json_data["System"]["Player Count"]))
                        return
                else:
                    await self.bot.say("You don't have enough money. You have $" + str(bank.get_balance(user)) + " The bet is set at $" + str(bet))
                    return
        else:
            await self.bot.say("You don't have a bank account. Make one with `*bank register`")
            return

    async def startGame(self, bank, ctx, totalPlayers):
        i = 1
        a = 1
        await self.bot.say("Game is starting")
        while i <= self.json_data["System"]["Player Count"]:
            bank.withdraw_credits(discord.utils.get(ctx.message.server.members, id=self.json_data["Players"][str(i)]), self.json_data["System"]["Bet"])
            i += 1
        while self.json_data["System"]["Player Count"] > 1:
            await self.play(ctx, a)
            a += 1
        b = 1
        winner = ""
        while winner == "":
            if self.json_data["Players"][str(b)] == "":
                b += 1
            else:
                winner = self.json_data["Players"][str(b)]
        bank.deposit_credits(discord.utils.get(ctx.message.server.members, id=winner), self.json_data["System"]["Bet"] * totalPlayers)
        await self.bot.say("Congrats " + discord.utils.get(ctx.message.server.members, id=winner).mention + " on winning $" + str(self.json_data["System"]["Bet"] * totalPlayers))
        self.json_data["Players"]["1"] = ""
        self.json_data["Players"]["2"] = ""
        self.json_data["Players"]["3"] = ""
        self.json_data["Players"]["4"] = ""
        self.json_data["Players"]["5"] = ""
        self.json_data["Players"]["6"] = ""
        self.json_data["System"]["Player Count"] = 0
        self.json_data["System"]["Status"] = "Stopped"
        self.json_data["System"]["Bet"] = 0
        f = "data/russianroulette/russianroulette.json"
        dataIO.save_json(f, self.json_data)

    async def play(self, ctx, a):
        try:
            if self.json_data["Players"][str((a%7))] == "":
                return
        except KeyError:
            return
        time.sleep(2)
        await self.bot.say(discord.utils.get(ctx.message.server.members, id=self.json_data["Players"][str(a%7)]).mention + " picks up the gun...")
        time.sleep(2)
        await self.bot.say("They pull the trigger...")
        time.sleep(1)
        if randint(1, 20) >= 9:
            await self.bot.say(discord.utils.get(ctx.message.server.members, id=self.json_data["Players"][str((a%7))]).mention + " you're still alive")
        else:
            await self.bot.say(discord.utils.get(ctx.message.server.members, id=self.json_data["Players"][str((a%7))]).mention + " shot their brains out")
            self.json_data["Players"][str((a%6))] = ""
            self.json_data["System"]["Player Count"] += -1
            f = "data/russianroulette/russianroulette.json"
            dataIO.save_json(f, self.json_data)

    async def timeOut(self):
        if self.json_data["System"]["Status"] == "Waiting":
            await asyncio.sleep(120)
            if self.json_data["System"]["Status"] == "Waiting":
                self.json_data["Players"]["1"] = ""
                self.json_data["Players"]["2"] = ""
                self.json_data["Players"]["3"] = ""
                self.json_data["Players"]["4"] = ""
                self.json_data["Players"]["5"] = ""
                self.json_data["Players"]["6"] = ""
                self.json_data["System"]["Player Count"] = 0
                self.json_data["System"]["Status"] = "Stopped"
                self.json_data["System"]["Bet"] = 0
                f = "data/russianroulette/russianroulette.json"
                dataIO.save_json(f, self.json_data)
                await self.bot.say("The game wasn't started within 2 minutes and has been cancelled")
                return

def check_folders():
    if not os.path.exists("data/russianroulette"):
        print("Creating data/russianroulette floder...")
        os.makedirs("data/russianroulette")

def check_files():
    system = {"System": {"Bet": 0,
                         "Status": "Stopped",
                         "Player Count": 0},
              "Players": {"1": "",
                          "2": "",
                          "3": "",
                          "4": "",
                          "5": "",
                          "6": ""}}
    f = "data/russianroulette/russianroulette.json"
    if not dataIO.is_valid_json(f):
        print("Creating defualt russianroulette.json...")
        dataIO.save_json(f, system)

def setup(bot):
    check_folders()
    check_files()
    n = Russianroulette(bot)
    bot.add_cog(n)
<commit_msg>User can bet all their money<commit_after>import discord
from discord.ext import commands
import os
from .utils.dataIO import dataIO
import time
import asyncio
from random import randint

client = discord.Client()

class Russianroulette:
    """Russian Roulette"""

    def __init__(self, bot):
        self.bot = bot
        self.file_path = "data/russianroulette/russianroulette.json"
        self.json_data = dataIO.load_json(self.file_path)

    @commands.command(pass_context=True, aliases=["rr", "russian"])
    async def russianroulette(self, ctx, type):
        """Type = start or join"""

        #Your code will go here
        user = ctx.message.author
        bank = self.bot.get_cog("Economy").bank
        if type.lower() == "start":
            if self.json_data["System"]["Status"] == "Stopped":
                await self.betAmount(user, bank)
            elif self.json_data["System"]["Status"] == "Waiting":
                if user.id == self.json_data["Players"]["1"] and self.json_data["System"]["Player Count"] > 1:
                    totalPlayers = self.json_data["System"]["Player Count"]
                    await self.startGame(bank, ctx, totalPlayers)
                else:
                    await self.bot.say("Game has been made, to join it type `*rr join`. Only the creator of the roulette can start it and there must be more than 1 person")
            else:
                await self.bot.say("Game is in progress, please wait until it's finished")
        elif type.lower() == "join":
            if self.json_data["System"]["Status"] == "Waiting":
                await self.joinGame(user, bank)
            elif self.json_data["System"]["Status"] == "Stopped":
                await self.bot.say("No game to join, type `*rr start` to create a game")
            else:
                await self.bot.say("Game is in progress, please wait until it's finished")
        elif type.lower() == "stop":
            if self.json_data["System"]["Status"] == "Stopped":
                await self.bot.say("There is no game running to stop")
            elif self.json_data["System"]["Status"] == "Running":
                await self.bot.say("The game is running and can only be stopped when waiting in the lobby")
            if user.id == self.json_data["Players"]["1"]:
                self.json_data["Players"]["1"] = ""
                self.json_data["Players"]["2"] = ""
                self.json_data["Players"]["3"] = ""
                self.json_data["Players"]["4"] = ""
                self.json_data["Players"]["5"] = ""
                self.json_data["Players"]["6"] = ""
                self.json_data["System"]["Player Count"] = 0
                self.json_data["System"]["Status"] = "Stopped"
                self.json_data["System"]["Bet"] = 0
                f = "data/russianroulette/russianroulette.json"
                dataIO.save_json(f, self.json_data)
                await self.bot.say("The roulette has been cancelled")
            else:
                await self.bot.say("You must be the person who started the roulette and you must currently be waiting for people to join")
        else:
            await self.bot.say(user.mention + "This command only accepts `start` `stop` or `join`")

    @client.event
    async def betAmount(self, user, bank):
        await self.bot.say("How much would you like to put on the line: $")
        bet = await self.bot.wait_for_message(timeout=10, author=user)
        if bet is None:
            await self.bot.say("You didn't enter anything")
            return
        try:
            bet = int(str(bet.content))
        except ValueError:
            pass
        if isinstance(bet , int):
            if bank.account_exists(user):
                if bank.get_balance(user) >= bet:
                    self.json_data["System"]["Bet"] = bet
                    self.json_data["Players"]["1"] = user.id
                    self.json_data["System"]["Player Count"] += 1
                    self.json_data["System"]["Status"] = "Waiting"
                    f = "data/russianroulette/russianroulette.json"
                    dataIO.save_json(f, self.json_data)
                    await self.bot.say("Bet placed at $" + str(bet) + "\nTo start the game you need atleast one another person to join with `*rr join`")
                    await self.timeOut()
                else:
                    await self.bot.say("You don't have enough to place a bet of $" + str(bet) + " You only have $" + str(bank.get_balance(user)))
            else:
                await self.bot.say("You don't have a bank account, create one first with `*bank register`")
                return
        else:
            await self.bot.say("You must enter a number")
            await self.betAmount(user, bank)

    async def joinGame(self, user, bank):
        bet = self.json_data["System"]["Bet"]
        if self.json_data["System"]["Player Count"] == 6:
            await self.bot.say("The game is full, please wait until it has finished to join")
        elif bank.account_exists(user):
            if user.id == self.json_data["Players"]["1"] or user.id == self.json_data["Players"]["2"] or user.id == self.json_data["Players"]["3"] or user.id == self.json_data["Players"]["4"] or user.id == self.json_data["Players"]["5"] or user.id == self.json_data["Players"]["6"]:
                await self.bot.say("You're already entered")
            else:
                if bank.get_balance(user) >= bet:
                    await self.bot.say("The bet is set to: $" + str(bet) + "\nWould you still like to enter? Y/N")
                    answer = ""
                    answer = await self.bot.wait_for_message(timeout=10, author=user)
                    answer = str(answer.content)
                    if answer is None or answer.lower() == "n" or answer.lower() == "no":
                        await self.bot.say("Very well, you haven't been entered")
                        return
                    elif answer.lower() == "y" or answer.lower() == "yes":
                        self.json_data["System"]["Player Count"] += 1
                        self.json_data["Players"][str(self.json_data["System"]["Player Count"])] = user.id
                        f = "data/russianroulette/russianroulette.json"
                        dataIO.save_json(f, self.json_data)
                        await self.bot.say("You have been entered. You are in seat: " + str(self.json_data["System"]["Player Count"]))
                        return
                else:
                    await self.bot.say("You don't have enough money. You have $" + str(bank.get_balance(user)) + " The bet is set at $" + str(bet))
                    return
        else:
            await self.bot.say("You don't have a bank account. Make one with `*bank register`")
            return

    async def startGame(self, bank, ctx, totalPlayers):
        i = 1
        a = 1
        await self.bot.say("Game is starting")
        while i <= self.json_data["System"]["Player Count"]:
            bank.withdraw_credits(discord.utils.get(ctx.message.server.members, id=self.json_data["Players"][str(i)]), self.json_data["System"]["Bet"])
            i += 1
        while self.json_data["System"]["Player Count"] > 1:
            await self.play(ctx, a)
            a += 1
        b = 1
        winner = ""
        while winner == "":
            if self.json_data["Players"][str(b)] == "":
                b += 1
            else:
                winner = self.json_data["Players"][str(b)]
        bank.deposit_credits(discord.utils.get(ctx.message.server.members, id=winner), self.json_data["System"]["Bet"] * totalPlayers)
        await self.bot.say("Congrats " + discord.utils.get(ctx.message.server.members, id=winner).mention + " on winning $" + str(self.json_data["System"]["Bet"] * totalPlayers))
        self.json_data["Players"]["1"] = ""
        self.json_data["Players"]["2"] = ""
        self.json_data["Players"]["3"] = ""
        self.json_data["Players"]["4"] = ""
        self.json_data["Players"]["5"] = ""
        self.json_data["Players"]["6"] = ""
        self.json_data["System"]["Player Count"] = 0
        self.json_data["System"]["Status"] = "Stopped"
        self.json_data["System"]["Bet"] = 0
        f = "data/russianroulette/russianroulette.json"
        dataIO.save_json(f, self.json_data)

    async def play(self, ctx, a):
        try:
            if self.json_data["Players"][str((a%7))] == "":
                return
        except KeyError:
            return
        time.sleep(2)
        await self.bot.say(discord.utils.get(ctx.message.server.members, id=self.json_data["Players"][str(a%7)]).mention + " picks up the gun...")
        time.sleep(2)
        await self.bot.say("They pull the trigger...")
        time.sleep(1)
        if randint(1, 20) >= 9:
            await self.bot.say(discord.utils.get(ctx.message.server.members, id=self.json_data["Players"][str((a%7))]).mention + " you're still alive")
        else:
            await self.bot.say(discord.utils.get(ctx.message.server.members, id=self.json_data["Players"][str((a%7))]).mention + " shot their brains out")
            self.json_data["Players"][str((a%6))] = ""
            self.json_data["System"]["Player Count"] += -1
            f = "data/russianroulette/russianroulette.json"
            dataIO.save_json(f, self.json_data)

    async def timeOut(self):
        if self.json_data["System"]["Status"] == "Waiting":
            await asyncio.sleep(120)
            if self.json_data["System"]["Status"] == "Waiting":
                self.json_data["Players"]["1"] = ""
                self.json_data["Players"]["2"] = ""
                self.json_data["Players"]["3"] = ""
                self.json_data["Players"]["4"] = ""
                self.json_data["Players"]["5"] = ""
                self.json_data["Players"]["6"] = ""
                self.json_data["System"]["Player Count"] = 0
                self.json_data["System"]["Status"] = "Stopped"
                self.json_data["System"]["Bet"] = 0
                f = "data/russianroulette/russianroulette.json"
                dataIO.save_json(f, self.json_data)
                await self.bot.say("The game wasn't started within 2 minutes and has been cancelled")
                return

def check_folders():
    if not os.path.exists("data/russianroulette"):
        print("Creating data/russianroulette floder...")
        os.makedirs("data/russianroulette")

def check_files():
    system = {"System": {"Bet": 0,
                         "Status": "Stopped",
                         "Player Count": 0},
              "Players": {"1": "",
                          "2": "",
                          "3": "",
                          "4": "",
                          "5": "",
                          "6": ""}}
    f = "data/russianroulette/russianroulette.json"
    if not dataIO.is_valid_json(f):
        print("Creating defualt russianroulette.json...")
        dataIO.save_json(f, system)

def setup(bot):
    check_folders()
    check_files()
    n = Russianroulette(bot)
    bot.add_cog(n)
<|endoftext|>