<commit_before>#!/usr/bin/env python
import requests
import time, datetime
from datetime import datetime
import bottle
import logging
import argparse
import ast
from bottle import run, route, get, post, request, response
import json
import config_manager as conf_man
import task_executor_utils as utils
import os
import applications as apps
import s3_utils as s3
import dynamo_utils as dutils
import re
import shutil
import sys
import sts
import seppukku
import sns_sqs
import inspect

metadata_server="http://169.254.169.254/latest/meta-data/"
clean_tmp_dirs = False

def get_instance_starttime() :
   try:
      data = requests.get(metadata_server + "local-ipv4")
      last_mod = data.headers['last-modified']
      return datetime.strptime(last_mod, "%a, %d %b %Y %H:%M:%S %Z")
   except e:
      print "Caught exception : {0}".format(e)

def get_metainfo() :
   try:
      data = requests.get(metadata_server + "")
      last_mod = data.headers['last-modified']
      return datetime.strptime(last_mod, "%a, %d %b %Y %H:%M:%S %Z")
   except e:
      print "Caught exception : {0}".format(e)

##################################################################
# A rudimentary times for coarse-grained profiling
##################################################################
class Timer(object):
   def __init__(self, verbose=False):
      self.verbose = verbose

      def __enter__(self):
         self.start = time.time()
         return self

      def __exit__(self, *args):
         self.end = time.time()
         self.secs = self.end - self.start
         self.msecs = self.secs * 1000  # millisecs
         if self.verbose:
            print 'elapsed time: %f ms' % self.msecs

def get_inputs(app, inputs, auth):

   try:
      print "Attempting to switch roles to : {0}".format(auth["role"])
      creds = sts.get_temp_creds(auth["role"])
      sts.print_creds(creds)
      s3conn  = s3.get_s3_conn( creds["AccessKeyId"],
                                creds["SecretAccessKey"],
                                creds["SessionToken"] )

   except Exception as e:
      print "Caught exception : {0}".format(e)
      raise

   print "In get_inputs"
   if not inputs:
      return

   for i in inputs:
      print "Staging_inputs : ", i

      if i["src"].startswith("http://"):
         print "Downloading {0} via http".format(i["src"])
         utils.download_file(i["src"], i["dest"])

      elif re.search("https://s3.*amazonaws.com/", i["src"]):
         s3_path = re.sub("https://s3.*amazonaws.com/", "", i["src"])
         tmp     = s3_path.split('/', 1)
         s3_bucket = tmp[0]
         s3_key    = tmp[1]
         print "Downloading {0} via s3 provider".format(i["src"])
         try:
            s3.smart_download_s3_keys(s3conn,
                                      s3_bucket,
                                      s3_key,
                                      i["dest"],
                                      creds)
         except Exception as e:
            print "Download from s3 failed {0}".format(e)
            raise

      elif i["src"].startswith("s3://"):

         s3_path   = i["src"].strip("s3://")
         tmp       = s3_path.split('/', 1)
         s3_bucket = tmp[0]
         s3_key    = tmp[1]
         print "Downloading {0} via s3 provider".format(i["src"])
         try:
            s3.smart_download_s3_keys(s3conn,
                                      s3_bucket,
                                      s3_key,
                                      i["dest"],
                                      creds)
         except Exception as e:
            print "Download from s3 failed {0}".format(e)
            raise

      else:
         print "No match. Could not fetch data"

   return

def put_outputs(app, outputs):
   print "In put_outputs"
   if not outputs:
      return

   for out in outputs:
      print "Outputs : ", out
      '''
      if not os.path.exists(out["src"]):
         print "Missing file. Continuing"
         continue
      '''
      target = out["dest"].split('/', 1)
      try:
         s3.smart_upload_s3_keys(app.config["s3.conn"],
                                out["src"], # Source filename
                                target[0],  # Bucket name
                                target[1],  # Prefix
                                {"Owner": "Yadu"})

      except Exception as e:
         print "Upload to s3 failed {0}".format(e)

   return

def update_record(record, key, value):
   record[key] = value
   record.save(overwrite=True)
   return

def exec_job(app, jobtype, job_id, executable, args, inputs, outputs, data, auth):

   # Save current folder and chdir to a temporary folder
   conf_man.update_creds_from_metadata_server(app)
   record = dutils.dynamodb_get(app.config["dyno.conn"], job_id)

   ##############################################################################
   # Notify job execution start time
   ##############################################################################
   update_record(record, "start_time", time.time())

   ##############################################################################
   # Setup dirs for execution
   ##############################################################################
   cwd    = os.getcwd()
   tmpdir = "/tmp/task_executor_jobs/{0}".format(job_id)
   try:
      os.makedirs(tmpdir)
   except:
      print "Tmpdir {0} exists. Deleting and recreating".format(tmpdir)
      shutil.rmtree(tmpdir)
      os.makedirs(tmpdir)
   os.chdir(tmpdir)

   ##############################################################################
   # Download the inputs to the temp folder
   ##############################################################################
   update_record(record, "status", "staging_inputs")
   stagein_start = time.time()
   try:
      get_inputs(app, inputs, auth)
   except Exception as e:
      print "Exception info : ".format(sys.exc_info()[0])
      update_record(record, "ERROR", "Failed to download inputs {0}".format(e))
      update_record(record, "status", "failed")
      update_record(record, "complete_time", time.time())
      logging.error("Failed to download inputs")
      return False
   stagein_total = time.time() - stagein_start

   ##############################################################################
   # Download the inputs to the temp folder
   ##############################################################################
   # Check if job is valid
   update_record(record, "status", "processing")
   if jobtype not in apps.JOBS:
      logging.error("Jobtype : {0} does not exist".format(jobtype))
      print "Unable to process jobtype : {0}".format(jobtype)
      return False
   print "JOBS : ", apps.JOBS[jobtype]

   status = True
   returncode = 0
   process_start = time.time()
   try:
      returncode = apps.JOBS[jobtype](app, data)
      print "Returncode : {0}".format(returncode)
      conf_man.update_creds_from_metadata_server(app)

   except Exception as e:
      update_record(record, "status", "Failed");
      update_record(record, "complete_time", time.time())
      update_record(record, "ERROR", str(e));
      print "Job execution failed : {0}".format(e)
      status = False
   process_total = time.time() - process_start

   ##############################################################################
   # Upload the results to the S3
   ##############################################################################
   record = dutils.dynamodb_get(app.config["dyno.conn"], job_id)
   update_record(record, "status", "staging_outputs")
   stageout_start = time.time()

   # Upload the result to S3
   try:
      put_outputs(app, outputs)
   except Exception as e:
      print "Exception info : ".format(sys.exc_info()[0])
      update_record(record, "ERROR", "Failed to upload outputs {0}".format(e))
      update_record(record, "status", "failed")
      update_record(record, "complete_time", time.time())
      logging.error( "Failed to upload inputs")
      return False
   stageout_total = time.time() - stageout_start

   update_record(record, "z_stagein_dur",    stagein_total)
   update_record(record, "z_stageout_dur",   stageout_total)
   update_record(record, "z_processing_dur", process_total - 1)

   if returncode != 0 :
      update_record(record, "status", "failed");
      update_record(record, "complete_time", time.time())
      update_record(record, "ERROR_CODE", returncode);
      status = False
   else:

      update_record(record, "status", "completed")
      update_record(record, "complete_time", time.time())

   if clean_tmp_dirs:
      shutil.rmtree(tmpdir)
   # Chdir back to the original folder
   os.chdir(cwd)
   return True

def task_loop(app):
   sqs_conn  = app.config["sqs.conn"]
   pending   = app.config["instance.tags"]["JobsQueueName"]
   active    = app.config["instance.tags"]["ActiveQueueName"]
   pending_q = sqs_conn.get_queue(pending)
   active_q  = sqs_conn.get_queue(active)

   while 1:
      # Wait to read a message from the pending_q
      msg = pending_q.read(wait_time_seconds=20)

      print "Received message from pending_q"
      if msg:
         # Too many things could fail here, do a blanket
         # Try catch
         try:

            sreq = json.loads(msg.get_body())["Message"]
            if not sreq :
               continue

            app.config["current_msg_handle"] = msg

            data        =  ast.literal_eval(sreq)
            job_id      =  data.get('job_id')
            jobtype     =  data.get('jobtype')
            executable  =  data.get('executable')
            args        =  data.get('args')
            inputs      =  data.get('inputs')
            inputs      =  data.get('inputs')
            outputs     =  data.get('outputs')
            user_auth   =  {"user"      : data.get('i_user_id'),
                            "role"      : data.get('i_user_role'),
                            "token"     : data.get('i_token'),
                            "keyid"     : data.get('i_keyid'),
                            "keysecret" : data.get('i_keysecret')}

            # Post the job to the active queue and delete it from the pending queue
            attr, current_msg = sns_sqs.post_message_to_active(app, active_q, msg.get_body(), job_id)
            print "Posted job from pending to active queue"
            if not pending_q.delete_message(msg):
               print "Deleting message from pending queue failed"

            for key in data:
               print "{0} : {1}".format(key, data[key])

            print "Starting task"
            status      =  exec_job(app,
                                    jobtype,
                                    job_id,
                                    executable,
                                    args,
                                    inputs,
                                    outputs,
                                    data,
                                    user_auth)

            print "Status : ", status

            if status == True:
               conf_man.send_success_mail(data, app)
            else:
               conf_man.send_failure_mail(data, app)

            # TODO : CLeanup
            print "At deletion : ", msg
            #res = active_q.delete_message(current_msg)
            if not  sns_sqs.delete_message_from_active(sqs_conn, active_q, attr):
               print "Messages deleted : ", count

         except Exception as e:
               print "Job failed to complete : {0}".format(sys.exc_info()[0])
               print "Trace : ", inspect.trace()
               if not  sns_sqs.delete_message_from_active(sqs_conn, active_q, attr):
                  print "Messages deleted : ", count

      else:
         print "{0}: Waiting for job description".format(time.time())
         seppukku.die_at_hour_edge(app, dry_run=True)
         logging.debug("{0}: Waiting for job description".format(time.time()))

      conf_man.update_creds_from_metadata_server(app)

