Tracking down "missing parameter type for expanded function" - scala

Im stuck with with code, whenever I try to run it I get the error:
Error:(37, 66) missing parameter type for expanded function
The argument types of an anonymous function must be fully known. (SLS 8.5)
Expected type was: com.bfg.domain.model.RunnerSnap
def syncPrices(pair: (RunnerSnap, RunnerChange)): RunnerSnap = {
However the error message is not enogh for me to know what I need to change to get this working.
def syncPrices(pair: (RunnerSnap, RunnerChange)): RunnerSnap = {
case (cache: RunnerSnap, delta: RunnerChange) =>
val newHc = if (delta.hc.isEmpty) cache.runnerId.handicap else delta.hc
val id = RunnerId(delta.id, newHc)
val prices = MarketRunnerPrices(
atl = syncPriceVolume(cache.prices.atl, delta.atl),
atb = syncPriceVolume(cache.prices.atb, delta.atb),
trd = syncPriceVolume(cache.prices.trd, delta.trd),
spb = syncPriceVolume(cache.prices.spb, delta.spb),
spl = syncPriceVolume(cache.prices.spl, delta.spl),
batb = syncLevelPriceVolume(cache.prices.batb, delta.batb),
batl = syncLevelPriceVolume(cache.prices.batl, delta.batl),
bdatb = syncLevelPriceVolume(cache.prices.bdatb, delta.bdatb),
bdatl = syncLevelPriceVolume(cache.prices.bdatl, delta.bdatl),
spn = if (delta.spn.isEmpty) cache.prices.spn else delta.spn,
spf = if (delta.hc.isEmpty) cache.prices.spf else delta.spf,
ltp = if (delta.hc.isEmpty) cache.prices.ltp else delta.ltp,
tv = if (delta.hc.isEmpty) cache.prices.tv else delta.tv
)
RunnerSnap(id, prices)
}
My question is: Why am I getting this error and what do I need to
change in my code to get it working as expected?

You are missing pair match:
def syncPrices(pair: (RunnerSnap, RunnerChange)): RunnerSnap = pair match {
case (cache: RunnerSnap, delta: RunnerChange) =>
...
}

Related

Custome prefix for sequence - OdooV14

I'm trying to change the prefix of quotation's sequence in Odoo.
I want that the prefix change by a boolean but i don't have any result.
Here is my code :
class prefix_change(models.Model):
_inherit = 'sale.order'
prefix_choice = fields.Boolean(string="Set to OL", default=False)
def _get_sequence(self, xml_id='quotation.seq'):
user = self.env.user
sequence = self.env['ir.sequence'].with_company(user.company_id).next_by_code(xml_id)
if not sequence:
return _('New')
try:
prefix, suffix = sequence.split('-')
except Exception as e:
logging.error(repr(e))
return _('New')
if not self.prefix_choice :
prefix = "BE"
else:
prefix = "OL"
return "%s-%s-%s" % (prefix, suffix)
Thanks by advance....
Answer W.R.T create and write call:
#api.model
def create(self, values):
res = super(prefix_change, self).create(values)
name = res.name
if res.prefix_choice:
name = res.name.replace('SO', 'OL')
else:
name = res.name.replace('SO', 'BE')
res.name = name
return res
def write(self, values):
res = super(prefix_change, self).write(values)
if 'prefix_choice' in values and values.get('prefix_choice'):
#update code accordingly if needed
if 'BE' in self.name:
self.name = self.name.replace('BE', 'OL')
if 'prefix_choice' in values and not values.get('prefix_choice'):
if 'OL' in self.name:
self.name = self.name.replace('OL', 'BE')
return res
Please check and let me know if it works for you.

Dealing and Sharing State with a Monix Task in a Recursive Loop

I have the following code that iterates recursively and does something over the network. As it goes over the network, I would like to do some optimizations, where the very first optimization would be to avoid going over the network for certain elements that I have already tried.
For example., in the case below, I call a URL, extract the HREF's found in that URL and call those URL's and report the status. As it could be possible that certain URL's might be fetched again, for those URL's that failed, I would like to add them to a global state so that when I encounter this URL the next time, I will avoid those network calls.
Here is the code:
def callURLWithCache(url: String): Task[HttpResult] = {
Task {
Http(url).timeout(connTimeoutMs = 1000, readTimeoutMs = 3000).asString
}.attempt.map {
case Left(err) =>
println(s"ERR happened ----------------- $url ************************ ${err.getMessage}")
// Add to the cache
val httpResult = HttpResult(source = url, isSuccess = false, statusCode = 1000, errorMessage = Some(err.getMessage))
val returnnnn: Try[Any] = httpResultErrorCache.put(url)(httpResult)
httpResult
case Right(doc) =>
if (doc.isError) {
HttpResult(source = url, isSuccess = doc.isSuccess, statusCode = doc.code)
} else {
val hrefs = (browser.parseString(doc.body) >> elementList("a[href]") >?> attr("href"))
.distinct.flatten.filter(_.startsWith("http"))
HttpResult(source = url, isSuccess = doc.isSuccess, statusCode = doc.code, elems = hrefs)
}
}
}
You can see in the case Left(....) block that I add the failed case class to the cache which I define globally on the enclosing class of this function as:
val underlyingCaffeineCache: cache.Cache[String, Entry[HttpResult]] = Caffeine.newBuilder().maximumSize(10000L).build[String, Entry[HttpResult]]
implicit val httpResultErrorCache: Cache[HttpResult] = CaffeineCache(underlyingCaffeineCache)
Here is the function that I do a recursive operation:
def parseSimpleWithFilter(filter: ParserFilter): Task[Seq[HttpResult]] = {
def parseInner(depth: Int, acc: HttpResult): Task[Seq[HttpResult]] = {
import cats.implicits._
if (depth > 0) {
val batched = acc.elems.collect {
case elem if httpResultErrorCache.get(elem).toOption.exists(_.isEmpty) =>
callURLWithCache(elem).flatMap(newElems => parseInner(depth - 1, newElems))
}.sliding(30).toSeq
.map(chunk => Task.parSequence(chunk))
Task.sequence(batched).map(_.flatten).map(_.flatten)
} else Task.pure(Seq(acc))
}
callURLWithCache(filter.url).map(elem => parseInner(filter.recursionDepth, elem)).flatten
}
It can be seen that I'm checking if the url that I have as my current elem is already in the cache, meaning that I have already tried it and failed, so I would like to avoid doing a HTTP call once again for it.
But what happens is that, the httpResultErrorCache turns up always empty. I'm not sure if the Task chunk is causing this behavior. Any ideas on how to get the cache to work?

Lexical Analyzer not getting the next character

So I am working on a project where we are making a small compiler program but before I can move on to the other parts I am having troubles with getting the lexical analyzer to output anything after '\BEGIN' afterwards I debugged it and it seems the value is stuck in a loop where the condition is saying the next character is always a newline. Is it because I haven't added the pattern matching yet to the defined tokens?
Here is the code
import java.util
//import com.sun.javafx.fxml.expression.Expression.Parser.Token
/*Lexical analyzer will be responsible for the following:
- finds the lexemes
- Checks each given character determining the tokens
* */
class MyLexicalAnalyzer extends LexicalAnalyzer {
//Array full of the keywords
//val SpecialCharacters = List(']', '#', '*', '+', '\\', '[', '(',')', "![", '=')
val TEXT = "[a-z] | _ | 0-9 | [A-Z]:"
private var sourceLine: String = null
private val lexeme: Array[Char] = new Array[Char](999)
private var nextChar: Char = 0
private var lexLength: Int = 0
private var position: Int = 0
private val lexems: util.List[String] = new util.ArrayList[String]
def start(line: String): Unit = {
initializeLexems()
sourceLine = line
position = 0
getChar()
getNextToken()
}
// A helper method to determine if the current character is a space.
private def isSpace(c: Char) = c == ' '
//Defined and intialized tokens
def initializeLexems(): Any = {
lexems.add("\\BEGIN")
lexems.add("\\END")
lexems.add("\\PARAB")
lexems.add("\\DEF[")
lexems.add("\\USE[")
lexems.add("\\PARAE")
lexems.add("\\TITLE[")
lexems.add("]")
lexems.add("[")
lexems.add("\\")
lexems.add("(")
lexems.add(")")
lexems.add("![")
lexems.add("=")
lexems.add("+")
lexems.add("#")
}
//val pattern = new regex("''").r
def getNextToken() ={
lexLength = 0
// Ignore spaces and add the first character to the token
getNonBlank()
addChar()
getChar()
// Continue gathering characters for the token
while ( {
(nextChar != '\n') && (nextChar != ' ')
}) {
addChar()
getChar()
}
// Convert the gathered character array token into a String
val newToken: String = new String(lexeme)
if (lookup(newToken.substring(0, lexLength)))
MyCompiler.setCurrentToken(newToken.substring(0,lexLength))
}
// A helper method to get the next non-blank character.
private def getNonBlank(): Unit = {
while ( {
isSpace(nextChar)
}) getChar()
}
/*
Method of function that adds the current character to the token
after checking to make sure that length of the token isn't too
long, a lexical error in this case.
*/
def addChar(){
if (lexLength <= 998) {
lexeme({
lexLength += 1; lexLength - 1
}) = nextChar
lexeme(lexLength) = 0
}
else
System.out.println("LEXICAL ERROR - The found lexeme is too long!")
if (!isSpace(nextChar))
while ( {
!isSpace(nextChar)
})
getChar()
lexLength = 0
getNonBlank()
addChar()
}
//Reading from the file its obtaining the tokens
def getChar() {
if (position < sourceLine.length)
nextChar = sourceLine.charAt ( {
position += 1;
position - 1
})
else nextChar = '\n'
def lookup(candidateToken: String): Boolean ={
if (!(lexems.contains(candidateToken))) {
System.out.println("LEXICAL ERROR - '" + candidateToken + "' is not recognized.")
return false
}
return true
}
}
else nextChar = '\n'<- this is where the condition goes after rendering the first character '\BEGIN' then just keeps outputting in the debug console as listed below.
This is what the debug console it outputting after '\BEGIN' is read through
Can anyone please let me know why that is? This happens after I keep stepping into it many times as well.
Here is the driver class that uses the lexical analyzer
import scala.io.Source
object MyCompiler {
//check the arguments
//check file extensions
//initialization
//get first token
//call start state
var currentToken : String = ""
def main(args: Array[String]): Unit = {
val filename = args(0)
//check if an input file provided
if(args.length == 0) {
//usage error
println("USAGE ERROR: Must provide an input file. ")
System.exit(0)
}
if(!checkFileExtension(args(0))) {
println("USAGE ERROR: Extension name is invalid make sure its .gtx ")
System.exit(0)
}
val Scanner = new MyLexicalAnalyzer
val Parser = new MySyntaxAnalyzer
//getCurrentToken(Scanner.getNextToken())
//Parser.gittex()
for (line <- Source.fromFile(filename).getLines()){
Scanner.start(line)
println()
}
//.......
//If it gets here, it is compiled
//post processing
}
//checks the file extension if valid and ends with .gtx
def checkFileExtension(filename : String) : Boolean = filename.endsWith(".gtx")
def getCurrentToken() : String = this.currentToken
def setCurrentToken(t : String ) : Unit = this.currentToken = t
}
The code is operating as it is supposed to. The first line contains only the string \BEGIN so the lexical analyser is treating the end of the first line as an '\n' as shown in this method:
def getChar() {
if (position < sourceLine.length)
nextChar = sourceLine.charAt ( {
position += 1;
position - 1
})
else nextChar = '\n'
However, the comment directly above that method does not describe what the method actually does. This could be a hint as to where your confusion lies. If the comment says it should read from the file, but it is not reading from the file, maybe that's what you've forgotten to implement.

PlayFramework: value as is not a member of Array[Byte]

I want to make file download from a database using Play framework.
But when I use this code I get this message:
value as is not a member of Array[Byte]
And if I change Ok(bytOfImage.as("image/jpg")) to Ok(bytOfImage) it works good but I get a file with a name: secondindex without .jpg
Here's my controller:
def secondindex(number: Int) = Action {
var bytOfImage = Array[Byte](1)
val conn = DB.getConnection()
try {
val stmt = conn.createStatement
val rs = stmt.executeQuery("SELECT image from images where id = " + number)
while(rs.next()) {
var blob = rs.getBlob("image")
bytOfImage = blob.getBytes(1, blob.length().toInt)
blob.free()
}
} finally {
conn.close() }
Ok(bytOfImage.as("image/jpg"))
}
You are calling the as method on the wrong object. It should look as follows:
Ok(bytOfImage).as("image/jpg")
If you need download images from browser, you can use method SimpleResult
and add in header"Content-Disposition" -> "attachment"
For example change row Ok(bytOfImage.as("image/jpg")) in you code on
val enumImg: Enumerator[Array[Byte]] = { Enumerator(bytOfImage) }
SimpleResult (
header = ResponseHeader(200, Map("Content-Disposition" -> "attachment")),
body = enumImg
)

Unable to type cast <AnonymousType#1> to <WindowsFormsApplication1.Attributes> [ C#3.0 ]

I have
List<Attributes> la = new List<Attributes>();
la = (from t in result
let t1 = t.AttributeCollection
from t2 in t1
where t2.AttributeCode.Equals(attributeType)
let t3 = t2.TimeSeriesData
from k in t3.ToList()
where k.Key.Equals(startDate) && k.Key.Equals(endDate)
select new
{
AttributeCode = attributeType,
TimeSeriesData = fn(k.Key, k.Value.ToString())
}).ToList<Attributes>();
I am getting the error:
'System.Collections.Generic.IEnumerable<AnonymousType#1>' does not contain a definition for 'ToList' and the best extension method overload 'System.Linq.Enumerable.ToList<TSource>(System.Collections.Generic.IEnumerable<TSource>)' has some invalid arguments
I understood tye error meaning but how to type cast it. I have used var and then iterating over it got the result. But without that any other way by which I can do it?
Using C# 3.0
Thanks
may be:
List<Attributes> la = new List<Attributes>();
la = (from t in result
let t1 = t.AttributeCollection
from t2 in t1
where t2.AttributeCode.Equals(attributeType)
let t3 = t2.TimeSeriesData
from k in t3.ToList()
where k.Key.Equals(startDate) && k.Key.Equals(endDate)
select new Attributes()
{
AttributeCode = attributeType,
TimeSeriesData = fn(k.Key, k.Value.ToString())
}).ToList<Attributes>();
you are constructing anonymous type with same fields as Attributes. But they are different types and can't be cast to each other.
Basically save it to an anonymous list type, and then call a conversion function.
public void TestMethod(){
List<Attributes> la = new List<Attributes>();
var annonyType = (from t in result
let t1 = t.AttributeCollection
from t2 in t1
where t2.AttributeCode.Equals(attributeType)
let t3 = t2.TimeSeriesData
from k in t3.ToList()
where k.Key.Equals(startDate) && k.Key.Equals(endDate)
select new
{
AttributeCode = attributeType,
TimeSeriesData = fn(k.Key, k.Value.ToString())
});
la = annonyType.ConvertAll(x=>ConvertToAttribute(x.AttributeCode , x.TimeSeriesData ));
....
//End test method
}
//... (where TimeSeriesDataType = type returned by fn(
public Attributes ConvertToAttribute(string AttributeType, TimeSeriesDataType d){
return new Attribute()....;
}