Пример #1
0
async def add(msg, *args):
    if (len(args) != 2):
        await msg.send(".add <nom> <distance>")
    else:
        id = msg.author.id
        add_dico(args[0], id, args[1])
        printd()
Пример #2
0
 def send_data(self, data):
     msg = pickle.dumps(data)
     for addr in self.addresses:
         # DROP_RATE is zero if DEBUG is set to false
         if random.random() >= constants.DROP_RATE:
             self.s.sendto(msg, addr)
         else:
             printd("SERVER: dropping packet")
Пример #3
0
def main():
    clear_log()
    acSys = AccessSystem(CARDS_FILE)
    try:
        acSys.run_access_control()
    except:
        GPIO.cleanup()
        printd('Finished cleaning up ... Done.')
Пример #4
0
 def __init__(self, engine, server_host, server_port):
   self.engine = engine
   self.s = socket.socket(constants.S_FAMILY, constants.S_TYPE)
   self.s.settimeout(constants.S_START_TIMEOUT)
   self.server_host = server_host # init these before calling wait_to_start
   self.server_port = server_port
   game_start_data = self.wait_to_start()
   self.engine.set_game_start_data(game_start_data)
   self.local_player_id = game_start_data.get_player_id()
   print("CLIENT: Game started!")
   printd("My id is: {0}".format(self.local_player_id))
   self.n_dropped = 0
Пример #5
0
 def run_access_control(self):
     printd('Starting access control system ...')
     while True:
         # read RFID card reader
         card_num = self.card_reader.read_card()
         # read cards file
         cards_dic = self._read_cards_file()
         # check permission
         if card_num in cards_dic.keys():
             name = cards_dic[card_num]
             self._grant_access(name)
         elif card_num is not None:
             self._deny_access(card_num)
Пример #6
0
    def __init__(self):
        # find the RFID card reader device
        devices = [evdev.InputDevice(fn) for fn in evdev.list_devices()]

        rfid_devs = [d for d in devices if 'RFID' in d.name]
        if len(rfid_devs) == 0:
            printd('ERROR: No RFID devices found... exiting')
            sys.exit(1)

        self.rfid_dev = rfid_devs[0]

        if len(rfid_devs) > 1:
            printd('WARNING: Multiple RFID devices found... using: {}'.format(
                self.rfid_dev.name))
Пример #7
0
def get_trans(price_map, tickers, date, holding_period):
  trans = []
  for ticker in tickers:
    bdate, bprice = utils.get_price(price_map, ticker, date)
    if bdate is None or bprice is None:
      continue
    tdate = (datetime.datetime.strptime(bdate, '%Y-%m-%d') + holding_period).strftime('%Y-%m-%d')
    sdate, sprice = utils.get_price(price_map, ticker, tdate)
    if sdate is None or sprice is None:
      if utils.is_ticker_dead(price_map, ticker):
        utils.printd('!! %s dead' % ticker)
        sdate, sprice = tdate, 0
      else:
        continue
    trans.append([ticker, bdate, bprice, sdate, sprice])
  return trans
Пример #8
0
 def _read_cards_file(self):
     cards_dic = {}
     with open(self.cards_file) as f:
         for line in f:
             line_vals = [s.strip() for s in line.split(',')]
             if len(line_vals) != 2:
                 printd(
                     'ERROR: invalid line in cards file: {}'.format(line))
             else:
                 try:
                     num = int(line_vals[0])
                     name = line_vals[1]
                 except ValueError as e:
                     printd('ERROR: invalid card number on line: {}'.format(
                         line))
                 cards_dic[num] = name
     return cards_dic
Пример #9
0
  def update_engine(self):
    """Whenever the client wants to update the state of the game, it should call
    this method. This will return the appropriate engine, which will either have
    been updated because it received something from the server, or
    because it predicted something while waiting for the server to reply."""
    try:
      data, addr = self.s.recvfrom(1024)
      update_received = pickle.loads(data)
      if isinstance(update_received, str):
        print(update_received)
        sys.exit()
      self.engine.update(update_received)
    except socket.timeout:
      printd("CLIENT: nothing received. # dropped = {0}".format(self.n_dropped))
      self.n_dropped += 1
      self.engine.update_default()

    return self.engine