if __name__ == "__main__":

   parser   = argparse.ArgumentParser()
   parser.add_argument("-v", "--verbose", default="DEBUG", help="set level of verbosity, DEBUG, INFO, WARN")
   parser.add_argument("-l", "--logfile", default="task_executor.log", help="Logfile path. Defaults to ./task_executor.log")
   parser.add_argument("-c", "--conffile", default="test.conf", help="Config file path. Defaults to ./test.conf")
   parser.add_argument("-j", "--jobid", type=str, action='append')
   parser.add_argument("-i", "--workload_id", default=None)
   args   = parser.parse_args()

   if args.verbose not in conf_man.log_levels :
      print "Unknown verbosity level : {0}".format(args.verbose)
      print "Cannot proceed. Exiting"
      exit(-1)

   logging.basicConfig(filename=args.logfile, level=conf_man.log_levels[args.verbose],
                       format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                       datefmt='%m-%d %H:%M')
   logging.debug("\n{0}\nStarting task_executor\n{0}\n".format("*"*50))
   app = conf_man.load_configs(args.conffile);

   task_loop(app)

<commit_msg>Setting worker to delete tmp dirs<commit_after>#!/usr/bin/env python
import requests
import time, datetime
from datetime import datetime
import bottle
import logging
import argparse
import ast
from bottle import run, route, get, post, request, response
import json
import config_manager as conf_man
import task_executor_utils as utils
import os
import applications as apps
import s3_utils as s3
import dynamo_utils as dutils
import re
import shutil
import sys
import sts
import seppukku
import sns_sqs
import inspect

metadata_server="http://169.254.169.254/latest/meta-data/"
clean_tmp_dirs = True

def get_instance_starttime() :
   try:
      data = requests.get(metadata_server + "local-ipv4")
      last_mod = data.headers['last-modified']
      return datetime.strptime(last_mod, "%a, %d %b %Y %H:%M:%S %Z")
   except e:
      print "Caught exception : {0}".format(e)

def get_metainfo() :
   try:
      data = requests.get(metadata_server + "")
      last_mod = data.headers['last-modified']
      return datetime.strptime(last_mod, "%a, %d %b %Y %H:%M:%S %Z")
   except e:
      print "Caught exception : {0}".format(e)

##################################################################
# A rudimentary times for coarse-grained profiling
##################################################################
class Timer(object):
   def __init__(self, verbose=False):
      self.verbose = verbose

      def __enter__(self):
         self.start = time.time()
         return self

      def __exit__(self, *args):
         self.end = time.time()
         self.secs = self.end - self.start
         self.msecs = self.secs * 1000  # millisecs
         if self.verbose:
            print 'elapsed time: %f ms' % self.msecs

def get_inputs(app, inputs, auth):

   try:
      print "Attempting to switch roles to : {0}".format(auth["role"])
      creds = sts.get_temp_creds(auth["role"])
      sts.print_creds(creds)
      s3conn  = s3.get_s3_conn( creds["AccessKeyId"],
                                creds["SecretAccessKey"],
                                creds["SessionToken"] )

   except Exception as e:
      print "Caught exception : {0}".format(e)
      raise

   print "In get_inputs"
   if not inputs:
      return

   for i in inputs:
      print "Staging_inputs : ", i

      if i["src"].startswith("http://"):
         print "Downloading {0} via http".format(i["src"])
         utils.download_file(i["src"], i["dest"])

      elif re.search("https://s3.*amazonaws.com/", i["src"]):
         s3_path = re.sub("https://s3.*amazonaws.com/", "", i["src"])
         tmp     = s3_path.split('/', 1)
         s3_bucket = tmp[0]
         s3_key    = tmp[1]
         print "Downloading {0} via s3 provider".format(i["src"])
         try:
            s3.smart_download_s3_keys(s3conn,
                                      s3_bucket,
                                      s3_key,
                                      i["dest"],
                                      creds)
         except Exception as e:
            print "Download from s3 failed {0}".format(e)
            raise

      elif i["src"].startswith("s3://"):

         s3_path   = i["src"].strip("s3://")
         tmp       = s3_path.split('/', 1)
         s3_bucket = tmp[0]
         s3_key    = tmp[1]
         print "Downloading {0} via s3 provider".format(i["src"])
         try:
            s3.smart_download_s3_keys(s3conn,
                                      s3_bucket,
                                      s3_key,
                                      i["dest"],
                                      creds)
         except Exception as e:
            print "Download from s3 failed {0}".format(e)
            raise

      else:
         print "No match. Could not fetch data"

   return

def put_outputs(app, outputs):
   print "In put_outputs"
   if not outputs:
      return

   for out in outputs:
      print "Outputs : ", out
      '''
      if not os.path.exists(out["src"]):
         print "Missing file. Continuing"
         continue
      '''
      target = out["dest"].split('/', 1)
      try:
         s3.smart_upload_s3_keys(app.config["s3.conn"],
                                out["src"], # Source filename
                                target[0],  # Bucket name
                                target[1],  # Prefix
                                {"Owner": "Yadu"})

      except Exception as e:
         print "Upload to s3 failed {0}".format(e)

   return

def update_record(record, key, value):
   record[key] = value
   record.save(overwrite=True)
   return

def exec_job(app, jobtype, job_id, executable, args, inputs, outputs, data, auth):

   # Save current folder and chdir to a temporary folder
   conf_man.update_creds_from_metadata_server(app)
   record = dutils.dynamodb_get(app.config["dyno.conn"], job_id)

   ##############################################################################
   # Notify job execution start time
   ##############################################################################
   update_record(record, "start_time", time.time())

   ##############################################################################
   # Setup dirs for execution
   ##############################################################################
   cwd    = os.getcwd()
   tmpdir = "/tmp/task_executor_jobs/{0}".format(job_id)
   try:
      os.makedirs(tmpdir)
   except:
      print "Tmpdir {0} exists. Deleting and recreating".format(tmpdir)
      shutil.rmtree(tmpdir)
      os.makedirs(tmpdir)
   os.chdir(tmpdir)

   ##############################################################################
   # Download the inputs to the temp folder
   ##############################################################################
   update_record(record, "status", "staging_inputs")
   stagein_start = time.time()
   try:
      get_inputs(app, inputs, auth)
   except Exception as e:
      print "Exception info : ".format(sys.exc_info()[0])
      update_record(record, "ERROR", "Failed to download inputs {0}".format(e))
      update_record(record, "status", "failed")
      update_record(record, "complete_time", time.time())
      logging.error("Failed to download inputs")
      return False
   stagein_total = time.time() - stagein_start

   ##############################################################################
   # Download the inputs to the temp folder
   ##############################################################################
   # Check if job is valid
   update_record(record, "status", "processing")
   if jobtype not in apps.JOBS:
      logging.error("Jobtype : {0} does not exist".format(jobtype))
      print "Unable to process jobtype : {0}".format(jobtype)
      return False
   print "JOBS : ", apps.JOBS[jobtype]

   status = True
   returncode = 0
   process_start = time.time()
   try:
      returncode = apps.JOBS[jobtype](app, data)
      print "Returncode : {0}".format(returncode)
      conf_man.update_creds_from_metadata_server(app)

   except Exception as e:
      update_record(record, "status", "Failed");
      update_record(record, "complete_time", time.time())
      update_record(record, "ERROR", str(e));
      print "Job execution failed : {0}".format(e)
      status = False
   process_total = time.time() - process_start

   ##############################################################################
   # Upload the results to the S3
   ##############################################################################
   record = dutils.dynamodb_get(app.config["dyno.conn"], job_id)
   update_record(record, "status", "staging_outputs")
   stageout_start = time.time()

   # Upload the result to S3
   try:
      put_outputs(app, outputs)
   except Exception as e:
      print "Exception info : ".format(sys.exc_info()[0])
      update_record(record, "ERROR", "Failed to upload outputs {0}".format(e))
      update_record(record, "status", "failed")
      update_record(record, "complete_time", time.time())
      logging.error( "Failed to upload inputs")
      return False
   stageout_total = time.time() - stageout_start

   update_record(record, "z_stagein_dur",    stagein_total)
   update_record(record, "z_stageout_dur",   stageout_total)
   update_record(record, "z_processing_dur", process_total - 1)

   if returncode != 0 :
      update_record(record, "status", "failed");
      update_record(record, "complete_time", time.time())
      update_record(record, "ERROR_CODE", returncode);
      status = False
   else:

      update_record(record, "status", "completed")
      update_record(record, "complete_time", time.time())

   if clean_tmp_dirs:
      shutil.rmtree(tmpdir)
   # Chdir back to the original folder
   os.chdir(cwd)
   return True

