示例#1
0
def main(args, curr_dir):
    np.set_printoptions(precision=5, threshold=np.inf)
    logger.set_up_pyrklog(args.logfile)
    infile = load_infile(args.infile)
    out_db = database.Database(filepath=args.outfile)
    if not hasattr(infile, 'n_ref'):
        n_ref = 0
    else:
        n_ref = infile.n_ref
    si = sim_info.SimInfo(timer=infile.ti,
                          components=infile.components,
                          iso=infile.fission_iso,
                          e=infile.spectrum,
                          n_precursors=infile.n_pg,
                          n_decay=infile.n_dg,
                          n_fic=n_ref,
                          kappa=infile.kappa,
                          feedback=infile.feedback,
                          rho_ext=infile.rho_ext,
                          plotdir=args.plotdir,
                          infile=args.infile,
                          db=out_db)
    # TODO: think about weather to add n_ref to all input files, or put n_ref in
    # database files
    print_logo(curr_dir)
    sol = solve(si=si, y=si.y, infile=infile)
    log_results(si)
    out_db.close_db()
    pyrklog.critical("\nSimulation succeeded.\n")
示例#2
0
文件: tax.py 项目: Rettend/BuffBot
 def __init__(self, bot):
     self.bot = bot
     self.taxable = True
     self.database = database.Database(self.bot)
     self.tax_amount_percentage = 0.20
     self.wealth_tax_percentage = 0.10
     self.is_wealthy = 5000  # Users with this amount of coins or greater has to pay wealthTax
     self.WEALTH_TAX_INTERVAL = 60  # Interval for wealth tax.
示例#3
0
 def __init__(self, bot):
     self.bot = bot  # The bot object.
     self.database = database.Database(self.bot)  # database object -> used to update and get coin amount
     self.blackjack_players = []
     self.blackjack_game_status = 0
     self.deck = []
     self.coins = Coin(bot)
     self.dealerCards = []
示例#4
0
文件: coins.py 项目: Rettend/BuffBot
 def __init__(self, bot):
     self.bot = bot  # The bot object.
     self.coinActive = True  # If this is set to false, the coin interval is stopped.
     self.database = database.Database(
         self.bot)  # database object -> used to update and get coin amount
     self.tax = tax.Tax(
         self.bot)  # Tax object used to get the value of taxable
     self.COIN_AMOUNT = 1  # amount of coins to be given every interval
     self.COIN_INTERVAL = 30  # interval in seconds for sending out coins.
示例#5
0
文件: voice.py 项目: Dasister/BuffBot
 def __init__(self, bot):
     self.bot = bot
     self.voice = None
     self.player = None
     self.volume = 1.0
     self.database = database.Database()
     self.playlist = playlist.Queue()
     self.people_voted = []
     self.seconds_to_next = 0
     self.music_server = None
示例#6
0
 def __init__(self, bot):
     self.bot = bot
     self.database = database.Database(self.bot)
     self.coins = Coin(bot)
     # self.lotteryTickets = {} // Different implementation
     self.ticketCost = 100
     self.winningTicket = 0
     self.ticketCounter = 0
     self.prizePool = 0
     self.generate_tickets(100)
示例#7
0
def main():
    username = '******'
    token = config.OAUTH_TOKEN
    channels = ['deviousdata']
    # comment batch size before database insertion
    max_batch_size = 1  # hint: larger batch sizes are more efficient

    # initialize PostgreSQL database
    twitch_database = database.Database(filename='db/database.ini',
                                        section='postgresql')

    # initialize chat bot
    bot = chatbot.ChatBot(twitch_database, username, token, channels)

    # create tables in database, if they don't already exist
    twitch_database.create_tables(filename='db/twitch_chat_tables.sql')

    # connect to twitch chat and log user messages
    bot.connect(max_batch_size)
