Python, where to add a 2nd loop - python

This is my function
def offer(rent_start, rent_end, website):
driver.get(website[0])
driver.find_element_by_xpath('//input[#id="btnUpdateQuote"]').click()
This is my 1st for loop
phones = ["https://xxxxxx/", "phones"]
laptops = ["https://xxxxxx/", "laptops"]
headsets = ["https://xxxxxx/", "headsets"]
keyboards = ["https://xxxxxx/", "keyboards"]
websites_list = [phones,laptops,headsets,keyboards]
for website in websites_list:
offer(rent_start, rent_end, website)
I would like to add the following 2nd for loop in my code, so that first the date is selected and then the website opened. So for example 17 June 2021 selected and then [phones,laptops,headsets,keyboards] are requested. After that 19 June 2021 (+ 2 days) is selected and [phones,laptops,headsets,keyboards] are requested
rent_start = date(2022, 6, 19)
add_to_rent_start = int(2)
alternate_days = timedelta(days=add_to_rent_start)
rent_end = rent_start + alternate days
alternate_days_list = [2, 4, 6, 8]
for alt_days in alternate_days_list:
alternate_days = timedelta(days=add_to_rent_start)

alternate_days_list = [2, 4, 6, 8]
for alt_days in alternate_days_list:
rent_start = date(2022, 6, 19)
alternate_days = timedelta(days=alt_days)
rent_end = rent_start + alternate days
for website in websites_list:
offer(rent_start, rent_end, website)
Then, you can request each URL with alternate_days_list.

Related

Is there any possibility for creating task scheduler on monthly based in python?

I am trying to create monthly task schedule based on user input like, StartBoundary datetime, selected months, DaysOfWeek, WeeksOfMonth however i am getting error,
I can create daily task trigger successfully. however this monthly task scheduling didn't working.
trigger.DaysOfWeek = [2, 3, 4] # Tuesday, Wednesday, Thursday
File "C:\Users\myuser\Desktop\Internal\Task Scheduler\task\Lib\site-
packages\win32com\client\dynamic.py", line 686, in __setattr__
self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
pywintypes.com_error: (-2147352571, 'Type mismatch.', None, 1)
Here is my script:
import win32com.client
import datetime as dt
set_time=dt.datetime(2022,10,6,2,5,58,500000)
computer_name = "" #leave all blank for current computer, current user
computer_username = ""
computer_userdomain = ""
computer_password = ""
action_id = "Test Task" #arbitrary action ID
action_path = r'C:\Users\Somesh\AppData\Local\Programs\Python\Python310\python.exe'
#executable path (could be python.exe)
action_arguments = r'windows_patching.py' #arguments (could be something.py)
action_workdir = r"D:\Practice\patch1.0" #working directory for action executable
author = "Somesh" #so that end users know who you are
description = "testing task" #so that end users can identify the task
task_id = "Test Task"
task_hidden = False #set this to True to hide the task in the interface
username = "myuser"
password = "mypassword"
#define constants
TASK_TRIGGER_DAILY = 2
TASK_TRIGGER_MONTHLY = 3
TASK_CREATE = 2
TASK_CREATE_OR_UPDATE = 6
TASK_ACTION_EXEC = 0
#connect to the scheduler (Vista/Server 2008 and above only)
scheduler = win32com.client.Dispatch("Schedule.Service")
scheduler.Connect(computer_name or None, computer_username or None, computer_userdomain or
None, computer_password or None)
rootFolder = scheduler.GetFolder("\\")
#(re)define the task
taskDef = scheduler.NewTask(0)
colTriggers = taskDef.Triggers
trigger = colTriggers.Create(TASK_TRIGGER_MONTHLY)
trigger.StartBoundary = set_time.isoformat()
trigger.Enabled = True
trigger.DaysOfWeek = [2, 3, 4] # Tuesday, Wednesday, Thursday
trigger.WeeksOfMonth = [1, 2, 3, 4]
trigger.Months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
colActions = taskDef.Actions
action = colActions.Create(TASK_ACTION_EXEC)
action.ID = action_id
action.Path = action_path
action.WorkingDirectory = action_workdir
action.Arguments = action_arguments
info = taskDef.RegistrationInfo
info.Author = author
info.Description = description
settings = taskDef.Settings
settings.ExecutionTimeLimit = "PT2H"
settings.RestartInterval = "PT1M"
settings.RestartCount = 3
settings.Enabled = True
settings.Hidden = task_hidden
logon_type = 1
#register the task (create or update, just keep the task name the same)
result = rootFolder.RegisterTaskDefinition(task_id, taskDef,
TASK_CREATE_OR_UPDATE,username, password, logon_type)
could you please let me know which part i have mmised. that would be appreciated. thank you.