def task_loop(app):
   sqs_conn  = app.config["sqs.conn"]
   pending   = app.config["instance.tags"]["JobsQueueName"]
   active    = app.config["instance.tags"]["ActiveQueueName"]
   pending_q = sqs_conn.get_queue(pending)
   active_q  = sqs_conn.get_queue(active)

   while 1:
      # Wait to read a message from the pending_q
      msg = pending_q.read(wait_time_seconds=20)

      print "Received message from pending_q"
      if msg:
         # Too many things could fail here, do a blanket
         # Try catch
         try:

            sreq = json.loads(msg.get_body())["Message"]
            if not sreq :
               continue

            app.config["current_msg_handle"] = msg

            data        =  ast.literal_eval(sreq)
            job_id      =  data.get('job_id')
            jobtype     =  data.get('jobtype')
            executable  =  data.get('executable')
            args        =  data.get('args')
            inputs      =  data.get('inputs')
            inputs      =  data.get('inputs')
            outputs     =  data.get('outputs')
            user_auth   =  {"user"      : data.get('i_user_id'),
                            "role"      : data.get('i_user_role'),
                            "token"     : data.get('i_token'),
                            "keyid"     : data.get('i_keyid'),
                            "keysecret" : data.get('i_keysecret')}

            # Post the job to the active queue and delete it from the pending queue
            attr, current_msg = sns_sqs.post_message_to_active(app, active_q, msg.get_body(), job_id)
            print "Posted job from pending to active queue"
            if not pending_q.delete_message(msg):
               print "Deleting message from pending queue failed"

            for key in data:
               print "{0} : {1}".format(key, data[key])

            print "Starting task"
            status      =  exec_job(app,
                                    jobtype,
                                    job_id,
                                    executable,
                                    args,
                                    inputs,
                                    outputs,
                                    data,
                                    user_auth)

            print "Status : ", status

            if status == True:
               conf_man.send_success_mail(data, app)
            else:
               conf_man.send_failure_mail(data, app)

            # TODO : CLeanup
            print "At deletion : ", msg
            #res = active_q.delete_message(current_msg)
            if not  sns_sqs.delete_message_from_active(sqs_conn, active_q, attr):
               print "Messages deleted : ", count

         except Exception as e:
               print "Job failed to complete : {0}".format(sys.exc_info()[0])
               print "Trace : ", inspect.trace()
               if not  sns_sqs.delete_message_from_active(sqs_conn, active_q, attr):
                  print "Messages deleted : ", count

      else:
         print "{0}: Waiting for job description".format(time.time())
         seppukku.die_at_hour_edge(app, dry_run=True)
         logging.debug("{0}: Waiting for job description".format(time.time()))

      conf_man.update_creds_from_metadata_server(app)

if __name__ == "__main__":

   parser   = argparse.ArgumentParser()
   parser.add_argument("-v", "--verbose", default="DEBUG", help="set level of verbosity, DEBUG, INFO, WARN")
   parser.add_argument("-l", "--logfile", default="task_executor.log", help="Logfile path. Defaults to ./task_executor.log")
   parser.add_argument("-c", "--conffile", default="test.conf", help="Config file path. Defaults to ./test.conf")
   parser.add_argument("-j", "--jobid", type=str, action='append')
   parser.add_argument("-i", "--workload_id", default=None)
   args   = parser.parse_args()

   if args.verbose not in conf_man.log_levels :
      print "Unknown verbosity level : {0}".format(args.verbose)
      print "Cannot proceed. Exiting"
      exit(-1)

   logging.basicConfig(filename=args.logfile, level=conf_man.log_levels[args.verbose],
                       format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                       datefmt='%m-%d %H:%M')
   logging.debug("\n{0}\nStarting task_executor\n{0}\n".format("*"*50))
   app = conf_man.load_configs(args.conffile);

   task_loop(app)

<|endoftext|>


<commit_before>from __future__ import unicode_literals

from django import http
from django.conf import settings
from django.contrib.sites.models import Site
from django.db.models import Q

from .models import Redirect, StaticRedirect

class RedirectFallbackMiddleware(object):
    def process_request(self, request):
        static_redirect = StaticRedirect.objects.get_for_request(request)
        if static_redirect:
            full_domain = '{}://{}'.format(request.scheme, Site.objects.get(id=settings.SITE_ID).domain)
            return http.HttpResponsePermanentRedirect(static_redirect.get_outbound_url(full_domain))

        path = request.path_info
        path_with_queries = request.get_full_path()
        queries = (
            Q(old_path__iexact=path)
            | Q(old_path__iexact=path_with_queries)
        )

        if settings.APPEND_SLASH and path.endswith('/'):
            path_with_queries_no_slash = path[:-1] + path_with_queries[len(path):]
            queries |= (
                Q(old_path__iexact=path[:-1])
                | Q(old_path__iexact=path_with_queries_no_slash)
            )

        try:
            r = Redirect.objects.filter(
                queries,
                site__id__exact=settings.SITE_ID
            ).distinct().get()
        except Redirect.DoesNotExist:
            return

        if r.new_path == '':
            return http.HttpResponseGone()
        return http.HttpResponsePermanentRedirect(r.new_path)
<commit_msg>Fixed DoesNotExist error raised when no matching translation found<commit_after>from __future__ import unicode_literals

from django import http
from django.conf import settings
from django.contrib.sites.models import Site
from django.db.models import Q

from .models import Redirect, StaticRedirect

class RedirectFallbackMiddleware(object):
    def process_request(self, request):
        static_redirect = StaticRedirect.objects.get_for_request(request)
        if static_redirect:
            full_domain = '{}://{}'.format(request.scheme, Site.objects.get(id=settings.SITE_ID).domain)
            return http.HttpResponsePermanentRedirect(static_redirect.get_outbound_url(full_domain))

        path = request.path_info
        path_with_queries = request.get_full_path()
        queries = (
            Q(old_path__iexact=path)
            | Q(old_path__iexact=path_with_queries)
        )

        if settings.APPEND_SLASH and path.endswith('/'):
            path_with_queries_no_slash = path[:-1] + path_with_queries[len(path):]
            queries |= (
                Q(old_path__iexact=path[:-1])
                | Q(old_path__iexact=path_with_queries_no_slash)
            )

        try:
            r = Redirect.objects.filter(
                queries,
                site__id__exact=settings.SITE_ID
            ).distinct().get()
        except Redirect.DoesNotExist:
            return

        new_path = r.safe_translation_getter('new_path', any_language=True)

        if new_path in (None, ''):
            return http.HttpResponseGone()
        return http.HttpResponsePermanentRedirect(r.new_path)
<|endoftext|>


<commit_before># Copyright 2018 Open Source Integrators (http://www.opensourceintegrators.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from dateutil.relativedelta import relativedelta

from odoo import _, api, fields, models
from odoo.exceptions import UserError

class AccountPaymentRegister(models.TransientModel):
    _inherit = "account.payment.register"

    invoice_id = fields.Many2one(comodel_name="account.move", string="Invoice")
    discount_amt = fields.Monetary(store=True)

    @api.model
    def default_get(self, fields):
        res = super().default_get(fields)
        active_id = self.env.context.get("active_ids", [])
        if self.env.context.get("active_model") == "account.move" and (
            isinstance(active_id, int) or len(active_id) == 1
        ):
            record = self.env["account.move"].browse(active_id)
            res.update({"invoice_id": record.id, "discount_amt": record.discount_amt})
        return res

    @api.onchange("amount", "payment_difference", "payment_date")
    def onchange_payment_amount(self):
        if (
            self.invoice_id
            and self.invoice_id.invoice_payment_term_id
            and self.invoice_id.invoice_payment_term_id.is_discount
            and self.invoice_id.invoice_payment_term_id.line_ids
        ):

            self.payment_difference_handling = "open"
            self.writeoff_account_id = False
            self.writeoff_label = False

            for line in self.invoice_id.invoice_payment_term_id.line_ids:
                # Check payment date discount validation
                invoice_date = fields.Date.from_string(self.invoice_id.invoice_date)
                till_discount_date = invoice_date + relativedelta(
                    days=line.discount_days
                )
                payment_date = fields.Date.from_string(self.payment_date)
                discount_amt = self.invoice_id.discount_amt

                payment_difference = self.payment_difference
                self.payment_difference = 0.0

                if payment_date <= till_discount_date:
                    discount_account = (
                        line.discount_income_account_id
                        if self.invoice_id.is_purchase_document()
                        else line.discount_expense_account_id
                    )
                    # changing payment date
                    if not payment_difference and discount_amt:

                        self.payment_difference = discount_amt
                        self.payment_difference_handling = "reconcile"
                        self.writeoff_account_id = discount_account.id
                        self.writeoff_label = "Payment Discount"
                    # customer is paying more
                    elif abs(payment_difference) < discount_amt:

                        self.payment_difference = abs(payment_difference)
                        self.payment_difference_handling = "reconcile"
                        self.writeoff_account_id = discount_account.id
                        self.writeoff_label = "Payment Discount"
                    # ocustomer paying more than discount_amt
                    elif abs(payment_difference) > discount_amt:

                        self.payment_difference = abs(payment_difference)
                        self.payment_difference_handling = "open"
                        self.writeoff_label = False
                    # customer paying more than discount_amt
                    elif abs(payment_difference) == discount_amt and discount_amt > 0:

                        self.payment_difference = abs(payment_difference)
                        self.payment_difference_handling = "reconcile"
                        self.writeoff_account_id = discount_account.id
                        self.writeoff_label = "Payment Discount"
                else:
                    self.payment_difference = payment_difference

                self.amount = self.invoice_id.amount_residual - abs(
                    self.payment_difference
                )

    def action_create_payments(self):
        active_id = self.env.context.get("active_ids", [])

        if (not isinstance(active_id, int)) and len(active_id) != 1:
            # For multiple invoices, there is account.register.payments wizard
            raise UserError(
                _(
                    "This method should only be called to process a "
                    "single invoice's payment."
                )
            )
        res = super().action_create_payments()
        for payment in self:
            if payment.payment_difference_handling == "reconcile":
                payment.invoice_id.write(
                    {
                        "discount_taken": abs(payment.payment_difference),
                        "discount_amt": 0,
                    }
                )
        return res
<commit_msg>[FIX] account_payment_term_discount: cannot add extra amount in Register payment<commit_after># Copyright 2018 Open Source Integrators (http://www.opensourceintegrators.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from dateutil.relativedelta import relativedelta

from odoo import _, api, fields, models
from odoo.exceptions import UserError

