I want to generate auto generate book fine of 10% of book cost. I have written the following code but nothing happens. No error comes and not working. book_cost field is in book module.
Please check code.
issue_date = fields.Date('Issue Date', required=True, tracking=True)
due_date = fields.Date('Due Date', required=True, tracking=True)
book_ids = fields.Many2many('odooschool.library.books','tch_book_rel','book_name','teacher_id','Issued Books')
sequence = fields.Integer('sequence')
fine_amount = fields.Char('Fine Amount', compute='_get_cost_details')
submission_date = fields.Date.today()
price = fields.Char('Price')
#api.depends('due_date','book_ids.book_cost')
def _get_cost_details(self):
market_multiplier = 0
date_return = fields.Date()
for rec in self:
fine_amount = 0
if rec.due_date and rec.submission_date and rec.due_date > rec.submission_date:
date_return = (rec.due_date - rec.submission_date)
market_multiplier = int(decimal.Decimal('0.10'))
fine_amount = rec.book_ids.book_cost * market_multiplier
rec.fine_amount += rec.fine_amount
I think if you replace
submission_date = fields.Date.today()
by
submission_date = fields.Date(default= fields.Date.today)
That will be work. Cause the submission_date in your code is always the starting date of Odoo server.
Regards
Related
I have to make a code taking a name and turning it into a last name, first initial, middle initial format. My code works assuming there is a middle name but breaks if not provided a middle name. Is there a way to ignore not having a middle name and to just default to last name and first initial? I'm super new to python3 so I'm sorry if my code is uber bad.
Heres my code :
your_name = input()
broken_name = your_name.split()
first_name = broken_name[0]
middle_name = broken_name[1]
last_name = broken_name[2]
middle_in = middle_name[0]
first_in = first_name[0]
print(last_name+',',first_in+'.'+middle_in+'.' )
You can use an if else statement to check how long broken_name is.
Try:
your_name = input()
broken_name = your_name.split()
if len(broken_name) > 2:
first_name = broken_name[0]
middle_name = broken_name[1]
last_name = broken_name[2]
middle_in = middle_name[0]
first_in = first_name[0]
print(last_name+', ',first_in+'. '+middle_in+'.'
else:
first_name = broken_name[0]
last_name = broken_name[1]
first_in = first_name[0]
print(last_name+', ',first_in+'.')
Another option:
def get_pretty_name_str(names):
splited_names = names.split()
last_name = splited_names.pop(-1)
result = f'{last_name},'
while splited_names:
n = splited_names.pop(0)
result += f'{n}.'
return result
print(get_pretty_name_str('First Middle Last')) # Last,First.Middle.
print(get_pretty_name_str('First Last')) # Last,First.
I am trying to make my discord bot send a message from a random date in the server's history but the around argument doesn't seem to work properly
def random_date():
d1 = date(year=2020, month=3,day=16)
d2= date.today()
delta = d2 - d1
int_delta = delta.days
random_number_of_days = random.randrange(int_delta)
ran = random_number_of_days
global day
day = d1 + timedelta(ran)
# en = d1 + timedelta(ran + 1)
return day
#commands.command(name='quote')
async def quote(self,message):
day = random_date()
messages = await message.channel.history(around=day).flatten()
msg = random.choice(messages)
embed = discord.Embed(description=f'{msg.content}' , color=message.author.color, timestamp=msg.created_at)
embed.set_author(name=f"{msg.author.name}#{msg.author.discriminator}", icon_url=msg.author.avatar_url)
embed.add_field(name = 'Source' , value = f"[Jump]({msg.jump_url})")
embed.set_footer(text=f"Found in : #{message.channel.name}")
await message.channel.send(embed=embed)
See https://discordpy.readthedocs.io/en/latest/api.html?highlight=channel%20history#discord.TextChannel.history
You need to use datetime.datetime()
Also see: https://docs.python.org/3/library/datetime.html#datetime.datetime if you need help with that
I am having some issues with some code. I have set about a project for creating Bitcoin wallets in an attempt to turn a hobby into a learning experience, whereby I can understand both Python and the Bitcoin protocol in more detail. I have posted here rather than in the Bitcoin site as the question is related to Python programming.
Below I have some code which I have created to turn a private key into a WIF key. I have written this out for clarity rather than the most optimal method of coding, so that I can see all the steps clearly and work on issues. This code was previously a series lines which I have now progressed into a class with functions.
I am following the example from this page: https://en.bitcoin.it/wiki/Wallet_import_format
Here is my current code:
import hashlib
import codecs
class wif():
def private_to_wif(private_key):
extended_key = wif.create_extended(private_key)
address = wif.create_wif_address(extended_key)
return address
def create_extended(private_key):
private_key1 = bytes.fromhex(private_key)
private_key2 = codecs.encode(private_key1, 'hex')
mainnet = b'80'
#testnet = b'ef'
#compressed = b'01'
extended_key = mainnet + private_key2
return extended_key
def create_wif_address(extended_key):
first_hash = hashlib.sha256(extended_key)
first_digest = first_hash.digest()
second_hash = hashlib.sha256(first_digest)
second_digest = second_hash.digest()
second_digest_hex = codecs.encode(second_digest, 'hex')
checksum = second_digest_hex[:8]
extended_key_chksm = (extended_key + checksum).decode('utf-8')
wif_address = base58(extended_key_chksm)
return wif_address
def base58(extended_key_chksm):
alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
b58_string = ''
leading_zeros = len(extended_key_chksm) - len(extended_key_chksm.lstrip('0'))
address_int = int(extended_key_chksm, 16)
while address_int > 0:
digit = address_int % 58
digit_char = alphabet[digit]
b58_string = digit_char + b58_string
address_int //= 58
ones = leading_zeros // 2
for one in range(ones):
b58_string = '1' + b58_string
return b58_string
I then use a few lines of code to get this working, using the example private key from the above guide, as follows:
key = ‘0C28FCA386C7A227600B2FE50B7CAE11EC86D3BF1FBE471BE89827E19D72AA1D‘
address = wif.private_to_wif(key)
Print(address)
I should be getting the output: 5HueCGU8rMjxEXxiPuD5BDku4MkFqeZyd4dZ1jvhTVqvbTLvyTJ
Instead I’m getting:
5HueCGU8rMjxEXxiPuD5BDku4MkFqeZyd4dZ1jvhTVqvbWs6eYX
It’s only the last 6 characters that differ!
Any suggestions and help would be greatly appreciated.
Thank you in advance.
Connor
I have managed to find the solution by adding a missing encoding step.
I am posting for all those who run into a similar issue and can see the steps that brought resolution.
def create_wif_address(extended_key):
extended_key_dec = codecs.decode(extended_key, 'hex')
first_hash = hashlib.sha256(extended_key_dec)
first_digest = first_hash.digest()
second_hash = hashlib.sha256(first_digest)
second_digest = second_hash.digest()
second_digest_hex = codecs.encode(second_digest, 'hex')
checksum = second_digest_hex[:8]
extended_key_chksm = (extended_key + checksum).decode('utf-8')
wif_address = base58(extended_key_chksm)
return wif_address
So above I added in a step to the function, at the beginning, to decode the passed in variable from a hexadecimal byte string to raw bytes, which is what the hashing algorithms require it seems, and this produced the result I was hoping to achieve.
Connor
I am working on face recognition system for my academic project. I want to set the first time an employee was recognized as his first active time and the next time he is being recognized should be recorded as his last active time and then calculate the total active hours based on first active and last active time.
I tried with the following code but I'm getting only the current system time as the start time. can someone help me on what I am doing wrong.
Code:
data = pickle.loads(open(args["encodings"], "rb").read())
vs = VideoStream(src=0).start()
writers = None
time.sleep(2.0)
while True:
frame = vs.read()
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
rgb = imutils.resize(frame, width=750)
r = frame.shape[1] / float(rgb.shape[1])
boxes = face_recognition.face_locations(rgb)
encodings = face_recognition.face_encodings(rgb, boxes)
names = []
face_names = []
for encoding in encodings:
matches = face_recognition.compare_faces(data["encodings"],
encoding)
name = "Unknown"
if True in matches:
matchedIdxs = [i for (i, b) in enumerate(matches) if b]
counts = {}
for i in matchedIdxs:
name = data["names"][i]
counts[name] = counts.get(name, 0) + 1
name = max(counts, key=counts.get)
names.append(name)
if names != []:
for i in names:
first_active_time = datetime.now().strftime('%H:%M')
last_active_time = datetime.now().strftime('%H:%M')
difference = datetime.strptime(first_active_time, '%H:%M') - datetime.strptime(last_active_time, '%H:%M')
difference = difference.total_seconds()
total_hours = time.strftime("%H:%M", time.gmtime(difference))
face_names.append([i, first_active_time, last_active_time, total_hours])
I am newbie to python and was trying following code
class Arm(object):
def __init__(self, SNo, ActivityDate, RequesterTeam, RequesterSignumId, RequesterEmailId,Circle,Customer,Technology,WOType,ProblemTitle,ActivityTypeorEqType,SiteID,BSCFACID,EngineerName,EngineerSignum,DetailDescriptionOfActivityToBePerformed,TimelineforActivityCompletion,WOIDbyWFM ):
self.SNo= SNo
self.ActivityDate=ActivityDate
self.RequesterTeam=RequesterTeam
self.RequesterSignumId=RequesterSignumId
self.RequesterEmailId=RequesterEmailId
self.Circle=Circle
self.Customer=Customer
self.Technology=Technology
self.WOType=WOType
self.ProblemTitle=ProblemTitle
self.ActivityTypeorEqType=ActivityTypeorEqType
self.SiteID=SiteID
self.BSCFACID=BSCFACID
self.EngineerName=EngineerName
self.EngineerSignum=EngineerSignum
self.DetailDescriptionOfActivityToBePerformed=DetailDescriptionOfActivityToBePerformed
self.TimelineforActivityCompletion=TimelineforActivityCompletion
self.WOIDbyWFM=WOIDbyWFM
def __str__(self):
return("Arm object:\n"
"SNo = {0}\n"
"ActivityDate = {1}\n"
"RequesterTeam = {2}\n"
"RequesterSignumId = {3}\n"
"RequesterEmailId = {4}\n"
"Circle = {5}\n"
"Customer = {6}\n"
"Technology = {7}\n"
"WOType = {8}\n"
"ProblemTitle = {9}\n"
"ActivityTypeorEqType = {10}\n"
"SiteID = {11}\n"
"BSCFACID = {12}\n"
"EngineerName = {13}\n"
"EngineerSignum = {14}\n"
"DetailDescriptionOfActivityToBePerformed = {15}\n"
"TimelineforActivityCompletion= {16}\n"
"WOIDbyWFM = {17}\n"
.format(self.SNo,
self.ActivityDate,
self.RequesterTeam,
self.RequesterSignumId,
self.RequesterEmailId,
self.Circle,
self.Customer,
self.Technology,
self.WOType,
self.ProblemTitle,
self.ActivityTypeorEqType,
self.SiteID,
self.BSCFACID,
self.EngineerName,
self.EngineerSignum,
self.DetailDescriptionOfActivityToBePerformed,
self.TimelineforActivityCompletion,
self.WOIDbyWFM)
I am getting
File
"C:\Users\OpenSource\eclipse-workspace\PythonWorkSpace\DataHiding\src\Hiding.py", line 26 ^ SyntaxError:unexpected EOF while parsing error
while running the code. please suggest me where i am making errors.
You should have "WOIDbyWFM = {17}\n"..format(self.SNo, .......
You are missing a closing right parentheses at the end of your return statement.
Please use the PyCharm editor and it will show you all errors like eclipse does and then you can correctly indent your code to make it bug free.