示例#8
0
    def __init__(self,
                 timer=Timer(),
                 components={},
                 iso="u235",
                 e="thermal",
                 n_precursors=6,
                 n_decay=11,
                 n_fic=0,
                 kappa=0.0,
                 rho_ext=None,
                 feedback=False,
                 plotdir='images',
                 infile=None,
                 sim_id=None,
                 db=None):
        """This class holds information about a reactor kinetics simulation

        :param timer: the Timer object for the simulation
        :type timer: Timer
        :param components: the components making up the reactor
        :type components: dictionary
        :param iso: the main fissioning isotope, decides precursor data
        :type iso: only a few values are supported. see PrecursorData class
        :param e: spectrum ("fast", "thermal", etc.)
        :type e: string
        :param n_precursors: number of delayed precursor groups
        :type n_precursors: int
        :param n_decay: number of decay groups
        :type n_decay: int
        :param n_fic: number of fictitious neutron groups for multi
        point kinetics
        :type n_fic: int
        :param kappa: the value for kappa, a decay heat parameter
        :type kappa: float
        :param rho_ext: external reactivity
        :type rho_ext: a ReactivityInsertion object or None
        :param feedback: is reactivity feedback present in the simulation
        :type feedback: bool
        :param plotdir: the directory where the plots will be placed
        :type plotdir: string
        """
        self.timer = timer
        self.components = components
        self.iso = iso
        self.e = e
        self.n_pg = n_precursors + n_fic
        self.n_dg = n_decay
        self.rho_ext = self.init_rho_ext(rho_ext)
        self.feedback = feedback
        self.ne = self.init_ne()
        self.kappa = kappa
        self.th = th_system.THSystem(kappa=kappa, components=components)
        self.y = np.zeros(shape=(timer.timesteps(), self.n_entries()),
                          dtype=float)
        self.plotdir = plotdir
        self.infile = infile
        if sim_id is not None:
            self.sim_id = sim_id
        else:
            self.sim_id = self.generate_sim_id()

        if db is not None:
            self.db = db
        else:
            self.db = database.Database()
        self.register_recorders()
示例#9
0
 def __init__(self, bot):
     self.bot = bot
     self.voice = None
     self.player = None
     self.volume = 1.0
     self.database = database.Database()
示例#10
0
from db import database

# Set this variable to "threading", "eventlet" or "gevent" to test the
# different async modes, or leave it set to None for the application to choose
# the best option based on installed packages.
async_mode = None

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, async_mode=async_mode)

players_in_game = {}  # username -> game
players_in_lobby = []  # usernames
username_to_player = {}  # username -> player
session_to_username = {}
db = database.Database()


@app.route('/')
def index():
    return render_template('index.html', async_mode=socketio.async_mode)


@app.route('/highscores')
def highscores():
    return render_template('highscores.html')


@app.route('/bots')
def bots():
    return render_template('bots.html')
from http_client import client
from dateutil.relativedelta import relativedelta
from datetime import datetime
from services import tracks_service
import math
from db import database
from models.item_model import ItemModel
import traceback
import time

database = database.Database()
tracksService = tracks_service.TracksService()


class UsersService:

    httpClient = client.HttpClient()

    def getUsers(self, last):
        users = []
        last = None

        result = ItemModel.scan(ItemModel.date == '2020-01-01',
                                attributes_to_get=['user'],
                                limit=10,
                                last_evaluated_key=last)

        for rep in result:
            userData = rep.to_dict()
            user = userData['user']
            users.append(user)