class AccountPaymentRegister(models.TransientModel):
    _inherit = "account.payment.register"

    invoice_id = fields.Many2one(comodel_name="account.move", string="Invoice")
    discount_amt = fields.Monetary(store=True)

    @api.model
    def default_get(self, fields):
        res = super().default_get(fields)
        active_id = self.env.context.get("active_ids", [])
        if self.env.context.get("active_model") == "account.move" and (
            isinstance(active_id, int) or len(active_id) == 1
        ):
            record = self.env["account.move"].browse(active_id)
            res.update({"invoice_id": record.id, "discount_amt": record.discount_amt})
        return res

    @api.onchange("amount", "payment_difference", "payment_date")
    def onchange_payment_amount(self):
        if (
            self.invoice_id
            and self.invoice_id.invoice_payment_term_id
            and self.invoice_id.invoice_payment_term_id.is_discount
            and self.invoice_id.invoice_payment_term_id.line_ids
        ):

            self.payment_difference_handling = "open"
            self.writeoff_account_id = False
            self.writeoff_label = False

            for line in self.invoice_id.invoice_payment_term_id.line_ids:
                # Check payment date discount validation
                invoice_date = fields.Date.from_string(self.invoice_id.invoice_date)
                till_discount_date = invoice_date + relativedelta(
                    days=line.discount_days
                )
                payment_date = fields.Date.from_string(self.payment_date)
                discount_amt = self.invoice_id.discount_amt

                payment_difference = self.payment_difference
                self.payment_difference = 0.0

                if payment_date <= till_discount_date:
                    discount_account = (
                        line.discount_income_account_id
                        if self.invoice_id.is_purchase_document()
                        else line.discount_expense_account_id
                    )
                    # changing payment date
                    if not payment_difference and discount_amt:

                        self.payment_difference = discount_amt
                        self.payment_difference_handling = "reconcile"
                        self.writeoff_account_id = discount_account.id
                        self.writeoff_label = "Payment Discount"
                    # customer is paying more
                    elif payment_difference < discount_amt:
                        if payment_difference > 0:
                            self.payment_difference = discount_amt
                            self.payment_difference_handling = "reconcile"
                            self.writeoff_account_id = discount_account.id
                            self.writeoff_label = "Payment Discount"
                        elif payment_difference < 0:
                            self.payment_difference = payment_difference
                    # ocustomer paying more than discount_amt
                    elif payment_difference > discount_amt:
                        self.payment_difference = payment_difference
                        self.payment_difference_handling = "open"
                        self.writeoff_label = False
                    # customer paying more than discount_amt
                    elif payment_difference == discount_amt and discount_amt > 0:

                        self.payment_difference = abs(payment_difference)
                        self.payment_difference_handling = "reconcile"
                        self.writeoff_account_id = discount_account.id
                        self.writeoff_label = "Payment Discount"
                else:
                    self.payment_difference = payment_difference

                self.amount = self.invoice_id.amount_residual - (
                    self.payment_difference
                )

    def action_create_payments(self):
        active_id = self.env.context.get("active_ids", [])

        if (not isinstance(active_id, int)) and len(active_id) != 1:
            # For multiple invoices, there is account.register.payments wizard
            raise UserError(
                _(
                    "This method should only be called to process a "
                    "single invoice's payment."
                )
            )
        res = super().action_create_payments()
        for payment in self:
            if payment.payment_difference_handling == "reconcile":
                payment.invoice_id.write(
                    {
                        "discount_taken": abs(payment.payment_difference),
                        "discount_amt": 0,
                    }
                )
        return res
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import models
from collections import namedtuple

class XmlDeclaration(models.TransientModel):
    """
    Intrastat XML Declaration
    """
    _inherit = "l10n_be_intrastat_xml.xml_decl"

    def _build_intrastat_line(self, numlgn, item, linekey, amounts, dispatchmode, extendedmode):
        super(XmlDeclaration, self)._build_intrastat_line(numlgn, item, linekey, amounts, dispatchmode, extendedmode)
        if dispatchmode:
            self._set_Dim(item, 'EXCNTORI', unicode(linekey.EXCNTORI))
            self._set_Dim(item, 'PARTNERID', unicode(linekey.PARTNERID))

    def _get_intrastat_linekey(self, declcode, inv_line, dispatchmode, extendedmode):
        res = super(XmlDeclaration, self)._get_intrastat_linekey(declcode, inv_line, dispatchmode, extendedmode)
        if res and dispatchmode:
            res_dict = res._asdict()
            res_dict['EXCNTORI'] = inv_line.intrastat_product_origin_country_id.code or 'QU'
            res_dict['PARTNERID'] = inv_line.invoice_id.partner_id.vat or 'QV999999999999'
            return namedtuple('intrastatkey', res_dict.keys())(**res_dict)
        return res

    def _get_expedition_code(self, extended):
        return 'INTRASTAT_X_E' if extended else 'INTRASTAT_X_S'

    def _get_expedition_form(self, extended):
        return 'INTRASTAT_X_EF' if extended else 'INTRASTAT_X_SF'
<commit_msg>[FIX] l10n_be_intrastat_2019: Python3 compatibility<commit_after># -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import models
from odoo.tools.pycompat import text_type
from collections import namedtuple

class XmlDeclaration(models.TransientModel):
    """
    Intrastat XML Declaration
    """
    _inherit = "l10n_be_intrastat_xml.xml_decl"

    def _build_intrastat_line(self, numlgn, item, linekey, amounts, dispatchmode, extendedmode):
        super(XmlDeclaration, self)._build_intrastat_line(numlgn, item, linekey, amounts, dispatchmode, extendedmode)
        if dispatchmode:
            self._set_Dim(item, 'EXCNTORI', text_type(linekey.EXCNTORI))
            self._set_Dim(item, 'PARTNERID', text_type(linekey.PARTNERID))

    def _get_intrastat_linekey(self, declcode, inv_line, dispatchmode, extendedmode):
        res = super(XmlDeclaration, self)._get_intrastat_linekey(declcode, inv_line, dispatchmode, extendedmode)
        if res and dispatchmode:
            res_dict = res._asdict()
            res_dict['EXCNTORI'] = inv_line.intrastat_product_origin_country_id.code or 'QU'
            res_dict['PARTNERID'] = inv_line.invoice_id.partner_id.vat or 'QV999999999999'
            return namedtuple('intrastatkey', res_dict.keys())(**res_dict)
        return res

    def _get_expedition_code(self, extended):
        return 'INTRASTAT_X_E' if extended else 'INTRASTAT_X_S'

    def _get_expedition_form(self, extended):
        return 'INTRASTAT_X_EF' if extended else 'INTRASTAT_X_SF'
<|endoftext|>


<commit_before>from ranks_points import rank_distance, RANKS_POINTS

SHITTY_CARDS = ['2', '3', '4', '5', '6']
OKAY_CARDS = ['7', '8', '9', '10']
GOOD_CARDS = ['Q', 'J']
HIGH_CARDS = ['A', 'K']

class Player:
    VERSION = "face-face"

    def betRequest(self, game_state):
        player_index = game_state['in_action']
        hole_cards = game_state['players'][player_index]['hole_cards']
        ranks = [c['rank'] for c in hole_cards]
        suits = [c['suit'] for c in hole_cards]
        current_round = get_current_round(game_state)

        total_bet = 0

        # http://www.holdemsecrets.com/startinghands.htm
        # Follow this! This is our bible!

        if current_round > 0:
            return total_bet

        if is_pair(hole_cards) and includes_high_card(ranks):
            print "high pair -- ALL IN"
            total_bet += 100000000

        if is_pair(hole_cards) and includes_good_card(ranks):
            print "good pair -- ALL IN"
            total_bet += 100000000

        if is_pair(hole_cards) and includes_okay_card(ranks):
            print "okay pair -- 65-74% win rate"
            total_bet += 100000000

        if is_ace_face_suited(hole_cards):
            print "ace face suited -- 64-66% win rate"
            total_bet += 100000000

        if ace_face_offsuit(ranks, hole_cards):
            print "ace face offsuit"
            total_bet += 100000000

        if is_ace_low_suited(hole_cards):
            print "ace low suited - 55-63%"
            total_bet += 100000000

        if is_face_face_offsuit(hole_cards):
            print 'face-face offsuit -- 57-60%'
            total_bet += 100000000

        if is_pair(hole_cards):
            print "pair"
            total_bet += get_minimum_raise_value(game_state)

        if is_part_of_straight(ranks):
            print "two adjacent ranks"
            total_bet += 100

        print total_bet, hole_cards
        return int(total_bet)

    def showdown(self, game_state):
        pass

def is_pair(hole_cards):
    return hole_cards[0]["rank"] == hole_cards[1]["rank"]

def is_same_suit(hole_cards):
    return hole_cards[0]["suit"] == hole_cards[1]["suit"]

def includes_ace(hole_cards):
    if hole_cards[0]['rank'] == 'A':
        return True
    if hole_cards[1]['rank'] == 'A':
        return True
    return False

def is_part_of_straight(ranks):
    return rank_distance(ranks) == 1

def is_ace_face_suited(hole_cards):
    other_pair = ['K', 'Q', 'J']
    ranks = [c['rank'] for c in hole_cards]
    includes_other = any(r in other_pair for r in ranks)
    return (includes_ace(hole_cards) and includes_other) and is_same_suit(hole_cards)

def is_face_face_offsuit(hole_cards):
    ranks = [c['rank'] for c in hole_cards]
    if 'K' in ranks and ('Q' in ranks or 'J' in ranks):
        return True
    if 'Q' in ranks and 'J' in ranks:
        return True
    return False

def includes_good_card(ranks):
    return any(r in GOOD_CARDS for r in ranks)

def includes_high_card(ranks):
    return any(r in HIGH_CARDS for r in ranks)

def includes_okay_card(ranks):
    return any(r in OKAY_CARDS for r in ranks)

def is_ace_low_suited(hole_cards):
    return is_same_suit(hole_cards) and includes_ace(hole_cards) and any([RANKS_POINTS[c['rank']] <= 10 for c in hole_cards])