Пример #10
0
    def get_updates_from_clients(self):
        waiting_for = list(self.addresses)  # to get a copy not pointer
        # for i in range(len(self.addresses)): #TODO: maybe make this smarter
        data = ""
        while len(waiting_for) > 0:
            try:
                data, addr_recv = self.s.recvfrom(1024)
            except socket.timeout:
                printd("SERVER: no data received")
            if len(data) > 0 and addr_recv in waiting_for:
                player_update = pickle.loads(data)
                player_id = self.addr_to_player_id_map[addr_recv]
                status_message = self.engine.update_player(player_id, player_update)
                if status_message == constants.GAME_OVER_MESSAGE:
                    self.close_conns()
                    sys.exit()
                waiting_for.remove(addr_recv)

        self.engine.update_positions()
Пример #11
0
 def read_card(self):
     # lock the device
     self.rfid_dev.grab()
     # read the digits
     digits = []
     for event in self.rfid_dev.read_loop():
         if event.type == evdev.ecodes.EV_KEY:
             data = evdev.categorize(event)
             if data.keycode == 'KEY_ENTER':
                 break
             if data.keystate == 1:  # the key is pressed down
                 digits.append(data.keycode.replace('KEY_', ''))
     # unlock the device
     self.rfid_dev.ungrab()
     input_str = ''.join(digits)
     try:
         card_num = int(input_str)
         return card_num
     except ValueError as e:
         card_num = -1
         if input_str != '':
             printd(
                 'ERROR: Invalid card number entered: {}'.format(input_str))
Пример #12
0
def main():
  if len(sys.argv) > 1:
    print(sys.argv[1])
    client = Client(Engine(), sys.argv[1], constants.SERVER_PORT)
  else:
    client = Client(Engine(), constants.SERVER_ADDR, constants.SERVER_PORT)

  gd = client.get_game_start_data()
  field = Gui(gd.width, gd.height, 1.0)
  engine = client.update_engine()
  players = engine.get_players()
  printd("CLIENT: players = {0}".format(players))
  game = Game(players) # TODO: figure out if we want to bother passing this

  # up, down, left, right
  dirs = (0, 0, 0, 0)
  while True:
    start_time = time.time()

    #get input
    dirs = game.get_input(dirs)

    #talk to server
    client.update_player(PlayerUpdate(dirs))    #send my velocity to the server
    engine = client.update_engine()
    game.players = engine.get_players()

    #draw
    field.fill_black()
    for p in game.players:
      field.draw_player(p.get_pos(), p.get_color(), gd.radius, p.is_it())
    pygame.display.flip()

    sleep_time = constants.LOOP_TIME - (time.time() - start_time)
    if sleep_time > 0:
      time.sleep(sleep_time)
Пример #13
0
def main():
  parser = argparse.ArgumentParser()
  parser.add_argument('--price_map_file', required=True)
  parser.add_argument('--ticker_file', required=True)
  parser.add_argument('--ranking_dir', required=True)
  parser.add_argument('--k', required=True)
  parser.add_argument('--h', required=True)
  parser.add_argument('--real', action='store_true')
  args = parser.parse_args()

  with open(args.ticker_file, 'r') as fp:
    ticker_filter = set(fp.read().splitlines())
  utils.printd('simulating %d tickers' % len(ticker_filter))

  k = int(args.k)
  h = int(args.h)
  assert h > 0
  holding_period = datetime.timedelta(days=h)

  dates = sorted([f[:f.find('.')] for f in os.listdir(args.ranking_dir) if f.endswith('.csv')])
  utils.printd('simulating %d dates' % len(dates))

  utils.printd('loading price map...')
  price_map = utils.read_price_map(args.price_map_file)
  utils.printd('done, %d entries in the price map' % len(price_map))

  all_trans, all_mtrans = [], []
  for date in dates:
    ranking_file = '%s/%s.csv' % (args.ranking_dir, date)
    tickers = utils.read_tickers_by_filter(ranking_file, k, ticker_filter)
    trans = get_trans(price_map, tickers, date, holding_period)
    if len(trans) == 0:
      utils.printd('no trans for %s' % date)
      continue
    mtickers = utils.read_tickers_by_filter(ranking_file, 0, ticker_filter)
    mtrans = get_trans(price_map, mtickers, date, holding_period)
    utils.printd('%s (ranking): %s' % (date, utils.get_string(trans, h, args.real)))
    utils.printd('%s (market): %s' % (date, utils.get_string(mtrans, h, args.real)))
    all_trans.extend(trans)
    all_mtrans.extend(mtrans)
  utils.printd('all (ranking): %s' % utils.get_string(all_trans, h, args.real))
  utils.printd('all (market): %s' % utils.get_string(all_mtrans, h, args.real))
  gains = utils.get_gains(all_trans, args.real)
  avg_gain = sum(gains)/len(gains)
  print(avg_gain/h*100)
  mgains = utils.get_gains(all_mtrans, args.real)
  avg_mgain = sum(mgains)/len(mgains)
  print(avg_mgain/h*100)
