Counting of available objects of the class 'Cat' when changing the variable of the class 'status' - class

Counting of available objects of the class 'class_name' when changing the variable of the class 'status'.
Tell me how to write a function for counting 'cat_counter' available objects of the class 'class_name' when changing the variable of the class 'status'.
The function only works to increase the counter.
I can't prescribe a condition so that when the variable 'status' != 'normal' the cat counter was decreasing.
from random import random
class Cat:
"""Initialization Cat class"""
counter = 0
def __init__(self, name, color):
self.name = name
self.color = color
self.weight = int(1500 + 3000 * random())
self.minimal_weight = 1000
self.maximal_weight = 9000
self.status = 'normal'
Cat.counter += 1
def cat_counter(self):
if self.cat_status != 'normal':
Cat.counter -= 1
return Cat.counter
def cat_display_parameters(self):
"""Display cat's parameters"""
print(f'name: {self.name}, color: {self.color}, weight: {self.weight}, status: {Cat.cat_status(self)}')
def cat_status(self):
"""Setup cat's status throw weight"""
if self.minimal_weight <= self.weight <= self.maximal_weight:
self.status = 'normal'
elif self.weight <= self.minimal_weight:
self.status = 'dead'
elif self.weight >= self.maximal_weight:
self.status = 'exploited'
return self.status
def cat_meow(self):
"""Cat do meow!"""
meow_weight = 100
if Cat.cat_status(self) == 'normal':
self.weight = self.weight - meow_weight
print(f'Cat with name {self.name} do MEOW!')
else:
print(f'Something wrong with {self.name} cat. Cant do meow.')
def cat_feed(self):
"""Cat do feed"""
feed_weight = 1000
if Cat.cat_status(self) == 'normal':
self.weight = self.weight + feed_weight
print(f'Cat with name {self.name} do MEOW!')
else:
print(f'Something wrong with {self.name} cat. Cant do feed.')
def meow_to_die(self):
"""meow to die"""
while self.weight > self.minimal_weight and Cat.cat_status(self) == 'normal':
Cat.cat_meow(self)
def feed_to_exploid(self):
"""feed to exploit"""
while self.weight < self.maximal_weight and Cat.cat_status(self) == 'normal':
Cat.cat_feed(self)
"""Testing cat_one"""
cat_one = Cat('Cat_one', 'color_one')
cat_one.cat_display_parameters()
print('Number of cats:', Cat.counter)
"""Let's do meow to die cat_one"""
cat_one.meow_to_die()
cat_one.cat_display_parameters()
cat_two = Cat('Name_two', 'color_two')
cat_two.cat_display_parameters()
print('Number of cats:', Cat.counter)
"""Let's feed to explode cat_two"""
cat_two.feed_to_exploid()
cat_two.cat_display_parameters()
cat_three = Cat('Name_three', 'color_three')
cat_three.cat_display_parameters()
print('Number of cats:', Cat.counter)
I tried the counter inside the class.
I tried to solve it via #classmethod.

Related

Lambda Sorted won't sort

I'm trying create a lambda Sorted by age, but it's not sorting, would appreciate if someone spots the error. Thank you
I made a class and a menu to input employees with name and age, objective is to print the list sorted by age
Here I show the code I have so far
class employee:
def __init__(self, name, age):
self.name = name
self.age = age
i = 0
list = []
def show():
k = 0
while k < len(list):
list2 =[
{'Name': list[k].name,
'Age' : list[k].age}]
_sorted = sorted(list2, key=lambda x: x['Age'], reverse=True)
print(_sorted)
k += 1
while i == 0:
print("Menu")
print("1. Register")
print("2. Show")
print("3. Exit")
option = int(input())
if option == 1:
print("Register")
n = str(input("Ingrese el nombre del empleado: "))
e = int(input("Ingrese la edad del empleado: "))
emp = employee(n, e)
list.append(emp)
print("Empleado guardado con éxito!")
elif option == 2:
print("Mostrar")
mostar()
elif option == 3:
exit()
else:
print("Option inválid")
I've made some minor changes to make the program run:
class employee:
def __init__(self, name, age):
self.name = name
self.age = age
def show(lst): # <--- make function with parameter, don't use global values
for emp in sorted(lst, key=lambda x: x.age, reverse=True): # <--- iterate over sorted list
print(emp.name, emp.age) # <-- print name, age
lst = []
while True: # <-- you don't need `i` variable here, just break when you want to exit
print("Menu")
print("1. Register")
print("2. Show")
print("3. Exit")
option = int(input())
if option == 1:
print("Register")
n = str(input("Ingrese el nombre del empleado: "))
e = int(input("Ingrese la edad del empleado: "))
emp = employee(n, e)
lst.append(emp)
print("Empleado guardado con éxito!")
elif option == 2:
print("Mostrar")
show(lst) # <--- use show(), not mostrar()
elif option == 3:
break # <--- to exit, break
else:
print("Option inválid")

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.