def get_current_round(game_state):
    return game_state['round']

def get_call_value(game_state):
    player_index = game_state['in_action']
    return game_state['current_buy_in'] - game_state['players'][player_index]['bet']

def get_minimum_raise_value(game_state):
    player_index = game_state['in_action']
    return game_state['current_buy_in'] - game_state['players'][player_index]['bet'] + game_state['minimum_raise']

def ace_face_offsuit(ranks, hole_cards):
    different_suit = not is_same_suit(hole_cards)
    return different_suit and 'A' in ranks and any(r in ['K', 'Q', 'J'] for r in ranks)
<commit_msg>round 0 to 1<commit_after>from ranks_points import rank_distance, RANKS_POINTS

SHITTY_CARDS = ['2', '3', '4', '5', '6']
OKAY_CARDS = ['7', '8', '9', '10']
GOOD_CARDS = ['Q', 'J']
HIGH_CARDS = ['A', 'K']

class Player:
    VERSION = "face-face"

    def betRequest(self, game_state):
        player_index = game_state['in_action']
        hole_cards = game_state['players'][player_index]['hole_cards']
        ranks = [c['rank'] for c in hole_cards]
        suits = [c['suit'] for c in hole_cards]
        current_round = get_current_round(game_state)

        total_bet = 0

        # http://www.holdemsecrets.com/startinghands.htm
        # Follow this! This is our bible!

        if current_round > 1:
            return total_bet

        if is_pair(hole_cards) and includes_high_card(ranks):
            print "high pair -- ALL IN"
            total_bet += 100000000

        if is_pair(hole_cards) and includes_good_card(ranks):
            print "good pair -- ALL IN"
            total_bet += 100000000

        if is_pair(hole_cards) and includes_okay_card(ranks):
            print "okay pair -- 65-74% win rate"
            total_bet += 100000000

        if is_ace_face_suited(hole_cards):
            print "ace face suited -- 64-66% win rate"
            total_bet += 100000000

        if ace_face_offsuit(ranks, hole_cards):
            print "ace face offsuit"
            total_bet += 100000000

        if is_ace_low_suited(hole_cards):
            print "ace low suited - 55-63%"
            total_bet += 100000000

        if is_face_face_offsuit(hole_cards):
            print 'face-face offsuit -- 57-60%'
            total_bet += 100000000

        if is_pair(hole_cards):
            print "pair"
            total_bet += get_minimum_raise_value(game_state)

        if is_part_of_straight(ranks):
            print "two adjacent ranks"
            total_bet += 100

        print total_bet, hole_cards
        return int(total_bet)

    def showdown(self, game_state):
        pass

def is_pair(hole_cards):
    return hole_cards[0]["rank"] == hole_cards[1]["rank"]

def is_same_suit(hole_cards):
    return hole_cards[0]["suit"] == hole_cards[1]["suit"]

def includes_ace(hole_cards):
    if hole_cards[0]['rank'] == 'A':
        return True
    if hole_cards[1]['rank'] == 'A':
        return True
    return False

def is_part_of_straight(ranks):
    return rank_distance(ranks) == 1

def is_ace_face_suited(hole_cards):
    other_pair = ['K', 'Q', 'J']
    ranks = [c['rank'] for c in hole_cards]
    includes_other = any(r in other_pair for r in ranks)
    return (includes_ace(hole_cards) and includes_other) and is_same_suit(hole_cards)

def is_face_face_offsuit(hole_cards):
    ranks = [c['rank'] for c in hole_cards]
    if 'K' in ranks and ('Q' in ranks or 'J' in ranks):
        return True
    if 'Q' in ranks and 'J' in ranks:
        return True
    return False

def includes_good_card(ranks):
    return any(r in GOOD_CARDS for r in ranks)

def includes_high_card(ranks):
    return any(r in HIGH_CARDS for r in ranks)

def includes_okay_card(ranks):
    return any(r in OKAY_CARDS for r in ranks)

def is_ace_low_suited(hole_cards):
    return is_same_suit(hole_cards) and includes_ace(hole_cards) and any([RANKS_POINTS[c['rank']] <= 10 for c in hole_cards])

def get_current_round(game_state):
    return game_state['round']

def get_call_value(game_state):
    player_index = game_state['in_action']
    return game_state['current_buy_in'] - game_state['players'][player_index]['bet']

def get_minimum_raise_value(game_state):
    player_index = game_state['in_action']
    return game_state['current_buy_in'] - game_state['players'][player_index]['bet'] + game_state['minimum_raise']

def ace_face_offsuit(ranks, hole_cards):
    different_suit = not is_same_suit(hole_cards)
    return different_suit and 'A' in ranks and any(r in ['K', 'Q', 'J'] for r in ranks)
<|endoftext|>


<commit_before>import sys
from collections import defaultdict
sys.stdout = sys.stderr

print "PYTHON VERSION", sys.version

def eval_hand(cards):
    result = 0.0
    card_ranks = defaultdict(int)

    for card in cards:
        rank = card["rank"]
        card_ranks[rank] += 1

    return max(card_ranks.items(), key = lambda x: x[1])[1]

class Player:
    VERSION = "Default Python folding player"

    def betRequest(self, game_state):
        in_action = game_state["in_action"]
        current_buy_in = game_state["current_buy_in"]
        pot = game_state["pot"]
        minimum_raise = game_state["minimum_raise"]
        players = game_state["players"]
        our_player = players[in_action]
        min_bet = current_buy_in - our_player["bet"]
        bet_index = game_state["bet_index"]
        community_cards = game_state["community_cards"]
        my_cards = our_player["hole_cards"]
        round = game_state["round"]

        hand_score = 0

        if len(community_cards):
            hand_value = eval_hand(my_cards + community_cards)
            community_value = eval_hand(community_cards)
            hand_score = hand_value - community_value
        else:
            hand_score = eval_hand(my_cards)

        #pull out the other players
        other_players = [player for player in players if player["status"] == "active" and player is not our_player]

        #other_players + 1
        n_playing = len(other_players) + 1

        #pre-flop
        if len(community_cards) == 0:
            cards = our_player["hole_cards"]
            #if we have at least one ace or a pair, we bet the first hand, if not, then fold
            if (cards[0]["rank"] == 'A'
                    or cards[1]["rank"] == 'A'
                    or cards[0]["rank"] == cards[1]["rank"]):
                this_bet = 500 # min_bet + minimum_raise
            elif current_buy_in <= 50:
                this_bet = min_bet
            else:
                this_bet = 0
        #if we are post flop and have a larger chip stack, put them all in
        elif hand_score > 0:
            #if n_playing == 2 and other_players[0]["stack"] < our_player["stack"]:
             #   this_bet = other_players[0]["stack"]
            #else:
            this_bet = max(min_bet, int(our_player["stack"]) / 2)
        else:
            this_bet = minimum_raise
        print "******** ROUND", round, "BET_INDEX", bet_index, "BET", this_bet, "STACK", our_player["stack"], "N_PLAYING", n_playing, "Hand Rating", hand_score, "Other Players", other_players
        return this_bet

    def showdown(self, game_state):
        pass

if __name__ == "__main__":
    import json
    game_state = json.loads('''
{
    "tournament_id":"550d1d68cd7bd10003000003",
    "game_id":"550da1cb2d909006e90004b1",
    "round":0,
    "bet_index":0,
    "small_blind": 10,
    "current_buy_in": 320,
    "pot": 400,
    "minimum_raise": 240,
    "dealer": 1,
    "orbits": 7,
    "in_action": 1,
    "players": [
        {
            "id": 0,
            "name": "Albert",
            "status": "active",
            "version": "Default random player",
            "stack": 1010,
            "bet": 320
        },
        {
            "id": 1,
            "name": "Bob",
            "status": "active",
            "version": "Default random player",
            "stack": 1590,
            "bet": 80,
            "hole_cards": [
                {
                    "rank": "6",
                    "suit": "hearts"
                },
                {
                    "rank": "K",
                    "suit": "spades"
                }
            ]
        },
        {
            "id": 2,
            "name": "Chuck",
            "status": "out",
            "version": "Default random player",
            "stack": 0,
            "bet": 0
        }
    ],
    "community_cards": [
        {
            "rank": "4",
            "suit": "spades"
        },
        {
            "rank": "A",
            "suit": "hearts"
        },
        {
            "rank": "6",
            "suit": "clubs"
        }
    ]
}''')
    player = Player()
    print player.betRequest(game_state)
<commit_msg>Add aggresive_bet logic<commit_after>import sys
from collections import defaultdict
sys.stdout = sys.stderr

print "PYTHON VERSION", sys.version

def eval_hand(cards):
    result = 0.0
    card_ranks = defaultdict(int)

    for card in cards:
        rank = card["rank"]
        card_ranks[rank] += 1

    return max(card_ranks.items(), key = lambda x: x[1])[1]