Getting value from a combo box in a table problem

I have a table that's being populated from a database. you can edit the table then update the database with the new data. I have this:
def populate(self):
tablerow = 0
rowcount = 0
self.ui.widget_unass_fights.clearContents()
self.ui.widget_unass_fights.setRowCount(0)
for row in x:
rowcount += 1
self.ui.widget_unass_fights.setRowCount(rowcount)
self.ui.widget_unass_fights.setItem(tablerow, 0, QtWidgets.QTableWidgetItem(str(row[0])))
self.ui.widget_unass_fights.setItem(tablerow, 2, QtWidgets.QTableWidgetItem(str(row[2])))
self.ui.widget_unass_fights.setItem(tablerow, 3, QtWidgets.QTableWidgetItem(str(row[3])))
self.ui.widget_unass_fights.setItem(tablerow, 4, QtWidgets.QTableWidgetItem(str(row[4])))
self.ui.widget_unass_fights.setItem(tablerow, 5, QtWidgets.QTableWidgetItem(str(row[5])))
self.ui.widget_unass_fights.setItem(tablerow, 8, QtWidgets.QTableWidgetItem(str(row[8])))
combobox1 = QComboBox()
combobox1.clear()
for j in self.plane_list_combo:
self.ui.widget_unass_fights.setItem(tablerow, 1, QtWidgets.QTableWidgetItem(""))
combobox1.addItem(j)
self.ui.widget_unass_fights.setCellWidget(tablerow, 1, combobox1)
self.ui.widget_unass_fights.cellWidget(tablerow, 1).setCurrentText(row[1])
combobox2 = QComboBox()
combobox2.clear()
combobox2.addItem("")
combobox3 = QComboBox()
combobox3.clear()
combobox3.addItem("")
for j in self.pilot_list_combo:
self.ui.widget_unass_fights.setItem(tablerow, 6, QtWidgets.QTableWidgetItem(""))
self.ui.widget_unass_fights.setItem(tablerow, 7, QtWidgets.QTableWidgetItem(""))
combobox2.addItem(j)
combobox3.addItem(j)
self.ui.widget_unass_fights.setCellWidget(tablerow, 6, combobox2)
self.ui.widget_unass_fights.setCellWidget(tablerow, 7, combobox3)
self.ui.widget_unass_fights.cellWidget(tablerow, 6).setCurrentText(row[6])
self.ui.widget_unass_fights.cellWidget(tablerow, 7).setCurrentText(row[7])
tablerow += 1
print(self.ui.widget_unass_fights.cellWidget(0, 1).currentText())
def update(self)
rowcount = self.ui.widget_unass_fights.rowCount()
print(self.ui.widget_unass_fights.cellWidget(0, 1).currentText())
for i in range(rowcount):
flight_id = self.ui.widget_unass_fights.item(i, 0).text()
flight_reg = self.ui.widget_unass_fights.cellWidget(i, 1).currentText()
desc = self.ui.widget_unass_fights.item(i, 2).text()
date = self.ui.widget_unass_fights.item(i, 3).text()
etd = self.ui.widget_unass_fights.item(i, 4).text()
flight_time = self.ui.widget_unass_fights.item(i, 5).text()
pilot = self.ui.widget_unass_fights.cellWidget(i, 6).currentText()
co_pilot = self.ui.widget_unass_fights.cellWidget(i, 7).currentText()
max_pax = self.ui.widget_unass_fights.item(i, 8).text()
columns 1, 6, and 7 are combo boxes
When I tried running the update function I got the error:
self.ui.widget_unass_fights.cellWidget(i, 1).currentText()
AttributeError: 'QWidget' object has no attribute 'currentText'
so I put in the 2 print commands to try to find out why. the print command in the populate function works, but the print command in the update function doesn't, they are copy and paste of each other, they should both work right? what am I doing wrong?
EDIT - after fiddling around I found that It will only let me call the last row of the table, none of the others.

Selenium hovering over incorrect FirefoxWebElement instead of the specified one

