How to conditionally update the value of an object in Python? - python

I am learning Python and working on a sequencing program
In the program I have an attribut called 'Uptime'
Uptime has a fixed value of 60mins (for each day)
I want to create a function that will conditionnally Update the 'Uptime'
To drive more clarity, I use an excel to retrieve the Uptime value:
Uptime_data = pd.read_excel(excel_file, sheet_name='Up_value')
And here is the function I tried to create in order to not use a fixed value, but rather a value that will change accordingly to another attribut called 'Day':
def get_uptime_value(Uptime_data, day : Day, week : Week):
if day[Week] == 7:
Uptime_data += 120
return Uptime_data
The function itself has no error, but nothing changes in the Program.
Can you please help and spot what am I doing wrong?
Many thanks !

Related

{ODOO :: Payroll] get total of worked days into another field inside the payslip

In Odoo 14 community, using hr_payroll_community module, I'm looking to save the total value of 'number_of_days' in worked days tree in another field to allow me use it in another place, and the below screenshot describe the needs.
enter image description here
please advice.... big thanks
I don't know the actual field names. But you should need a computed field for the total and then calculate the total to it.
total_days = fields.Float(name="Total Days", compute='_compute_total', store=True)
#api.depends('line_ids.days')
def _compute_total(self):
for record in self:
record.total_days = sum(record.line_ids.mapped('days'))

How to check if a key already exists in the database using Firebase and Python?

Essentially, I'll be using a database of this structure:
to keep track of the users' xp. Under the xp_data section, there will be multiple timestamps and xp numbers for each timestamp. A function will run every 24 hours, that will log the users' XP. I want to have some way to check if the player is already in the database (and if so, add to their existing xp count) and if not, create a new node for them. Here is my code for writing to the server:
db_ref = db.reference('/')
for i in range(100):
tom = await mee6API.levels.get_leaderboard_page(i)
if xp_trigger:
break
this_lb_list = {}
for l in tom['players']:
if l['xp'] < 300:
xp_trigger = True
break
this_lb_list.update({l['id']: {'name': l['username'], 'xp_data': {time.strftime(time_format_str, time.gmtime()): l['xp']}}})
details += [{ int(l['id']) : l['xp']}]
print(i)
db_ref.update(this_lb_list)
Basically, this code loops through each page in the leaderboard, obtains the XP for each user, and appends it to a dict, which is then used to update the database. there are two problems with this code, one is that it does not check if the user already exists, meaning that, and this is the second problem, that it overwrites the user's existing data. I've also attempted to write the data for each player individually, but problem 1 was still an issue, and it was painfully slow. What can I do to rectify this?
When you pass a value for a property in update(), that value replaces the entire existing value of the property in the database. So while update() leaves the properties you don't specify in the call unmodified, it does completely replace any property you do specify.
To add a value to an existing property, you'll want to specify the entire path as the key, separating the various child nodes with /.
So something like:
this_lb_list.update({'xp_data/13-Auth-2021': l['xp']})
This will write only the 13-Auth-2021 of xp_data, leaving all other child nodes of xp_data unmodified.
You'll of course want to use a variable for the date/time, but the important thing is that you specify it in the key, and not in the value of the dictionary.

Intro to Python: Creating a function that tests the validity of 'months'

I have to say thank you in advance to whomever is helping me out here, I recently started learning python a fews days ago and a current problem set we are working on has been quite confusing.
I think it has to do with a fundamental misunderstanding of mine on how parameters are assigned within a function.
As I have briefly mentioned in title, I am being tasked with creating a function is_months_valid(months)
This is what I have done so far, brace yourselves:
def is_valid_month(month):
month = int
if month <= 0:
month == False
print('this is not a valid month')
if month >12:
month = False
print('this is not a valid month')
return month
As you can see what I am trying to do here is create an integer range from 1 to 12 where 'months' is a valid date.
The issue that I have been encountering is this:
'<=' not supported between instances of 'type' and 'int'
I.e a type error, and I think that my issue is that I am having trouble defining my parameter 'months' as an integer that can take any value. And this value, when run through my program presents me with a valid month or a print statement that says that
'this isnt a valid month'
Again, I am not sure how my code appears to anyone outside my perspective but I would appreciate any and all feedback on it.
Thank you
EDIT: Thank you guys my little frankenstein code finally works, for some reason I was under the assumption that in order to have my parameter (month) take any integer value I wanted, I needed to define it as an 'int.'
I know that stackoverflow isnt "help a student with his cs homework.com" but thank you all for your feedback regarding my indentation, the rules of python, and the guidance in the right direction. Coding is something that I want to improve on and hopefully become literate in.
Thank you
Maybe you meant that!
def is_valid_month(month):
if month <= 0:
month = False
print('this is not a valid month')
elif month >12:
month = False
print('this is not a valid month')
else:month=True
return month