class Player:
    VERSION = "Default Python folding player"

    def betRequest(self, game_state):
        in_action = game_state["in_action"]
        current_buy_in = game_state["current_buy_in"]
        pot = game_state["pot"]
        minimum_raise = game_state["minimum_raise"]
        players = game_state["players"]
        our_player = players[in_action]
        min_bet = current_buy_in - our_player["bet"]
        bet_index = game_state["bet_index"]
        community_cards = game_state["community_cards"]
        my_cards = our_player["hole_cards"]
        round = game_state["round"]
        aggresive_bet = max(min_bet, int(our_player["stack"]) / 2)

        hand_score = 0

        if len(community_cards):
            hand_value = eval_hand(my_cards + community_cards)
            community_value = eval_hand(community_cards)
            hand_score = hand_value - community_value
        else:
            hand_score = eval_hand(my_cards)

        #pull out the other players
        other_players = [player for player in players if player["status"] == "active" and player is not our_player]

        #other_players + 1
        n_playing = len(other_players) + 1

        #pre-flop
        if len(community_cards) == 0:
            cards = our_player["hole_cards"]
            #if we have at least one ace or a pair, we bet the first hand, if not, then fold
            if (cards[0]["rank"] == 'A'
                    or cards[1]["rank"] == 'A'
                    or cards[0]["rank"] == cards[1]["rank"]):
                this_bet = aggresive_bet
            elif current_buy_in <= 50:
                this_bet = min_bet
            else:
                this_bet = 0
        #if we are post flop and have a larger chip stack, put them all in
        elif hand_score > 0:
            #if n_playing == 2 and other_players[0]["stack"] < our_player["stack"]:
             #   this_bet = other_players[0]["stack"]
            #else:
            this_bet = aggresive_bet
        else:
            this_bet = minimum_raise
        print "******** ROUND", round, "BET_INDEX", bet_index, "BET", this_bet, "STACK", our_player["stack"], "N_PLAYING", n_playing, "Hand Rating", hand_score, "Other Players", other_players
        return this_bet

    def showdown(self, game_state):
        pass

if __name__ == "__main__":
    import json
    game_state = json.loads('''
{
    "tournament_id":"550d1d68cd7bd10003000003",
    "game_id":"550da1cb2d909006e90004b1",
    "round":0,
    "bet_index":0,
    "small_blind": 10,
    "current_buy_in": 320,
    "pot": 400,
    "minimum_raise": 240,
    "dealer": 1,
    "orbits": 7,
    "in_action": 1,
    "players": [
        {
            "id": 0,
            "name": "Albert",
            "status": "active",
            "version": "Default random player",
            "stack": 1010,
            "bet": 320
        },
        {
            "id": 1,
            "name": "Bob",
            "status": "active",
            "version": "Default random player",
            "stack": 1590,
            "bet": 80,
            "hole_cards": [
                {
                    "rank": "6",
                    "suit": "hearts"
                },
                {
                    "rank": "K",
                    "suit": "spades"
                }
            ]
        },
        {
            "id": 2,
            "name": "Chuck",
            "status": "out",
            "version": "Default random player",
            "stack": 0,
            "bet": 0
        }
    ],
    "community_cards": [
        {
            "rank": "4",
            "suit": "spades"
        },
        {
            "rank": "A",
            "suit": "hearts"
        },
        {
            "rank": "6",
            "suit": "clubs"
        }
    ]
}''')
    player = Player()
    print player.betRequest(game_state)
<|endoftext|>


<commit_before>import sys

class Player:
    VERSION = "fokin new strategy"

    # Constant holding the weak pair hands when we have the same color
    WEAK_PAIR_HANDS = [
        (2, 7),
        (2, 8),
        (3, 8),
        (3, 7),
        (2, 6),
        (2, 9),
        (3, 9),
        (4, 9),
        (2, 10),
        (5, 9),
        (4, 7),
        (4, 8),
        (5, 8),
        (3, 6)
    ]

    # Constant holding the face cards one-char symbol and their value
    FACE_CARDS = {'J': 11, 'Q': 12, 'K': 13, 'A': 14}

    def unicode_repr(self, value):
        """
        Convert a value (string/int) to unicode object
        :param value: string or int
        :rtype: unicode obj
        """

        return unicode(str(value), "utf-8")

    def gen_diff_color_weak_pairs(self):
        """
        Generate weak pair hands. We use it when two cards are in different colors
        :rtype: list[tuple(unicode,unicode)]
        """

        diff_color_weak_pairs = []
        for face in self.FACE_CARDS.keys():
            for value in range(2, 6):
                new_unicode_pair = (self.unicode_repr(
                    face), self.unicode_repr(value))
                diff_color_weak_pairs.append(new_unicode_pair)
        return diff_color_weak_pairs

    def royal_flush(self, cards):
        return false

    def before_flop(self, hole_cards):
        """
        We check if we have weak hands in the beginning, and fold if we have. All in if not
        """
        our_tuple = (hole_cards[0]["rank"], hole_cards[1]["rank"])
        reversed_tuple = (our_tuple[1], our_tuple[0])

        if hole_cards[0]["suit"] == hole_cards[1]["suit"]:
            if our_tuple in self.WEAK_PAIR_HANDS or reversed_tuple in self.WEAK_PAIR_HANDS:
                return 0
        else:
            diff_color_weak_pairs = self.gen_diff_color_weak_pairs()
            if our_tuple in diff_color_weak_pairs or reversed_tuple in diff_color_weak_pairs:
                return 0
        return 10000

    def after_flop(self, hole_cards, community_cards):
        if self.royal_flush(hole_cards + community_cards):
            return 10000

        # if we have a match between hole and community cards in figure
        for hole_card in hole_cards:
            for com_card in community_cards:
                if hole_card["rank"] == com_card["rank"]:
                    return 10000

        # if we have a pair

        if hole_cards[0]["rank"] == hole_cards[1]["rank"]:
            return 10000

        # else:
        return 0

    def betRequest(self, game_state):
        # small_blind = game_state["small_blind"]
        current_buy_in = game_state["current_buy_in"]
        pot = game_state["pot"]
        minimum_raise = game_state["minimum_raise"]
        round = game_state["round"]
        dealer = game_state["dealer"]
        players = game_state["players"]
        in_action = game_state["in_action"]
        community_cards = game_state["community_cards"]
        last_bet = players[in_action]["bet"]
        hole_cards = players[in_action]["hole_cards"]
        print(hole_cards)

        if len(community_cards) == 0:
            return_bet = self.before_flop(hole_cards)
        else:
            return_bet = self.after_flop(hole_cards, community_cards)
        print(return_bet)
        print >> sys.stderr, return_bet
        return return_bet

    def showdown(self, game_state):
        pass<commit_msg>fix False<commit_after>import sys

class Player:
    VERSION = "fokin new strategy"

    # Constant holding the weak pair hands when we have the same color
    WEAK_PAIR_HANDS = [
        (2, 7),
        (2, 8),
        (3, 8),
        (3, 7),
        (2, 6),
        (2, 9),
        (3, 9),
        (4, 9),
        (2, 10),
        (5, 9),
        (4, 7),
        (4, 8),
        (5, 8),
        (3, 6)
    ]

    # Constant holding the face cards one-char symbol and their value
    FACE_CARDS = {'J': 11, 'Q': 12, 'K': 13, 'A': 14}

    def unicode_repr(self, value):
        """
        Convert a value (string/int) to unicode object
        :param value: string or int
        :rtype: unicode obj
        """

        return unicode(str(value), "utf-8")

    def gen_diff_color_weak_pairs(self):
        """
        Generate weak pair hands. We use it when two cards are in different colors
        :rtype: list[tuple(unicode,unicode)]
        """

        diff_color_weak_pairs = []
        for face in self.FACE_CARDS.keys():
            for value in range(2, 6):
                new_unicode_pair = (self.unicode_repr(
                    face), self.unicode_repr(value))
                diff_color_weak_pairs.append(new_unicode_pair)
        return diff_color_weak_pairs

    def royal_flush(self, cards):
        return False

    def before_flop(self, hole_cards):
        """
        We check if we have weak hands in the beginning, and fold if we have. All in if not
        """
        our_tuple = (hole_cards[0]["rank"], hole_cards[1]["rank"])
        reversed_tuple = (our_tuple[1], our_tuple[0])

        if hole_cards[0]["suit"] == hole_cards[1]["suit"]:
            if our_tuple in self.WEAK_PAIR_HANDS or reversed_tuple in self.WEAK_PAIR_HANDS:
                return 0
        else:
            diff_color_weak_pairs = self.gen_diff_color_weak_pairs()
            if our_tuple in diff_color_weak_pairs or reversed_tuple in diff_color_weak_pairs:
                return 0
        return 10000

    def after_flop(self, hole_cards, community_cards):
        if self.royal_flush(hole_cards + community_cards):
            return 10000

        # if we have a match between hole and community cards in figure
        for hole_card in hole_cards:
            for com_card in community_cards:
                if hole_card["rank"] == com_card["rank"]:
                    return 10000

        # if we have a pair

        if hole_cards[0]["rank"] == hole_cards[1]["rank"]:
            return 10000

        # else:
        return 0

    def betRequest(self, game_state):
        # small_blind = game_state["small_blind"]
        current_buy_in = game_state["current_buy_in"]
        pot = game_state["pot"]
        minimum_raise = game_state["minimum_raise"]
        round = game_state["round"]
        dealer = game_state["dealer"]
        players = game_state["players"]
        in_action = game_state["in_action"]
        community_cards = game_state["community_cards"]
        last_bet = players[in_action]["bet"]
        hole_cards = players[in_action]["hole_cards"]
        print(hole_cards)

        if len(community_cards) == 0:
            return_bet = self.before_flop(hole_cards)
        else:
            return_bet = self.after_flop(hole_cards, community_cards)
        print(return_bet)
        print >> sys.stderr, return_bet
        return return_bet

    def showdown(self, game_state):
        pass<|endoftext|>


<commit_before>import signal
import threading

from twisted.internet.defer import inlineCallbacks
from twisted.logger import Logger

from autobahn.twisted.util import sleep
from autobahn.twisted.wamp import ApplicationSession, ApplicationRunner
from autobahn.wamp.exception import ApplicationError

import gi
gi.require_version('Gst', '1.0')
gi.require_version('Gtk', '3.0')
from gi.repository import Gst, GObject, Gtk
Gst.init(None)

# ensure that we can actually issue a KeyboardInterrupt to break out
# of Gtk.main()
signal.signal(signal.SIGINT, signal.SIG_DFL)

