<commit_before>package accumulator

import app._
import models._
import play.api.libs.json._
import scala.concurrent.{Future, Promise}
import scala.util.{Try, Success, Failure}
import akka.actor.ActorSystem
import akka.stream.{ActorMaterializer, Materializer}
import akka.http.scaladsl.model._
import utils._
import election.JsElection
import election.ElectionJsonFormatter

trait PostOffice extends ElectionJsonFormatter with Response
{  
  implicit val system = ActorSystem()
  implicit val executor = system.dispatchers.lookup("my-other-dispatcher")
  implicit val materializer = ActorMaterializer()
  // post index counter
  private var index : Long = 0
  private val queue = scala.collection.mutable.Queue[Option[Post]]()
  // the first parameter is the uid
  private val electionMap = scala.collection.mutable.Map[Long, MaintainerWrapper]()
  // list of callbacks to be called when a new election is created
  private val callbackQueue = scala.collection.mutable.Queue[String => Unit]()

  def getElectionInfo(electionId: Long) : Future[HttpResponse] = {
    val promise = Promise[HttpResponse]()
    Future {
      electionMap.get(electionId) match {
        case Some(electionWrapper) =>
           promise.success(HttpResponse(status = 200, entity = Json.stringify(response( electionWrapper.getElectionInfo() )) ))
         
        case None =>
          promise.success(HttpResponse(status = 400, entity = Json.stringify(error(s"Election $electionId not found", ErrorCodes.EO_ERROR)) ))
      }
    }
    promise.future
  }
  
  def add(post: Post) {
    println("GG PostOffice::add")
    queue.synchronized {
      Try {
        post.board_attributes.index.toLong
      } map { postIndex =>
        if(postIndex < index) {
          println("Error: old post")
        } else if(postIndex >= index) {
          if(postIndex < index + queue.size) {
            queue.get((postIndex - index).toInt) map { x =>
              x match {
                case Some(p) =>
                  println("Error: duplicated post")
                case None =>
                  queue.update((postIndex - index).toInt, Some(post))
              }
            }
          } else {
            queue ++= List.fill((postIndex - (index + (queue.size).toLong)).toInt)(None)
            queue += Some(post)
          }
        }
      }
    }
    remove()
  }
  
  private def send(post: Post) {
    println("send post index: " + post.board_attributes.index)
    if("election" == post.user_attributes.section) {
      val group : String = post.user_attributes.group
      if("create" == group) {
        val jsMsg = Json.parse(post.message)
        jsMsg.validate[JsElection] match {
          case jSeqPost: JsSuccess[JsElection] =>
            val electionIdStr = jSeqPost.get.state.id
            Try { electionIdStr.toLong } match {
              case Success(electionId) =>
                val maintainer = new MaintainerWrapper(jSeqPost.get.level, electionIdStr)
                maintainer.push(post)
                electionMap += (electionId -> maintainer)
                callbackQueue.synchronized {
                  callbackQueue foreach { func =>
                    Future { func(electionIdStr) }
                  }
                }
              case Failure(e) =>
                println(s"Error: Election Id is not a number (but It should be): ${electionIdStr}")
            }
          case e: JsError => 
            println("Error: JsCreate format error")
        }
      } else {
        Try { group.toLong } match {
          case Success(electionId) => 
            electionMap.get(electionId) match {
              case Some(electionWrapper) => 
                electionWrapper.push(post)
              case None =>
                println(s"Error: Election Id not found in db: ${electionId}, post is: " + post.toString())
            }
          case Failure(e) => 
            println(s"Error: group is not a number : ${group}")<commit_msg>fix election creation timing/blocking issue<commit_after>package accumulator

import app._
import models._
import play.api.libs.json._
import scala.concurrent.{Future, Promise}
import scala.util.{Try, Success, Failure}
import akka.actor.ActorSystem
import akka.stream.{ActorMaterializer, Materializer}
import akka.http.scaladsl.model._
import utils._
import election.JsElection
import election.ElectionJsonFormatter

trait PostOffice extends ElectionJsonFormatter with Response
{  
  implicit val system = ActorSystem()
  implicit val executor = system.dispatchers.lookup("my-other-dispatcher")
  implicit val materializer = ActorMaterializer()
  // post index counter
  private var index : Long = 0
  private val queue = scala.collection.mutable.Queue[Option[Post]]()
  // the first parameter is the uid
  private val electionMap = scala.collection.mutable.Map[Long, MaintainerWrapper]()
  // list of callbacks to be called when a new election is created
  private val callbackQueue = scala.collection.mutable.Queue[String => Unit]()

  def getElectionInfo(electionId: Long) : Future[HttpResponse] = {
    val promise = Promise[HttpResponse]()
    Future {
      electionMap.get(electionId) match {
        case Some(electionWrapper) =>
           promise.success(HttpResponse(status = 200, entity = Json.stringify(response( electionWrapper.getElectionInfo() )) ))
         
        case None =>
          promise.success(HttpResponse(status = 400, entity = Json.stringify(error(s"Election $electionId not found", ErrorCodes.EO_ERROR)) ))
      }
    }
    promise.future
  }
  
  def add(post: Post) {
    println("GG PostOffice::add")
    queue.synchronized {
      Try {
        post.board_attributes.index.toLong
      } map { postIndex =>
        if(postIndex < index) {
          println("Error: old post")
        } else if(postIndex >= index) {
          if(postIndex < index + queue.size) {
            queue.get((postIndex - index).toInt) map { x =>
              x match {
                case Some(p) =>
                  println("Error: duplicated post")
                case None =>
                  queue.update((postIndex - index).toInt, Some(post))
              }
            }
          } else {
            queue ++= List.fill((postIndex - (index + (queue.size).toLong)).toInt)(None)
            queue += Some(post)
          }
        }
      }
    }
    remove()
  }
  
  private def send(post: Post) {
    println("send post index: " + post.board_attributes.index)
    if("election" == post.user_attributes.section) {
      val group : String = post.user_attributes.group
      if("create" == group) {
        electionMap.synchronized {
          val jsMsg = Json.parse(post.message)
          jsMsg.validate[JsElection] match {
            case jSeqPost: JsSuccess[JsElection] =>
              val electionIdStr = jSeqPost.get.state.id
              Try { electionIdStr.toLong } match {
                case Success(electionId) =>
                  val maintainer = new MaintainerWrapper(jSeqPost.get.level, electionIdStr)
                  maintainer.push(post)
                  electionMap += (electionId -> maintainer)
                  callbackQueue.synchronized {
                    callbackQueue foreach { func =>
                      Future { func(electionIdStr) }
                    }
                  }
                case Failure(e) =>
                  println(s"Error: Election Id is not a number (but It should be): ${electionIdStr}")
              }
            case e: JsError => 
              println("Error: JsCreate format error")
          }
        }
      } else {
        Try { group.toLong } match {
          case Success(electionId) =>
            electionMap.synchronized {
              electionMap.get(electionId) 
            } match {
              case Some(electionWrapper) => 
                electionWrapper.push(post)
              case None =>
                println(s"Error: Election Id not found in db: ${electionId}, post is: " + post.toString())
            }
            
          case Failure(e) => 
            println(s"Error: group is not a number : ${group}")
{'fraction_non_alphanumeric': 0.10386562924539954, 'fraction_numerical': 0.0017290354452266271, 'mean_word_length': 2.11102573953131, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 39, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4142445', 'n_tokens_mistral': 2240, 'n_tokens_neox': 2176, 'n_words': 525}