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.
Related
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.
I have this enum
public enum Format {
case label(key: String)
case textField(key: String)
case image(key: String)
}
And I can use it like:
Format.label(key: "abc")
Format.textField(key: "0.0")
Format.image(key: "mystringfile")
When I try to get the value, I can do it with this:
let control = Format.label(key: "abc")
if case let Format.label(key) = control {
tmp = key
} else if case let Format.image(key) = control {
tmp = key
} else if case let Format.textField(key) = control {
tmp = key
}
With that I can get the value, but I'm not finding the case label, textfield or image.
How I can find the enum that belongs that variable?
If I try to use something like this:
control == Format.label
I get the error:
Binary operator '==' cannot be applied to operands of type
'Table.Format' and '(String) -> Format'
I may misunderstand your question but why not use a switch?
let control = Format.label(key: "abc") // or = Format.textField(key: "whatever") or = Format.image(key: "whatever")
let tmp: String
switch control {
case .label(let key):
// It's a label, do what you need
tmp = key
case .textField(let key):
// It's a textField, do what you need
tmp = key
case .image(let key):
// It's a image, do what you need
tmp = key
}
This lets you act on the type and get the value.
I am reading a file that contain 277272 lines with Int triples (s,p,o) like:
10,44,22
10,47,12
15,38,3
15,41,30
16,38,5
16,44,15
16,47,18
22,38,21
22,41,42
34,44,40
34,47,36
40,38,39
40,41,42
45,38,27
45,41,30
46,44,45
46,47,48
From this file I create a Random access file object in order to navigate trough this file. However I want to extract some specific values that are in the first column, an example can be that I want to extract the values of the row that contains 16 in the first column, then I choose a pointer that is in the half, something like:
var lengthfile = (file.length().asInstanceOf[Int])
var initpointer = lengthfile/2
Then I analize if the first value is 16, if not I did a procedure to move the pointer to the nextlines, or as in this case in the back lines. Once I detect that the first value is 16, I need to know if it was in the first row, the sceond or the last one. The functions that I present here are to get the first value of the line where I have the pointer, and to know the first value from the next line.
def firstvalue(pf: Int, file:RandomAccessFile): List[Int] ={
//val file = new RandomAccessFile(filename, "r")
var pointer = pf
var flag = true
var fline = Option("a")
if (pointer <= file.length()-1){
file.seek(pointer)
fline = Option(file.readLine)
}
else {
pointer = file.length().toInt-12
file.seek(pointer)
fline = Option(file.readLine)
}
while (flag)
{
if (fline.get != "")
{
if (pointer == 0)
{
file.seek(pointer)
fline = Option(file.readLine)
pointer -= 1
flag = false
}
else{
pointer -= 1
file.seek(pointer)
fline = Option(file.readLine)
}
}
else if (fline.get == ""){
flag = false
}
}
pointer += 1
file.seek(pointer)
val line = Option(file.readLine)
val spl = line.get.split(',')
val p = spl.apply(0).toInt
//file.close()
val l = pointer :: p :: Nil
l
}
//def nextvalue(pf: Int, filename:String): List[Int] = {
//val file = new RandomAccessFile(filename, "r")
def nextvalue(pf: Int, file:RandomAccessFile): List[Int] = {
//val file = new RandomAccessFile(filename, "r")
var pointer = pf
var p = 0
var flag = true
var lastline = false
var fline = Option ("a")
if (pointer <= file.length()-1){
file.seek(pointer)
fline = Option(file.readLine)
}
//fline = Option(file.readLine)
while (flag){
if (fline.get != "")
{
if (fline == None)
{
flag = false
lastline = true
}
else{
pointer = file.getFilePointer.toInt
fline = Option(file.readLine)
flag = false
}
}
else if (fline.get == ""){
fline = Option(file.readLine)
flag = false
}
}
if (lastline == false)
{
//file.close()
if (fline != None){
val spl = fline.get.split(',')
p = spl.apply(0).toInt
}
}
val l = pointer :: p :: Nil
l
}
However I have a prformance problem, because I am reading character by character, I am trying to fix that during a lot of days, and I don't have a solution. I don't know If perhaps the file object have a function to read back lines, or something that allows to me improve this code? How can I improve this code?
Source
.fromFile(file)
.getLines
.zipWithIndex
.filter(_._1.startsWith("16,"))
Will give you all lines, that start with "16", along with their indices in the file. That should be faster then seeking back and forth ...
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) =>
...
}
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
)