class JukeboxPlayer(ApplicationSession):

    log = Logger()

    @inlineCallbacks
    def onJoin(self, details):

        self.player = Gst.ElementFactory.make('playbin', None)
        self.current_song = ''
        self.is_playing = False
        self.volume = 100
        self.position = -1

        def run_player():
            bus = self.player.get_bus()
            bus.add_signal_watch()
            bus.connect('message', self._bus_watcher)
            GObject.threads_init()
            Gtk.main()
        threading.Thread(target=run_player).start()

        yield self.register(self.get_state,
                'com.forrestli.jukebox.player.get_state')
        yield self.register(self.play,
                'com.forrestli.jukebox.player.play')
        yield self.register(self.toggle_pause,
                'com.forrestli.jukebox.player.toggle_pause')

    def _bus_watcher(self, bus, msg):
        if msg.type == Gst.MessageType.ERROR:
            self.log.info('[player] error: {error}', error=msg.parse_error())

    @inlineCallbacks
    def wait_for_state(self, gst_state):
        """I know this isn't asynchronous, but it gets the job done.
        Technically I should be checking for state changes in _bus_watcher...
        """
        counter = 0
        max_counter = 10
        while counter <= max_counter:
            # block up to 1 second
            state_change_return, state, pending  = self.player.get_state(1)
            if state_change_return == Gst.StateChangeReturn.SUCCESS:
                return True
            yield sleep(0.5)
            counter += 1
        self.log.info('State change failed: {ret}, {state}, {pending}',
                ret=state_change_return, state=state, pending=pending)
        return False

    def get_state(self):
        return {
            'currently_playing': self.current_song,
            'is_playing': self.is_playing,
            'volume': self.volume,
            'position': self.position
        }

    @inlineCallbacks
    def play(self, song_id, url):
        _, _, pending = self.player.get_state(1)
        if pending == Gst.State.VOID_PENDING:
            self.player.set_state(Gst.State.READY)
            success = yield self.wait_for_state(Gst.State.READY)
            if not success:
                return False

            self.current_song = song_id
            self.player.set_property('uri', url)

            self.player.set_state(Gst.State.PLAYING)
            success = yield self.wait_for_state(Gst.State.PLAYING)
            if not success:
                return False
        else:
            self.log.info('[player] cannot play due to pending state: {state}',
                    state=pending)
            return False

        yield self.publish('com.forrestli.jukebox.event.player.play', song_id)
        return True

    @inlineCallbacks
    def toggle_pause(self):
        yield self.publish('com.forrestli.jukebox.event.player.toggle_pause')
        return True

if __name__ == '__main__':
    runner = ApplicationRunner('ws://127.0.0.1:8080/ws', realm='realm1')
    runner.run(JukeboxPlayer)
<commit_msg>added player monitoring and duration property<commit_after>import signal
import threading
import time

from twisted.internet.defer import inlineCallbacks
from twisted.logger import Logger

from autobahn.twisted.util import sleep
from autobahn.twisted.wamp import ApplicationSession, ApplicationRunner
from autobahn.wamp.exception import ApplicationError

import gi
gi.require_version('Gst', '1.0')
gi.require_version('Gtk', '3.0')
from gi.repository import Gst, GObject, Gtk
Gst.init(None)

# ensure that we can actually issue a KeyboardInterrupt to break out
# of Gtk.main()
signal.signal(signal.SIGINT, signal.SIG_DFL)

class JukeboxPlayer(ApplicationSession):

    log = Logger()

    @inlineCallbacks
    def onJoin(self, details):

        self.player = Gst.ElementFactory.make('playbin', None)
        self.current_song = ''
        self.is_playing = False
        self.volume = 100
        self.position = -1
        self.duration = -1

        def run_player():
            bus = self.player.get_bus()
            bus.add_signal_watch()
            bus.connect('message', self._bus_watcher)
            GObject.threads_init()
            Gtk.main()
        threading.Thread(target=run_player).start()

        def monitor_player():
            while True:
                time.sleep(1)
                state, pos = self.player.query_position(Gst.Format.TIME)
                if not state:
                    continue
                self.position = pos
                yield self.publish(
                        'com.forrestli.jukebox.event.player.position', pos)
        threading.Thread(target=monitor_player).start()

        yield self.register(self.get_state,
                'com.forrestli.jukebox.player.get_state')
        yield self.register(self.play,
                'com.forrestli.jukebox.player.play')
        yield self.register(self.toggle_pause,
                'com.forrestli.jukebox.player.toggle_pause')

    def _bus_watcher(self, bus, msg):
        if msg.type == Gst.MessageType.ERROR:
            self.log.info('[player] error: {error}', error=msg.parse_error())

    @inlineCallbacks
    def wait_for_state(self, gst_state):
        """I know this isn't asynchronous, but it gets the job done.
        Technically I should be checking for state changes in _bus_watcher...
        """
        counter = 0
        max_counter = 10
        while counter <= max_counter:
            # block up to 1 second
            state_change_return, state, pending  = self.player.get_state(1)
            if state_change_return == Gst.StateChangeReturn.SUCCESS:
                return True
            yield sleep(0.5)
            counter += 1
        self.log.info('State change failed: {ret}, {state}, {pending}',
                ret=state_change_return, state=state, pending=pending)
        return False

    def get_state(self):
        return {
            'currently_playing': self.current_song,
            'is_playing': self.is_playing,
            'volume': self.volume,
            'position': self.position,
            'duration': self.duration
        }

    @inlineCallbacks
    def play(self, song_id, url):
        _, _, pending = self.player.get_state(1)
        if pending == Gst.State.VOID_PENDING:
            self.player.set_state(Gst.State.READY)
            success = yield self.wait_for_state(Gst.State.READY)
            if not success:
                return False

            self.current_song = song_id
            self.player.set_property('uri', url)

            self.player.set_state(Gst.State.PLAYING)
            success = yield self.wait_for_state(Gst.State.PLAYING)
            if not success:
                return False
        else:
            self.log.info('[player] cannot play due to pending state: {state}',
                    state=pending)
            return False

        yield self.publish('com.forrestli.jukebox.event.player.play', song_id)
        return True

    @inlineCallbacks
    def toggle_pause(self):
        yield self.publish('com.forrestli.jukebox.event.player.toggle_pause')
        return True

if __name__ == '__main__':
    runner = ApplicationRunner('ws://127.0.0.1:8080/ws', realm='realm1')
    runner.run(JukeboxPlayer)
<|endoftext|>


<commit_before>import sys
import random

class Player:
    VERSION = "haha strategy"

    # Constant holding the weak pair hands when we have the same color
    WEAK_PAIR_HANDS = [
        (2, 7),
        (2, 8),
        (3, 8),
        (3, 7),
        (2, 6),
        (2, 9),
        (3, 9),
        (4, 9),
        (2, 10),
        (5, 9),
        (4, 7),
        (4, 8),
        (5, 8),
        (3, 6)
    ]

    # constant with strong 5 card hands
    STRONG_HANDS = [
        [{"rank": x, "suit": "hearts"}
            for x in ["A", "K", "Q", "J", "10"]],  # royal flush hearts
        [{"rank": x, "suit": "clubs"}
            for x in ["A", "K", "Q", "J", "10"]],  # royal flush clubs
        [{"rank": x, "suit": "diamonds"}
            for x in ["A", "K", "Q", "J", "10"]],  # royal flush diamonds
        [{"rank": x, "suit": "spades"}
            for x in ["A", "K", "Q", "J", "10"]]  # royal flush spades
    ]

    #[{"rank": x, "suit": "hearts"} for x in cards[]] for cards in ["K", "Q", "J", "10", "9", "8", "7", "6"][k:k+5] for k in range(3)

    # Constant holding the face cards one-char symbol and their value
    FACE_CARDS = {'J': 11, 'Q': 12, 'K': 13, 'A': 14}

    def same(self, expected_cards, actual_cards):
        have_it = [False, False, False, False, False]
        for act_card in actual_cards:
            for index, exp_card in enumerate(expected_cards):
                if act_card["rank"] == exp_card["rank"] and act_card["suit"] == exp_card["suit"]:
                    have_it[index] = True
        have_all = True
        for have_this_card in have_it:
            have_all = have_all and have_this_card
        return have_all

    def unicode_repr(self, value):
        """
        Convert a value (string/int) to unicode object

        :param value: string or int
        :rtype: unicode obj
        """

        return unicode(str(value), "utf-8")

    def gen_diff_color_weak_pairs(self):
        """
        Generate weak pair hands. We use it when two cards are in different colors

        :rtype: list[tuple(unicode,unicode)]
        """

        diff_color_weak_pairs = []
        for face in self.FACE_CARDS.keys():
            for value in range(2, 6):
                new_unicode_pair = (self.unicode_repr(
                    face), self.unicode_repr(value))
                diff_color_weak_pairs.append(new_unicode_pair)
        return diff_color_weak_pairs

    def before_flop(self, hole_cards):
        """
        We check if we have weak hands in the beginning, and fold if we have. All in if not
        """
        our_tuple = (hole_cards[0]["rank"], hole_cards[1]["rank"])
        reversed_tuple = (our_tuple[1], our_tuple[0])

        if hole_cards[0]["suit"] == hole_cards[1]["suit"]:
            if our_tuple in self.WEAK_PAIR_HANDS or reversed_tuple in self.WEAK_PAIR_HANDS:
                return 0
        else:
            diff_color_weak_pairs = self.gen_diff_color_weak_pairs()
            if our_tuple in diff_color_weak_pairs or reversed_tuple in diff_color_weak_pairs:
                return 0
        return 10000

    def after_flop(self, hole_cards, community_cards):
        # if we have strong hands
        # for hand in self.STRONG_HANDS:
        #     if self.same(hand, hole_cards + community_cards):
        #         return 10000

        # if we have a match between hole and community cards in figure
        for hole_card in hole_cards:
            for com_card in community_cards:
                if hole_card["rank"] == com_card["rank"]:
                    return 10000

        # if we have a pair
        if hole_cards[0]["rank"] == hole_cards[1]["rank"]:
            return 10000

        # else:
        return 0

    def betRequest(self, game_state):
        # small_blind = game_state["small_blind"]
        current_buy_in = game_state["current_buy_in"]
        pot = game_state["pot"]
        minimum_raise = game_state["minimum_raise"]
        round = game_state["round"]
        dealer = game_state["dealer"]
        players = game_state["players"]
        in_action = game_state["in_action"]
        community_cards = game_state["community_cards"]
        last_bet = players[in_action]["bet"]
        hole_cards = players[in_action]["hole_cards"]

        if len(community_cards) == 0:
            return_bet = self.before_flop(hole_cards)
        else:
            return_bet = self.after_flop(hole_cards, community_cards)

        if return_bet == 10000:  # if we want to go full retard, pls don't
            return_bet = current_buy_in - last_bet + \
                minimum_raise + random.randint(50, 300)

        print(return_bet)
        print >> sys.stderr, return_bet
        return return_bet

    def showdown(self, game_state):
        pass