Change value of variable by reference

Hi I have 4 variables and I want to refer to one of them depending on some conditions, my current code looks as follows:
switch color {
case .Azul:
botonACambiar.tintColor = colores.salidaAzul
if backTees == true {
if option == 1{self.colorHcpBackTees1 = .Azul} else{self.colorHcpBackTees2 = .Azul}
} else {
if option == 1{self.colorHcpFrontTees1 = .Azul} else{self.colorHcpFrontTees2 = .Azul}
}
...
...
case . Cafe:
botonACambiar.tintColor = colores.salidaMarron
if backTees == true {
if option == 1{self.colorHcpBackTees1 = .Cafe} else{self.colorHcpBackTees2 = .Cafe}
} else {
if option == 1{self.colorHcpFrontTees1 = .Cafe} else{self.colorHcpFrontTees2 = .Cafe}
}
}
I have around 8 options, and as you can see it gets kind of messy.
So far I only have 4 different variables that i might manipulate:
Option 1 & 2 for FrontTees & option 1 & 2 for BackTees, but in the future the app might support more options and more colors for front and back tees.
This 4 values are saved in the app and because of this I need to keep track of them individually, thus I have the four variables:
var colorHcpBackTees1: ColoresDeSalidas = .Negra
var colorHcpBackTees2: ColoresDeSalidas = .Blanca
var colorHcpFrontTees1: ColoresDeSalidas = .Roja
var colorHcpFrontTees2: ColoresDeSalidas = .Blanca
Each with their default values, it would be nice to have a way of initializing a reference variable in such a way that I could do something like:
var choice: ColoresDeSalidas{
if backTees && option == 1 { return self.colorHcpBackTees1}
if backTees && option == 2 { return self.colorHcpBackTees2}
if !backTees && option == 1 { return self.colorHcpFrontTees1}
if !backTees && option == 2 { return self.colorHcpFrontTees2}
}
And simply use the variable choice to manipulate the value of the right variable
You can accomplish this using a ReferenceWritableKeyPath.
What is a ReferenceWritableKeyPath?
Think of it as a precise description of a property in a class or struct. A real world example would be The Empire State Building instead of the address which would be 20 W 34th St, New York, NY 10001. You could tell either one to a cab driver and she could take you there.
A ReferenceWritableKeyPath is a generic type. You need to specify the class or struct name and the type of the variable you will be accessing. So your choice variable would be a ReferenceWritableKeyPath<YourClass,ColoresDeSalidas>.
Here is a standalone example:
enum ColoresDeSalidas : String {
case Negra
case Blanca
case Roja
case Azul
case Verde
}
class Foo {
var backTees = false
var option = 1
var colorHcpBackTees1: ColoresDeSalidas = .Negra
var colorHcpBackTees2: ColoresDeSalidas = .Blanca
var colorHcpFrontTees1: ColoresDeSalidas = .Roja
var colorHcpFrontTees2: ColoresDeSalidas = .Blanca
var choice: ReferenceWritableKeyPath<Foo,ColoresDeSalidas> {
if backTees && option == 1 { return \.colorHcpBackTees1 }
if backTees && option == 2 { return \.colorHcpBackTees2 }
if !backTees && option == 1 { return \.colorHcpFrontTees1 }
if !backTees && option == 2 { return \.colorHcpFrontTees2 }
fatalError("We were supposed to return a keyPath for choice")
}
func test() {
backTees = true
option = 2
print("Before: \(self.colorHcpBackTees2)")
// Now update the correct property using the choice KeyPath
self[keyPath: choice] = .Azul
print("After: \(self.colorHcpBackTees2)")
backTees = false
option = 1
// Assign it to another variable, just to show you can
let choiceFront1 = choice
option = 2
// choiceFront1 still refers to !backTees and option 1
// even though option and choice have changed
print("colorHcpFrontTees1 = \(self[keyPath: choiceFront1])")
colorHcpFrontTees1 = .Verde
print("colorHcpFrontTees1 = \(self[keyPath: choiceFront1])")
}
}
Run the test:
Foo().test()
Output:
Before: Blanca
After: Azul
colorHcpFrontTees1 = Roja
colorHcpFrontTees1 = Verde
To clean the code you could wrap the logic for initialising the properties within the enum itself.
extension ColoresDeSalidas {
init?(isBackTee: Bool, option: Int) {
switch (isBackTee, option) {
case (true, 1): self = .colorHcpBackTees1
case (true, 2(: self = .colorHcpBackTees2
case (false, 1): self = .colorHcpFrontTees1
case (false, 2): self = .colorHcpFrontTees2
default: return nil //or assign a default and make non-failable
}
And then you can initialise / update with:
let myVar = ColoresDeSalidas(isBackTee: true, option: 1)

Read first element and next element from a file SCALA

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 ...

Changing an attribute in an object that belongs to RDD

I have the following code :
def generateStoriesnew(outputPath: String, groupedRDD:RDD[(String,Iterable[String])], isInChurnMode: Boolean, isInChurnPeriod: Boolean) {
val windowedRDD = groupedRDD.map(SOME CODE)
var windowedRDD2 = windowedRDD.filter(r => r != null).map(a=>a.churnPeriod(isInChurnPeriod,isInChurnMode))
val prettyStringRDD = windowedRDD2.map(r => {
r.toString
})
prettyStringRDD.saveAsTextFile(outputPath)
}
and here is the code for ChurnPriod function:
def churnPeriod( churnPeriod:Boolean, churnMode: Boolean): Unit = {
if (churnMode && rootEventType.equalsIgnoreCase("c")){
var churnCustStory: CustStoryN = null
var nonChurnCustStory: CustStoryN = null
var churnPeriodEventStory: mutable.MutableList[StoryEventN] = null
var NonChurnEventstory: mutable.MutableList[StoryEventN] = null
churnPeriodEventStory = new mutable.MutableList[StoryEventN]
NonChurnEventstory = new mutable.MutableList[StoryEventN]
var lastEventChurnPeriod = true
var currentEventStory = eventStory
var max = currentEventStory.length
println(max);
if (currentEventStory.size > 0) {
for (i <- 0 until currentEventStory.length) {
var currentEvent = currentEventStory(i)
if (currentEvent.timeSenseRootEvent < 90) {
churnPeriodEventStory.+=(currentEvent)
//lastEventChurnPeriod = true
}
else {
NonChurnEventstory.+=(currentEvent)
lastEventChurnPeriod = false
}
}
}
if (churnPeriod)
eventStory = churnPeriodEventStory
else
eventStory=null
}
}
but churn period function does not change eventstory which is a member of a custstory class. what am I missing here ?
class CustStoryN (val custId:String,
var rootEventType:String,
var rootEventTime:Long,
var eventStory:mutable.MutableList[StoryEventN])
my hypothesis is either:
1.map is not the right transformation for the function that I have
2.churnPeriod function never get called
3.I can not change eventstory which is a member of cust story class
Does anyone have any idea how I can troubleshoot this problem?
This would be trivial to determine by debugging. Just put a few breakpoints and you can see if the program stops inside the function, and what transformations do occur.
My guess would be that the problem is this line: if (currentEventStory.size > 0), thus, a list that starts at size 0 remains at size 0 forever. Another option is that churnPeriod is never true, thus, you compute a lot but never assign to the eventStory variable.
Your code does need a good cleanup ;-)