Пример #14
0
 def _deny_access(self, num):
     printd('Access Denied for card: {}'.format(num))
     GPIO.output(OUT_PIN, False)
Пример #15
0
 def _grant_access(self, name):
     printd('Access Granted for {}'.format(name))
     GPIO.output(OUT_PIN, True)
     time.sleep(UNLOCK_TIME)
     GPIO.output(OUT_PIN, False)
Пример #16
0
def main():
  parser = argparse.ArgumentParser()
  parser.add_argument('--price_map_file', required=True)
  parser.add_argument('--ticker_filter_file')
  parser.add_argument('--ranking_dir', required=True)
  parser.add_argument('--k', required=True)
  parser.add_argument('--h', required=True)
  parser.add_argument('--real', action='store_true')
  parser.add_argument('--market_data_file')
  args = parser.parse_args()

  ticker_filter = set()
  if args.ticker_filter_file:
    with open(args.ticker_filter_file, 'r') as fp:
      ticker_filter = set(fp.read().splitlines())
  utils.printd('filtering %d tickers' % len(ticker_filter))

  k = int(args.k)
  h = int(args.h)
  assert h > 0
  holding_period = datetime.timedelta(days=h)

  dates = sorted([f[:f.find('.')] for f in os.listdir(args.ranking_dir) if f.endswith('.csv')])
  utils.printd('simulating %d dates' % len(dates))

  utils.printd('loading price map...')
  price_map = utils.read_price_map(args.price_map_file)
  utils.printd('done, %d entries in the price map' % len(price_map))

  if len(ticker_filter) > 0:
    index = None
  elif k > 0:
    index = range(1, k+1)
  else:
    index = range(-1, k-1, -1)
  all_trans = []
  for date in dates:
    ranking_file = '%s/%s.csv' % (args.ranking_dir, date)
    if len(ticker_filter) > 0:
      tickers = utils.read_tickers_by_filter(ranking_file, k, ticker_filter)
    else:
      tickers = utils.read_tickers_by_index(ranking_file, index)
    trans = get_trans(price_map, tickers, date, holding_period)
    if len(trans) == 0:
      continue
    utils.printd('%s: %s' % (date, utils.get_string(trans, h, args.real)))
    all_trans.extend(trans)
  utils.printd(utils.get_string(all_trans, h, args.real))
  gains = utils.get_gains(all_trans, args.real)
  avg_gain = sum(gains)/len(gains)
  print(avg_gain/h*100)

  if args.market_data_file:
    mtrans = utils.simulate_market_trans(all_trans, args.market_data_file)
    utils.printd('market:')
    utils.printd(utils.get_string(mtrans, h, False))
    sharpe = utils.compute_sharpe_ratio(all_trans, mtrans, args.real)
    utils.printd('sharpe ratio: %.4f' % sharpe)
    print(sharpe)
Пример #17
0
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

"""
Simulation of Concourse quickstart as if it were done in a Python REPL session.
"""

from concourse import Concourse, Link, TransactionException
from utils import printd, pprintd
import time

printd('# Lets start with some data that describes the employees in a company:')
data = [
    {
        'name': 'John Doe',
        'department': 'Engineering',
        'title': 'Senior Software Engineer',
        'role': 'Software Engineer - Backend',
        'manager': Link.to_where('title = Director of Engineering'),
        'salary': 10.00,
        'location': 'Atlanta',
        'exempt': True
    },
    {
        'name': 'Jane Doe',
        'department': 'Engineering',
        'title': 'Director of Engineering',
Пример #18
0
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

"""
Simulation of Concourse quickstart as if it were done in a Python REPL session.
"""

from concourse import Concourse, Link, TransactionException
from utils import printd, pprintd
import time

printd('# Lets start with some data that describes the employees in a company:')
data = [
    {
        'name': 'John Doe',
        'department': 'Engineering',
        'title': 'Senior Software Engineer',
        'role': 'Software Engineer - Backend',
        'manager': Link.to_where('title = Director of Engineering'),
        'salary': 10.00,
        'location': 'Atlanta',
        'exempt': True
    },
    {
        'name': 'Jane Doe',
        'department': 'Engineering',
        'title': 'Director of Engineering',