<commit_msg>let others win strategy<commit_after>import sys
import random

class Player:
    VERSION = "let others win strategy :P"

    # Constant holding the weak pair hands when we have the same color
    WEAK_PAIR_HANDS = [
        (2, 7),
        (2, 8),
        (3, 8),
        (3, 7),
        (2, 6),
        (2, 9),
        (3, 9),
        (4, 9),
        (2, 10),
        (5, 9),
        (4, 7),
        (4, 8),
        (5, 8),
        (3, 6)
    ]

    # constant with strong 5 card hands
    STRONG_HANDS = [
        [{"rank": x, "suit": "hearts"}
            for x in ["A", "K", "Q", "J", "10"]],  # royal flush hearts
        [{"rank": x, "suit": "clubs"}
            for x in ["A", "K", "Q", "J", "10"]],  # royal flush clubs
        [{"rank": x, "suit": "diamonds"}
            for x in ["A", "K", "Q", "J", "10"]],  # royal flush diamonds
        [{"rank": x, "suit": "spades"}
            for x in ["A", "K", "Q", "J", "10"]]  # royal flush spades
    ]

    #[{"rank": x, "suit": "hearts"} for x in cards[]] for cards in ["K", "Q", "J", "10", "9", "8", "7", "6"][k:k+5] for k in range(3)

    # Constant holding the face cards one-char symbol and their value
    FACE_CARDS = {'J': 11, 'Q': 12, 'K': 13, 'A': 14}

    def same(self, expected_cards, actual_cards):
        have_it = [False, False, False, False, False]
        for act_card in actual_cards:
            for index, exp_card in enumerate(expected_cards):
                if act_card["rank"] == exp_card["rank"] and act_card["suit"] == exp_card["suit"]:
                    have_it[index] = True
        have_all = True
        for have_this_card in have_it:
            have_all = have_all and have_this_card
        return have_all

    def unicode_repr(self, value):
        """
        Convert a value (string/int) to unicode object

        :param value: string or int
        :rtype: unicode obj
        """

        return unicode(str(value), "utf-8")

    def gen_diff_color_weak_pairs(self):
        """
        Generate weak pair hands. We use it when two cards are in different colors

        :rtype: list[tuple(unicode,unicode)]
        """

        diff_color_weak_pairs = []
        for face in self.FACE_CARDS.keys():
            for value in range(2, 6):
                new_unicode_pair = (self.unicode_repr(
                    face), self.unicode_repr(value))
                diff_color_weak_pairs.append(new_unicode_pair)
        return diff_color_weak_pairs

    def before_flop(self, hole_cards):
        """
        We check if we have weak hands in the beginning, and fold if we have. All in if not
        """
        our_tuple = (hole_cards[0]["rank"], hole_cards[1]["rank"])
        reversed_tuple = (our_tuple[1], our_tuple[0])

        if hole_cards[0]["suit"] == hole_cards[1]["suit"]:
            if our_tuple in self.WEAK_PAIR_HANDS or reversed_tuple in self.WEAK_PAIR_HANDS:
                return 0
        else:
            diff_color_weak_pairs = self.gen_diff_color_weak_pairs()
            if our_tuple in diff_color_weak_pairs or reversed_tuple in diff_color_weak_pairs:
                return 0
        return 10000

    def after_flop(self, hole_cards, community_cards):
        # if we have strong hands
        # for hand in self.STRONG_HANDS:
        #     if self.same(hand, hole_cards + community_cards):
        #         return 10000

        # if we have a match between hole and community cards in figure
        for hole_card in hole_cards:
            for com_card in community_cards:
                if hole_card["rank"] == com_card["rank"]:
                    return 10000

        # if we have a pair
        if hole_cards[0]["rank"] == hole_cards[1]["rank"]:
            return 10000

        # else:
        return 0

    def betRequest(self, game_state):
        # small_blind = game_state["small_blind"]
        current_buy_in = game_state["current_buy_in"]
        pot = game_state["pot"]
        minimum_raise = game_state["minimum_raise"]
        round = game_state["round"]
        dealer = game_state["dealer"]
        players = game_state["players"]
        in_action = game_state["in_action"]
        community_cards = game_state["community_cards"]
        last_bet = players[in_action]["bet"]
        hole_cards = players[in_action]["hole_cards"]

        if len(community_cards) == 0:
            return_bet = self.before_flop(hole_cards)
        else:
            return_bet = self.after_flop(hole_cards, community_cards)

        if return_bet == 10000:  # if we want to go full retard, pls don't
            return_bet = current_buy_in - last_bet + \
                minimum_raise + random.randint(50, 300)

        print(return_bet)
        print >> sys.stderr, return_bet
        return return_bet

    def showdown(self, game_state):
        pass
<|endoftext|>


<commit_before>import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

import os
import vlc

class Player:
    def __init__(self):
        # Front End
        self.builder = Gtk.Builder()
        self.builder.add_from_file("player.ui")

        # Connect handlers
        handlers = {
                "last_song_button_clicked": lambda x: self.last_song_button_clicked(),
                "play_button_clicked": lambda x: self.play_button_clicked(),
                "next_song_button_clicked": lambda x: self.next_song_button_clicked()
                }
        self.builder.connect_signals(handlers)

        #Load player
        self.playlist_directory = os.path.expanduser("~/Music/DoctorWho/TheFearmonger/")
        self.player = self.fill_playlist()

        #Set up window, display
        self.title = "Player!"
        self.win = self.builder.get_object("dialog1")
        self.win.connect('destroy', lambda w: Gtk.main_quit())
        self.win.show_all()

    ###### ACTIONS
    def fill_playlist(self):
        """Returns a vlc.MediaListPlayer with all the mp3 files from the
        self.playlist_directory"""
        songs = []
        for roots, dirs, files in os.walk(self.playlist_directory):
            for f in files:
                if f.endswith("mp3"):
                    filepath = os.path.join("file://", self.playlist_directory, f)
                    songs.append(filepath)

        playlist = vlc.MediaList()
        for song in sorted(songs):
            playlist.add_media(vlc.Media(song))

        player = vlc.MediaListPlayer()
        player.set_media_list(playlist)
        return player

    ###### EVENTS
    def last_song_button_clicked(self):
        self.player.previous()

    def play_button_clicked(self):
        #TODO: Update for MediaListPlayer
        if self.player.get_state() == vlc.State.Ended: #Play.
            self.player.play()
        else: #Pause/un-pause
            self.player.pause()

    def next_song_button_clicked(self):
        self.player.next()

    ###### MISC

    def main(self):
        Gtk.main()

if __name__ == '__main__':
    app = Player()
    app.main()
<commit_msg>Implemented FileChooserDialog for directory name<commit_after>import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

import os
import vlc

class Player:
    def __init__(self):
        # Front End
        self.builder = Gtk.Builder()
        self.builder.add_from_file("player.ui")

        # Connect handlers
        handlers = {
                "last_song_button_clicked": lambda x: self.last_song_button_clicked(),
                "play_button_clicked": lambda x: self.play_button_clicked(),
                "next_song_button_clicked": lambda x: self.next_song_button_clicked()
                }
        self.builder.connect_signals(handlers)

        #Set up window, display
        self.title = "Player!"
        self.win = self.builder.get_object("dialog1")
        self.win.connect('destroy', lambda w: Gtk.main_quit())
        self.win.show_all()

        #Load player
        #TODO: Take this out of constructor, activate from taskbar
        self.playlist_directory = self.select_directory()
        self.player = self.fill_playlist()

    ###### ACTIONS
    def select_directory(self):
        chooser = Gtk.FileChooserDialog("Please select a playlist directory.",
                self.win,
                Gtk.FileChooserAction.SELECT_FOLDER,
                (Gtk.STOCK_CANCEL,
                    Gtk.ResponseType.CANCEL,
                    Gtk.STOCK_OPEN,
                    Gtk.ResponseType.OK))
        chooser.run()
        filename = chooser.get_filename()
        chooser.destroy()
        return filename

    def fill_playlist(self):
        """Returns a vlc.MediaListPlayer with all the mp3 files from the
        self.playlist_directory"""
        songs = []
        for roots, dirs, files in os.walk(self.playlist_directory):
            for f in files:
                if f.endswith("mp3"):
                    filepath = os.path.join("file://", self.playlist_directory, f)
                    songs.append(filepath)

        playlist = vlc.MediaList()
        for song in sorted(songs):
            playlist.add_media(vlc.Media(song))

        player = vlc.MediaListPlayer()
        player.set_media_list(playlist)
        return player

    ###### EVENTS
    def last_song_button_clicked(self):
        self.player.previous()

    def play_button_clicked(self):
        #TODO: Update for MediaListPlayer
        if self.player.get_state() == vlc.State.Ended: #Play.
            self.player.play()
        else: #Pause/un-pause
            self.player.pause()

    def next_song_button_clicked(self):
        self.player.next()

    ###### MISC

    def main(self):
        Gtk.main()

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