示例#12
0
文件: holdem.py 项目: Rettend/BuffBot
    def __init__(self, bot):
        self.bot = bot
        self.database = database.Database(self.bot)
        self.holdem_players = []
        self.game_status = 0
        self.deck = []
        self.dealersHand = []
        self.coins = Coin(bot)

        # TODO: Command: holdem new, join, start, Call, raise, fold
        # TODO: Gather players

        @commands.group(name="holdem", pass_context=True)
        async def holdem(self, ctx):
            if ctx.invoked_subcommand is None:
                await self.bot.say(
                    "This is not a valid command, please add a subcommand")

        @holdem.command(name="new", pass_context=True)
        async def new_game(self, ctx):
            if self.game_status != 0:
                self.bot.say("A game is already running, please wait to join")
                return None,
            self.deck = self.generateDeck()
            self.game_status = 1
            welcome_msg =   "_______                   _    _       _     _\n" \
                          " |__   __|                 | |  | |     | |   | |               \n" \
                          "    | | _____  ____ _ ___  | |__| | ___ | | __| | ___ _ __ ___  \n" \
                          "    | |/ _ \ \/ / _` / __| |  __  |/ _ \| |/ _` |/ _ | '_ ` _ \ \n" \
                          "    | |  __/>  | (_| \__ \ | |  | | (_) | | (_| |  __| | | | | |\n" \
                          "    |_|\___/_/\_\__,_|___/ |_|  |_|\___/|_|\__,_|\___|_| |_| |_|\n"
            await self.bot.say(
                welcome_msg, "A Texas Hold'em table has opened"
                "Please use !holdem join <Blind> to join the table")

        @holdem.command(name="join", pass_context=True)
        async def join_game(self, ctx, bet):
            user = ctx.message.author
            if self.game_status != 1:
                await self.bot.say(
                    "No tables are open, please open one to play")
                return None

            if self.players_at_table(ctx.message.author):
                await self.bot.say(user.mention +
                                   "You're seated and ready to play")
                return None

            if float(bet) <= 0 and not self.coins.check_balance(bet):
                await self.bot.say(user.mention +
                                   " please make sure your bet is higher"
                                   "than 0 and that you've got enough coins")
                return None

            self.database.remove_coins(userid=user.id,
                                       coins=float(bet),
                                       mention=user.mention)

            # TODO : Make drawcard Dynamic
            self.holdem_players.append({
                "user":
                user,
                "cards": [self.drawCard(), self.drawCard()],
                "bet":
                float(bet),
                "Status":
                0
            })

            await self.bot.say(
                user.mention +
                " You've joined the table, please wait for the game to start,")

        @holdem.command(name="start", pass_context=True)
        async def start_game(self, ctx):

            if len(self.holdem_players) < 2:
                await self.bot.say(
                    "There needs to be at least 2 players at the table")
                return None
            # TODO: Solve this when you use the join command
            elif len(self.holdem_players) > 9:
                await self.bot.say("There are too many people at the table")
                return None

            self.game_status = 3
            self.dealersHand = [self.drawCard(), self.drawCard()]

            start_msg = "Let's play Texas Hold'em!"
            await self.bot.say(start_msg)

            for player in self.holdem_players:
                self.bot.send_message(
                    player["user"], "This is your hand: " +
                    player['cards'][0].getStringSymbol() +
                    player['cards'][0].getStringValue())
                pass

            community_cards_msg = "Here are the community cards: " + \
                         self.dealerCards[0].getStringSymbol() + self.dealerCards[0].getStringValue()
            await self.bot.say(community_cards_msg)

        @holdem.command(name="Call", pass_context=True)
        async def holdem_call(self, ctx):
            player = self.players_at_table(ctx.message.author)
            if player is None:
                await self.bot.say("You're not at this table, " +
                                   ctx.message.author.mention)
                return None

            if player["status"] != 0:
                await self.bot.say(ctx.message.author.mention +
                                   " is calling the bet")
                return None
            pass

        @holdem.command(name="raise", pass_context=True)
        async def holdem_stand(self, ctx, bet_raise):
            player = self.players_at_table(ctx.message.author)
            if player is None:
                await self.bot.say("You're not at this table, " +
                                   ctx.message.author.mention)
                return None

            if bet_raise <= 0 or None:
                await self.bot.say(ctx.message.author.mention +
                                   "You need to specify a bet")
                return None

            for player in self.players_at_table:
                if player["name"] == player:
                    player["bet"] += bet_raise

            await self.bot.say(ctx.message.author.mention + " Raised the bet")
示例#13
0
# Another, different, factory for the same object
import datetime
import factory
import factory.fuzzy
import random
from sqlalchemy import Table, Sequence, MetaData, create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker, scoped_session
from db import database, tables

db = database.Database('sqlite:///test/borrower.db', echo=False)

# # generate the database schema
# tables.Base.metadata.create_all(engine)

# # create a configured "Session" class
# Session = scoped_session(sessionmaker(bind=engine))


class BorrowerFactory(factory.alchemy.SQLAlchemyModelFactory):
    class Meta:
        model = tables.Borrower
        sqlalchemy_session = db.session  # the SQLAlchemy session object

    id = factory.Sequence(lambda n: n)
    appid = factory.Sequence(lambda n: '%s' % n)
    ApplicationDate = factory.LazyFunction(datetime.datetime.now)
    FirstName = factory.Sequence(lambda n: 'john%s' % n)
    LastName = factory.Sequence(lambda n: 'Bolton%s' % n)
    MiddleName = factory.Sequence(lambda n: 'S%s' % n)
    Alias = factory.fuzzy.FuzzyText()
    Sex = "Male"
示例#14
0
import socket

import os, sys
currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)

from db import database as database

import logging

HOST = '127.0.0.1'  # Standard loopback interface address (localhost)
PORT = 65432  # Port to listen on (non-privileged ports are > 1023)

db = database.Database('vsmdb_poc', load=False)
#try:
#    db.drop_table('classroom')
#except:
#    pass
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    conn, addr = s.accept()
    try:
        with conn:
            print('Connected by', addr)
            while True:
                data = conn.recv(1024)
                data = data.decode('utf-8')
                #send_query(data)
                #a = str(sqlInterpreter.main(query=data))
示例#15
0
 def __init__(self, bot):
     self.bot = bot  # The bot object.
     self.database = database.Database(
         self.bot)  # database object -> used to update and get coin amount
示例#16
0
 def setUp(self):
     "set up test fixtures"
     self.a = d.Database(mode='w')
     self.custom = d.Database(filepath='testfile.h5', mode='w')
示例#17
0
import sys
from ui_action import app
from db import database


if __name__ == "__main__":
    db = database.Database('sqlite:///db/borrower.db', echo=True)
    app.run(db)