I am trying to get the time of the last snapshot of the Washington Post front page from the Internet Archives for every day in a range of dates. The problem is that Selenium is not always selecting the correct date, although I have collected a list of date objects and it seems to be error-free. For example, Selenium will jump from January 31 to February 11, instead of to February 1.
Print output:
Moving to 31
Date: 2020-01-31 00:00:00
Last snapshot taken at 22:59:03
Moving to 1
Date: 2020-02-11 00:00:00
Last snapshot taken at 23:53:32
Moving to 2
Date: 2020-02-02 00:00:00
Last snapshot taken at 23:59:56
In this output we can see that it was supposed to go to 1, and that the date object's text said 1, meaning that the date object was extracted from the page correctly. Selenium is not hovering over it correctly though?
Complete code:
urls = ['https://web.archive.org/web/20190901000000*/washingtonpost.com',
'https://web.archive.org/web/*/washingtonpost.com']
browser = webdriver.Firefox(executable_path='/usr/local/bin/geckodriver') # brew install chromedriver then see in terminal where it was installed to and paste this
data = {}
for j in range(0, len(urls)):
browser.get(urls[j])
calendar_grid = WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CLASS_NAME, 'calendar-grid')))
if j == 0: # 2019
browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(10)
start = len(dates) - 1
end = 0
step = -1
elif j == 1: # 2020
start = 0
end = len(dates)
step = 1
dates = calendar_grid.find_elements_by_css_selector('.calendar-day')
print('Dates on page: ' + str(len(dates)))
for i in range(start, end, step):
if j==0 and len(data) == len(desired_ranges[j]): # to end 2019
break
# Hover over the date, let popup appear, wait for loader to disappear, select scroll area
print('Moving to ' + dates[i])
hov = ActionChains(browser).move_to_element(dates[i])
hov.perform()
popup = WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, '.popup-of-day-content')))
WebDriverWait(browser, 20).until(EC.invisibility_of_element_located((By.TAG_NAME, 'svg')))
scroll_area = WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, '.popup-of-day-content > ul > div')))
# Get date and check that it is in our range
date = popup.find_element_by_class_name('day-tooltip-title')
date_formatted = datetime.datetime.strptime(date.text, '%B %d, %Y')
print('Date: ' + str(date_formatted))
if date_formatted not in desired_ranges[j]:
continue # skip if it is not
else:
attempts = 0
while attempts < 5:
try:
browser.execute_script('arguments[0].scrollTop = arguments[0].scrollHeight', scroll_area)
snapshots = popup.find_elements_by_tag_name('a')
last_snapshot = snapshots[len(snapshots) - 1]
print('Last snapshot taken at ' + last_snapshot.text)
data[date_formatted] = {'link': last_snapshot.get_attribute('href'),
'time': last_snapshot.text,
'headlines': []}
break
except StaleElementReferenceException:
attempts += 1
Extra code to set date range:
start_day = datetime.date(2019, 12, 8)
end_day = datetime.date.today()
days = (end_day - start_day).days
desired_range = pd.date_range(start_day, periods=days).tolist()
print('Range: ' + str(start_day) + ' to ' + str(end_day))
print('Days: ' + str(days))
desired_range
def time_in_range(start, end, x):
'''Return true if x is in the range [start, end]'''
if start <= end:
return start <= x <= end
else:
return start <= x or x <= end
#Get 2019 date range
desired_range_in_2019 = [x for x in desired_range if time_in_range(datetime.date(2019, 1, 1), datetime.date(2019, 12, 31), x)]
desired_range_in_2020 = [x for x in desired_range if time_in_range(datetime.date(2020, 1, 1), datetime.date(2020, 12, 31), x)]
desired_ranges = [desired_range_in_2019, desired_range_in_2020]
print('Dates in 2019: ' + str(len(desired_range_in_2019)))
print('Dates in 2020: ' + str(len(desired_range_in_2020)))
Most probably this happens because ActionChains emulates user mouse movement, so the cursor - on its way to a proper element - stumbles upon other elements as your expected conditions kick in. The problem can be reliably reproduced with network throttling. Change network in Developer Tools to Regular 3G and you will be able to observe the issue for February 11 and April 5 cases.
There are certain creative ways to modify the cursor path to eliminate the problem (changing browser window width, going through empty calendar elements in a sequence etc), but the most reliable one would be to put the cursor out of the game completely. Replace the hover logic with the following snippet.
# Hover over the date, let popup appear, wait for loader to disappear, select scroll area
print('Moving to ' + str(dates[i]))
browser.execute_script("""
arguments[0].addEventListener('mouseover', function() {
});
var event = new MouseEvent('mouseover', {
'view': window,
'bubbles': true,
'cancelable': true
});
arguments[0].dispatchEvent(event);""", dates[i])

List prints letters and not strings?