Using an IF THEN loop with nested JSON files in Python

I am currently writing a program which uses the ComapaniesHouse API to return a json file containing information about a certain company.
I am able to retrieve the data easily using the following commands:
r = requests.get('https://api.companieshouse.gov.uk/company/COMPANY-NO/filing-history', auth=('API-KEY', ''))
data = r.json()
With that information I can do an awful lot, however I've ran into a problem which I was hoping you guys could possible help me with. What I aim to do is go through every nested entry in the json file and check if the value of certain keys matches certain criteria, if the values of 2 keys match a certain criteria then other code is executed.
One of the keys is the date of an entry, and I would like to ignore results that are older than a certain date, I have attempted to do this with the following:
date_threshold = datetime.date.today() - datetime.timedelta(days=30)``
for each in data["items"]:
date = ['date']
type = ['type']
if date < date_threshold and type is "RM01":
print("wwwwww")
In case it isn't clear, what I'm attempting to do (albeit very badly) is assign each of the entries to a variable, which then gets tested against certain criteria.
Although this doesn't work, python spits out a variable mismatch error:
TypeError: unorderable types: list() < datetime.date()
Which makes me think the date is being stored as a string, and so I can't compare it to the datetime value set earlier, but when I check the API documentation (https://developer.companieshouse.gov.uk/api/docs/company/company_number/filing-history/filingHistoryItem-resource.html), it says clearly that the 'date' entry is returned as a date type.
What am I doing wrong, its very clear that I'm extremely new to python given what I presume is the atrocity of my code, but in my head it seems to make at least a little sense. In case none of this clear, I basically want to go through all the entries in the json file, and the if the date and type match a certain description, then other code can be executed (in this case I have just used random text).
Any help is greatly appreciated! Let me know if you need anything cleared up.
:)
EDIT
After tweaking my code to the below:
for each in data["items"]:
date = each['date']
type = each['type']
if date is '2016-09-15' and type is "RM01":
print("wwwwww")
The code executes without any errors, but the words aren't printed, even though I know there is an entry in the json file with that exact date, and that exact type, any thoughts?
SOLUTION:
Thanks to everyone for helping me out, I had made a couple of very basic errors, the code that works as expected is below::
for each in data["items"]:
date = each['date']
typevariable = each['type']
if date == '2016-09-15' and typevariable == "RM01":
print("wwwwww")
This prints the word "wwwwww" 3 times, which is correct seeing as there are 3 entries in the JSON that fulfil those criteria.
You need to first convert your date variable to a datetime type using datetime.strptime()
You are comparing a list type variable date with datetime type variable date_threshold.

How to change the date dynamically using a command in linux

I am writing a python code to change the date in linux system to today-1 (dynamically). I tried various combinations but, yet I am not able to succeed. I searched and I found a close proximity to my scenario in this question .
I am able to change the date if I execute the command with static value say:
date --set="$(date +'2013%m%d %H:%M')"
However, I don't want to specify hardcoded value for year i.e., 2013. Instead i want to specify something like "%y-1" i.e.,
date --set="$(date +'%y-1%m%d %H:%M')"
If I run the above command I get the following error
[root#ramesh ~]$ date --set="$(date +'%y-1%m%d %H:%M')"
date: invalid date `14-11016 13:05'
Thanks for your answer. I did not try your approach though, reason being it has to be once again dealt with formatting issues when working with arithmetic operations incase if you want to.
So, I figured out a much simpler and generalized approach
Fetch the previous_year value with this command
date --date='1 years ago'
This gives the previous year date. Now this can be used in the python program to update the system in the following way
"date --set=$(date +'%%y%%m%s %%H:%%M') % previous_year"
This method has few advantages like
I can apply this method for day and month as well like "1 days ago", "1 month ago" along with +%d, +%m, +%y values.
e.g., date --date='1 years ago' +%y
I don't have to worry about the date and month arithmetic calculation logics
date will interpret the %y-1 literally has you showed. What you need is to retrieve the current year, subtract 1 and use this value as the new year.
To get the current_year - 1 you can do:
previous_year=$((`date +'%y'`-1))
echo $previous_year
>>> 13
Now you just need to use this variable to set the new date.

Categories