I'm having a hard time getting the following to print correctly:
core = 1, 2, 3, 4, 5
glutes = 6, 7, 8, 9, 10
upper = 11, 12, 13, 14, 15
lower = 16, 17, 18, 19, 20
conditioning = 21, 22, 23, 24, 25
core_ability = int(input("Core: "))
glute_ability = int(input("Glutes: "))
if core_ability > 4:
upper_ability = int(input("Upper body: "))
else:
""
lower_ability = int(input("Lower body: "))
conditioning_ability = int(input("\nConditioning ability level:"))
newcore = core[0:core_ability]
newglutes = glutes[0:glute_ability]
if core_ability > 4:
newupper = upper[0:upper_ability]
newlower = lower[0:lower_ability]
newconditioning = conditioning[0:conditioning_ability]
if core_ability > 4:
movement_bank = str(newcore) + str(newglutes) + str(newupper) + str(newlower) + str(conditioning_ability)
else:
movement_bank = str(newcore) + str(newglutes) + str(newlower) + str(conditioning_ability)
sections = int(input("\nNumber of GPP sections in the session: "))
print("\nSPECIFY THE NUMBER OF MOVEMENTS PER SECTION")
if sections == 1:
section1_num = int(input("Section 1:"))
print(random.sample(movement_bank[0:], k=section1_num))
I get an output the looks like:
' ', ' ', 'r'
when I'd like to get something like:
'1', '16', '8'
I added "str()" to each list in the "movement_bank" list because without it I got an error of: TypeError: can only concatenate list (not "int") to list.
All help is greatly appreciated.
It seems, you have different lists, and want to combine them all into one list.
Use extend:
core = 1, 2, 3, 4, 5
glutes = 6, 7, 8, 9, 10
upper = 11, 12, 13, 14, 15
lower = 16, 17, 18, 19, 20
conditioning = 21, 22, 23, 24, 25
movement_bank = []
core_ability = int(input("Core: "))
movement_bank.extend(core[:core_ability])
glute_ability = int(input("Glutes: "))
movement_bank.extend(glutes[:glute_ability])
if core_ability > 4:
upper_ability = int(input("Upper body: "))
movement_bank.extend(upper[:upper_ability])
lower_ability = int(input("Lower body: "))
movement_bank.extend(lower[:lower_ability])
conditioning_ability = int(input("\nConditioning ability level:"))
movement_bank.extend(conditioning[:conditioning_ability])
sections = int(input("\nNumber of GPP sections in the session: "))
print("\nSPECIFY THE NUMBER OF MOVEMENTS PER SECTION")
if sections == 1:
section1_num = int(input("Section 1:"))
print(random.sample(movement_bank, k=section1_num))

Compare datetime with Django birthday objects

I have a question about my script. I want to know all people who have more than 16 years from my Database. I want to check this when user triggers the function.
I have this function :
def Recensement_array(request) :
date = datetime.now().year
print date # I get year from now
birthday = Identity.objects.values_list('birthday', flat=True) # Return list with all birthday values
for element in birthday :
if date - element < 117 :
print "ok < 117"
else :
print "ok > 117"
From print date I get :
2017
From print birthday I get :
<QuerySet [datetime.date(1991, 12, 23), datetime.date(1900, 9, 12), datetime.date(1900, 9, 12), datetime.date(1900, 9, 12), datetime.date(1900, 9, 12), datetime.date(1089, 9, 22), datetime.date(1900, 9, 12), datetime.date(1900, 9, 12), datetime.date(1089, 9, 22), datetime.date(1089, 9, 22), datetime.date(1089, 9, 22), datetime.date(1089, 9, 22), datetime.date(1990, 12, 12)]>
So my goal is to substract date with birthday and compare if date - birthday = 16 years, I print element, else nothing.
I get two problems :
How extract only year from birthday ?
Then the comparison method is between int and tuple up to now. If I could extract only year from birthday, it should work right ?
Thank you
EDIT :
For example I want to get all people who had 16 years old since the begining of this year or will get 16 years old before the first year :
def Recensement_array(request) :
today = datetime.now()
age_16 = (today - relativedelta(years=16))
result = Identity.objects.filter(birthday__range=[age_16, today]).order_by('lastname')
paginator = Paginator(result, 3)
page = request.GET.get('page', 1)
try:
result = paginator.page(page)
except PageNotAnInteger:
result = paginator.page(1)
except EmptyPage:
result = paginator.page(paginator.num_pages)
context = {
"Identity":Identity,
"age_16":age_16,
"datetime" : datetime,
"result" : result,
"PageNotAnInteger":PageNotAnInteger,
}
return render(request, 'Recensement_resume.html', context)
If you need filter records with some specific year you can just use __year method of date field:
age_16 = (today - relativedelta(years=16))
result = Identity.objects.filter(birthday__year=age_16.year).order_by‌​('last‌​name')

Categories