prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>sleep_schedule.py<|end_file_name|><|fim▁begin|>from datetime import datetime, timedelta
from time import sleep
from random import uniform
class SleepSchedule(object):
"""Pauses the execution of the bot every day for some time
Simulates the user going to sleep every day for some time, the sleep time
and the duration is changed every day by a random offset defined in the
config file
Example Config:
"sleep_schedule": [
{
"time": "12:00",
"duration": "5:30",
"time_random_offset": "00:30",
"duration_random_offset": "00:30",
"wake_up_at_location": ""
},
{
"time": "17:45",
"duration": "3:00",
"time_random_offset": "01:00",
"duration_random_offset": "00:30",
"wake_up_at_location": ""
}
]
time: (HH:MM) local time that the bot should sleep
duration: (HH:MM) the duration of sleep
time_random_offset: (HH:MM) random offset of time that the sleep will start
for this example the possible start time is 11:30-12:30
duration_random_offset: (HH:MM) random offset of duration of sleep
for this example the possible duration is 5:00-6:00
wake_up_at_location: (lat, long | lat, long, alt | "") the location at which the bot wake up
*Note that an empty string ("") will not change the location*. """
LOG_INTERVAL_SECONDS = 600
SCHEDULING_MARGIN = timedelta(minutes=10) # Skip if next sleep is RESCHEDULING_MARGIN from now
def <|fim_middle|>(self, bot, config):
self.bot = bot
self._process_config(config)
self._schedule_next_sleep()
self._calculate_current_sleep()
def work(self):
if self._should_sleep_now():
self._sleep()
wake_up_at_location = self._wake_up_at_location
self._schedule_next_sleep()
if wake_up_at_location:
if hasattr(self.bot, 'api'): # Check if api is already initialized
self.bot.api.set_position(wake_up_at_location[0],wake_up_at_location[1],wake_up_at_location[2])
else:
self.bot.wake_location = wake_up_at_location
if hasattr(self.bot, 'api'): self.bot.login() # Same here
def _process_config(self, config):
self.entries = []
for entry in config:
prepared = {}
prepared['time'] = datetime.strptime(entry['time'] if 'time' in entry else '01:00', '%H:%M')
# Using datetime for easier stripping of timedeltas
raw_duration = datetime.strptime(entry['duration'] if 'duration' in entry else '07:00', '%H:%M')
duration = int(timedelta(hours=raw_duration.hour, minutes=raw_duration.minute).total_seconds())
raw_time_random_offset = datetime.strptime(entry['time_random_offset'] if 'time_random_offset' in entry else '01:00', '%H:%M')
time_random_offset = int(
timedelta(
hours=raw_time_random_offset.hour, minutes=raw_time_random_offset.minute).total_seconds())
raw_duration_random_offset = datetime.strptime(entry['duration_random_offset'] if 'duration_random_offset' in entry else '00:30', '%H:%M')
duration_random_offset = int(
timedelta(
hours=raw_duration_random_offset.hour, minutes=raw_duration_random_offset.minute).total_seconds())
raw_wake_up_at_location = entry['wake_up_at_location'] if 'wake_up_at_location' in entry else ''
if raw_wake_up_at_location:
try:
wake_up_at_location = raw_wake_up_at_location.split(',',2)
lat=float(wake_up_at_location[0])
lng=float(wake_up_at_location[1])
if len(wake_up_at_location) == 3:
alt=float(wake_up_at_location[2])
else:
alt = uniform(self.bot.config.alt_min, self.bot.config.alt_max)
except ValueError:
raise ValueError('SleepSchedule wake_up_at_location, parsing error in location') #TODO there must be a more elegant way to do it...
prepared['wake_up_at_location'] = [lat, lng, alt]
prepared['duration'] = duration
prepared['time_random_offset'] = time_random_offset
prepared['duration_random_offset'] = duration_random_offset
self.entries.append(prepared)
def _schedule_next_sleep(self):
self._next_sleep, self._next_duration, self._wake_up_at_location = self._get_next_sleep_schedule()
self.bot.event_manager.emit(
'next_sleep',
sender=self,
formatted="Next sleep at {time}",
data={
'time': str(self._next_sleep)
}
)
def _calculate_current_sleep(self):
self._current_sleep = self._next_sleep - timedelta(days=1)
current_duration = self._next_duration
self._current_end = self._current_sleep + timedelta(seconds = current_duration)
def _should_sleep_now(self):
if datetime.now() >= self._next_sleep:
return True
if datetime.now() >= self._current_sleep and datetime.now() < self._current_end:
self._next_duration = (self._current_end - datetime.now()).total_seconds()
return True
return False
def _get_next_sleep_schedule(self):
now = datetime.now() + self.SCHEDULING_MARGIN
times = []
for index in range(len(self.entries)):
next_time = now.replace(hour=self.entries[index]['time'].hour, minute=self.entries[index]['time'].minute)
next_time += timedelta(seconds=self._get_random_offset(self.entries[index]['time_random_offset']))
# If sleep time is passed add one day
if next_time <= now:
next_time += timedelta(days=1)
times.append(next_time)
diffs = {}
for index in range(len(self.entries)):
diff = (times[index]-now).total_seconds()
if diff >= 0: diffs[index] = diff
closest = min(diffs.iterkeys(), key=lambda x: diffs[x])
next_time = times[closest]
next_duration = self._get_next_duration(self.entries[closest])
location = self.entries[closest]['wake_up_at_location'] if 'wake_up_at_location' in self.entries[closest] else ''
return next_time, next_duration, location
def _get_next_duration(self, entry):
duration = entry['duration'] + self._get_random_offset(entry['duration_random_offset'])
return duration
def _get_random_offset(self, max_offset):
offset = uniform(-max_offset, max_offset)
return int(offset)
def _sleep(self):
sleep_to_go = self._next_duration
sleep_m, sleep_s = divmod(sleep_to_go, 60)
sleep_h, sleep_m = divmod(sleep_m, 60)
sleep_hms = '%02d:%02d:%02d' % (sleep_h, sleep_m, sleep_s)
now = datetime.now()
wake = str(now + timedelta(seconds=sleep_to_go))
self.bot.event_manager.emit(
'bot_sleep',
sender=self,
formatted="Sleeping for {time_hms}, wake at {wake}",
data={
'time_hms': sleep_hms,
'wake': wake
}
)
while sleep_to_go > 0:
if sleep_to_go < self.LOG_INTERVAL_SECONDS:
sleep(sleep_to_go)
sleep_to_go = 0
else:
sleep(self.LOG_INTERVAL_SECONDS)
sleep_to_go -= self.LOG_INTERVAL_SECONDS
<|fim▁end|> | __init__ |
<|file_name|>sleep_schedule.py<|end_file_name|><|fim▁begin|>from datetime import datetime, timedelta
from time import sleep
from random import uniform
class SleepSchedule(object):
"""Pauses the execution of the bot every day for some time
Simulates the user going to sleep every day for some time, the sleep time
and the duration is changed every day by a random offset defined in the
config file
Example Config:
"sleep_schedule": [
{
"time": "12:00",
"duration": "5:30",
"time_random_offset": "00:30",
"duration_random_offset": "00:30",
"wake_up_at_location": ""
},
{
"time": "17:45",
"duration": "3:00",
"time_random_offset": "01:00",
"duration_random_offset": "00:30",
"wake_up_at_location": ""
}
]
time: (HH:MM) local time that the bot should sleep
duration: (HH:MM) the duration of sleep
time_random_offset: (HH:MM) random offset of time that the sleep will start
for this example the possible start time is 11:30-12:30
duration_random_offset: (HH:MM) random offset of duration of sleep
for this example the possible duration is 5:00-6:00
wake_up_at_location: (lat, long | lat, long, alt | "") the location at which the bot wake up
*Note that an empty string ("") will not change the location*. """
LOG_INTERVAL_SECONDS = 600
SCHEDULING_MARGIN = timedelta(minutes=10) # Skip if next sleep is RESCHEDULING_MARGIN from now
def __init__(self, bot, config):
self.bot = bot
self._process_config(config)
self._schedule_next_sleep()
self._calculate_current_sleep()
def <|fim_middle|>(self):
if self._should_sleep_now():
self._sleep()
wake_up_at_location = self._wake_up_at_location
self._schedule_next_sleep()
if wake_up_at_location:
if hasattr(self.bot, 'api'): # Check if api is already initialized
self.bot.api.set_position(wake_up_at_location[0],wake_up_at_location[1],wake_up_at_location[2])
else:
self.bot.wake_location = wake_up_at_location
if hasattr(self.bot, 'api'): self.bot.login() # Same here
def _process_config(self, config):
self.entries = []
for entry in config:
prepared = {}
prepared['time'] = datetime.strptime(entry['time'] if 'time' in entry else '01:00', '%H:%M')
# Using datetime for easier stripping of timedeltas
raw_duration = datetime.strptime(entry['duration'] if 'duration' in entry else '07:00', '%H:%M')
duration = int(timedelta(hours=raw_duration.hour, minutes=raw_duration.minute).total_seconds())
raw_time_random_offset = datetime.strptime(entry['time_random_offset'] if 'time_random_offset' in entry else '01:00', '%H:%M')
time_random_offset = int(
timedelta(
hours=raw_time_random_offset.hour, minutes=raw_time_random_offset.minute).total_seconds())
raw_duration_random_offset = datetime.strptime(entry['duration_random_offset'] if 'duration_random_offset' in entry else '00:30', '%H:%M')
duration_random_offset = int(
timedelta(
hours=raw_duration_random_offset.hour, minutes=raw_duration_random_offset.minute).total_seconds())
raw_wake_up_at_location = entry['wake_up_at_location'] if 'wake_up_at_location' in entry else ''
if raw_wake_up_at_location:
try:
wake_up_at_location = raw_wake_up_at_location.split(',',2)
lat=float(wake_up_at_location[0])
lng=float(wake_up_at_location[1])
if len(wake_up_at_location) == 3:
alt=float(wake_up_at_location[2])
else:
alt = uniform(self.bot.config.alt_min, self.bot.config.alt_max)
except ValueError:
raise ValueError('SleepSchedule wake_up_at_location, parsing error in location') #TODO there must be a more elegant way to do it...
prepared['wake_up_at_location'] = [lat, lng, alt]
prepared['duration'] = duration
prepared['time_random_offset'] = time_random_offset
prepared['duration_random_offset'] = duration_random_offset
self.entries.append(prepared)
def _schedule_next_sleep(self):
self._next_sleep, self._next_duration, self._wake_up_at_location = self._get_next_sleep_schedule()
self.bot.event_manager.emit(
'next_sleep',
sender=self,
formatted="Next sleep at {time}",
data={
'time': str(self._next_sleep)
}
)
def _calculate_current_sleep(self):
self._current_sleep = self._next_sleep - timedelta(days=1)
current_duration = self._next_duration
self._current_end = self._current_sleep + timedelta(seconds = current_duration)
def _should_sleep_now(self):
if datetime.now() >= self._next_sleep:
return True
if datetime.now() >= self._current_sleep and datetime.now() < self._current_end:
self._next_duration = (self._current_end - datetime.now()).total_seconds()
return True
return False
def _get_next_sleep_schedule(self):
now = datetime.now() + self.SCHEDULING_MARGIN
times = []
for index in range(len(self.entries)):
next_time = now.replace(hour=self.entries[index]['time'].hour, minute=self.entries[index]['time'].minute)
next_time += timedelta(seconds=self._get_random_offset(self.entries[index]['time_random_offset']))
# If sleep time is passed add one day
if next_time <= now:
next_time += timedelta(days=1)
times.append(next_time)
diffs = {}
for index in range(len(self.entries)):
diff = (times[index]-now).total_seconds()
if diff >= 0: diffs[index] = diff
closest = min(diffs.iterkeys(), key=lambda x: diffs[x])
next_time = times[closest]
next_duration = self._get_next_duration(self.entries[closest])
location = self.entries[closest]['wake_up_at_location'] if 'wake_up_at_location' in self.entries[closest] else ''
return next_time, next_duration, location
def _get_next_duration(self, entry):
duration = entry['duration'] + self._get_random_offset(entry['duration_random_offset'])
return duration
def _get_random_offset(self, max_offset):
offset = uniform(-max_offset, max_offset)
return int(offset)
def _sleep(self):
sleep_to_go = self._next_duration
sleep_m, sleep_s = divmod(sleep_to_go, 60)
sleep_h, sleep_m = divmod(sleep_m, 60)
sleep_hms = '%02d:%02d:%02d' % (sleep_h, sleep_m, sleep_s)
now = datetime.now()
wake = str(now + timedelta(seconds=sleep_to_go))
self.bot.event_manager.emit(
'bot_sleep',
sender=self,
formatted="Sleeping for {time_hms}, wake at {wake}",
data={
'time_hms': sleep_hms,
'wake': wake
}
)
while sleep_to_go > 0:
if sleep_to_go < self.LOG_INTERVAL_SECONDS:
sleep(sleep_to_go)
sleep_to_go = 0
else:
sleep(self.LOG_INTERVAL_SECONDS)
sleep_to_go -= self.LOG_INTERVAL_SECONDS
<|fim▁end|> | work |
<|file_name|>sleep_schedule.py<|end_file_name|><|fim▁begin|>from datetime import datetime, timedelta
from time import sleep
from random import uniform
class SleepSchedule(object):
"""Pauses the execution of the bot every day for some time
Simulates the user going to sleep every day for some time, the sleep time
and the duration is changed every day by a random offset defined in the
config file
Example Config:
"sleep_schedule": [
{
"time": "12:00",
"duration": "5:30",
"time_random_offset": "00:30",
"duration_random_offset": "00:30",
"wake_up_at_location": ""
},
{
"time": "17:45",
"duration": "3:00",
"time_random_offset": "01:00",
"duration_random_offset": "00:30",
"wake_up_at_location": ""
}
]
time: (HH:MM) local time that the bot should sleep
duration: (HH:MM) the duration of sleep
time_random_offset: (HH:MM) random offset of time that the sleep will start
for this example the possible start time is 11:30-12:30
duration_random_offset: (HH:MM) random offset of duration of sleep
for this example the possible duration is 5:00-6:00
wake_up_at_location: (lat, long | lat, long, alt | "") the location at which the bot wake up
*Note that an empty string ("") will not change the location*. """
LOG_INTERVAL_SECONDS = 600
SCHEDULING_MARGIN = timedelta(minutes=10) # Skip if next sleep is RESCHEDULING_MARGIN from now
def __init__(self, bot, config):
self.bot = bot
self._process_config(config)
self._schedule_next_sleep()
self._calculate_current_sleep()
def work(self):
if self._should_sleep_now():
self._sleep()
wake_up_at_location = self._wake_up_at_location
self._schedule_next_sleep()
if wake_up_at_location:
if hasattr(self.bot, 'api'): # Check if api is already initialized
self.bot.api.set_position(wake_up_at_location[0],wake_up_at_location[1],wake_up_at_location[2])
else:
self.bot.wake_location = wake_up_at_location
if hasattr(self.bot, 'api'): self.bot.login() # Same here
def <|fim_middle|>(self, config):
self.entries = []
for entry in config:
prepared = {}
prepared['time'] = datetime.strptime(entry['time'] if 'time' in entry else '01:00', '%H:%M')
# Using datetime for easier stripping of timedeltas
raw_duration = datetime.strptime(entry['duration'] if 'duration' in entry else '07:00', '%H:%M')
duration = int(timedelta(hours=raw_duration.hour, minutes=raw_duration.minute).total_seconds())
raw_time_random_offset = datetime.strptime(entry['time_random_offset'] if 'time_random_offset' in entry else '01:00', '%H:%M')
time_random_offset = int(
timedelta(
hours=raw_time_random_offset.hour, minutes=raw_time_random_offset.minute).total_seconds())
raw_duration_random_offset = datetime.strptime(entry['duration_random_offset'] if 'duration_random_offset' in entry else '00:30', '%H:%M')
duration_random_offset = int(
timedelta(
hours=raw_duration_random_offset.hour, minutes=raw_duration_random_offset.minute).total_seconds())
raw_wake_up_at_location = entry['wake_up_at_location'] if 'wake_up_at_location' in entry else ''
if raw_wake_up_at_location:
try:
wake_up_at_location = raw_wake_up_at_location.split(',',2)
lat=float(wake_up_at_location[0])
lng=float(wake_up_at_location[1])
if len(wake_up_at_location) == 3:
alt=float(wake_up_at_location[2])
else:
alt = uniform(self.bot.config.alt_min, self.bot.config.alt_max)
except ValueError:
raise ValueError('SleepSchedule wake_up_at_location, parsing error in location') #TODO there must be a more elegant way to do it...
prepared['wake_up_at_location'] = [lat, lng, alt]
prepared['duration'] = duration
prepared['time_random_offset'] = time_random_offset
prepared['duration_random_offset'] = duration_random_offset
self.entries.append(prepared)
def _schedule_next_sleep(self):
self._next_sleep, self._next_duration, self._wake_up_at_location = self._get_next_sleep_schedule()
self.bot.event_manager.emit(
'next_sleep',
sender=self,
formatted="Next sleep at {time}",
data={
'time': str(self._next_sleep)
}
)
def _calculate_current_sleep(self):
self._current_sleep = self._next_sleep - timedelta(days=1)
current_duration = self._next_duration
self._current_end = self._current_sleep + timedelta(seconds = current_duration)
def _should_sleep_now(self):
if datetime.now() >= self._next_sleep:
return True
if datetime.now() >= self._current_sleep and datetime.now() < self._current_end:
self._next_duration = (self._current_end - datetime.now()).total_seconds()
return True
return False
def _get_next_sleep_schedule(self):
now = datetime.now() + self.SCHEDULING_MARGIN
times = []
for index in range(len(self.entries)):
next_time = now.replace(hour=self.entries[index]['time'].hour, minute=self.entries[index]['time'].minute)
next_time += timedelta(seconds=self._get_random_offset(self.entries[index]['time_random_offset']))
# If sleep time is passed add one day
if next_time <= now:
next_time += timedelta(days=1)
times.append(next_time)
diffs = {}
for index in range(len(self.entries)):
diff = (times[index]-now).total_seconds()
if diff >= 0: diffs[index] = diff
closest = min(diffs.iterkeys(), key=lambda x: diffs[x])
next_time = times[closest]
next_duration = self._get_next_duration(self.entries[closest])
location = self.entries[closest]['wake_up_at_location'] if 'wake_up_at_location' in self.entries[closest] else ''
return next_time, next_duration, location
def _get_next_duration(self, entry):
duration = entry['duration'] + self._get_random_offset(entry['duration_random_offset'])
return duration
def _get_random_offset(self, max_offset):
offset = uniform(-max_offset, max_offset)
return int(offset)
def _sleep(self):
sleep_to_go = self._next_duration
sleep_m, sleep_s = divmod(sleep_to_go, 60)
sleep_h, sleep_m = divmod(sleep_m, 60)
sleep_hms = '%02d:%02d:%02d' % (sleep_h, sleep_m, sleep_s)
now = datetime.now()
wake = str(now + timedelta(seconds=sleep_to_go))
self.bot.event_manager.emit(
'bot_sleep',
sender=self,
formatted="Sleeping for {time_hms}, wake at {wake}",
data={
'time_hms': sleep_hms,
'wake': wake
}
)
while sleep_to_go > 0:
if sleep_to_go < self.LOG_INTERVAL_SECONDS:
sleep(sleep_to_go)
sleep_to_go = 0
else:
sleep(self.LOG_INTERVAL_SECONDS)
sleep_to_go -= self.LOG_INTERVAL_SECONDS
<|fim▁end|> | _process_config |
<|file_name|>sleep_schedule.py<|end_file_name|><|fim▁begin|>from datetime import datetime, timedelta
from time import sleep
from random import uniform
class SleepSchedule(object):
"""Pauses the execution of the bot every day for some time
Simulates the user going to sleep every day for some time, the sleep time
and the duration is changed every day by a random offset defined in the
config file
Example Config:
"sleep_schedule": [
{
"time": "12:00",
"duration": "5:30",
"time_random_offset": "00:30",
"duration_random_offset": "00:30",
"wake_up_at_location": ""
},
{
"time": "17:45",
"duration": "3:00",
"time_random_offset": "01:00",
"duration_random_offset": "00:30",
"wake_up_at_location": ""
}
]
time: (HH:MM) local time that the bot should sleep
duration: (HH:MM) the duration of sleep
time_random_offset: (HH:MM) random offset of time that the sleep will start
for this example the possible start time is 11:30-12:30
duration_random_offset: (HH:MM) random offset of duration of sleep
for this example the possible duration is 5:00-6:00
wake_up_at_location: (lat, long | lat, long, alt | "") the location at which the bot wake up
*Note that an empty string ("") will not change the location*. """
LOG_INTERVAL_SECONDS = 600
SCHEDULING_MARGIN = timedelta(minutes=10) # Skip if next sleep is RESCHEDULING_MARGIN from now
def __init__(self, bot, config):
self.bot = bot
self._process_config(config)
self._schedule_next_sleep()
self._calculate_current_sleep()
def work(self):
if self._should_sleep_now():
self._sleep()
wake_up_at_location = self._wake_up_at_location
self._schedule_next_sleep()
if wake_up_at_location:
if hasattr(self.bot, 'api'): # Check if api is already initialized
self.bot.api.set_position(wake_up_at_location[0],wake_up_at_location[1],wake_up_at_location[2])
else:
self.bot.wake_location = wake_up_at_location
if hasattr(self.bot, 'api'): self.bot.login() # Same here
def _process_config(self, config):
self.entries = []
for entry in config:
prepared = {}
prepared['time'] = datetime.strptime(entry['time'] if 'time' in entry else '01:00', '%H:%M')
# Using datetime for easier stripping of timedeltas
raw_duration = datetime.strptime(entry['duration'] if 'duration' in entry else '07:00', '%H:%M')
duration = int(timedelta(hours=raw_duration.hour, minutes=raw_duration.minute).total_seconds())
raw_time_random_offset = datetime.strptime(entry['time_random_offset'] if 'time_random_offset' in entry else '01:00', '%H:%M')
time_random_offset = int(
timedelta(
hours=raw_time_random_offset.hour, minutes=raw_time_random_offset.minute).total_seconds())
raw_duration_random_offset = datetime.strptime(entry['duration_random_offset'] if 'duration_random_offset' in entry else '00:30', '%H:%M')
duration_random_offset = int(
timedelta(
hours=raw_duration_random_offset.hour, minutes=raw_duration_random_offset.minute).total_seconds())
raw_wake_up_at_location = entry['wake_up_at_location'] if 'wake_up_at_location' in entry else ''
if raw_wake_up_at_location:
try:
wake_up_at_location = raw_wake_up_at_location.split(',',2)
lat=float(wake_up_at_location[0])
lng=float(wake_up_at_location[1])
if len(wake_up_at_location) == 3:
alt=float(wake_up_at_location[2])
else:
alt = uniform(self.bot.config.alt_min, self.bot.config.alt_max)
except ValueError:
raise ValueError('SleepSchedule wake_up_at_location, parsing error in location') #TODO there must be a more elegant way to do it...
prepared['wake_up_at_location'] = [lat, lng, alt]
prepared['duration'] = duration
prepared['time_random_offset'] = time_random_offset
prepared['duration_random_offset'] = duration_random_offset
self.entries.append(prepared)
def <|fim_middle|>(self):
self._next_sleep, self._next_duration, self._wake_up_at_location = self._get_next_sleep_schedule()
self.bot.event_manager.emit(
'next_sleep',
sender=self,
formatted="Next sleep at {time}",
data={
'time': str(self._next_sleep)
}
)
def _calculate_current_sleep(self):
self._current_sleep = self._next_sleep - timedelta(days=1)
current_duration = self._next_duration
self._current_end = self._current_sleep + timedelta(seconds = current_duration)
def _should_sleep_now(self):
if datetime.now() >= self._next_sleep:
return True
if datetime.now() >= self._current_sleep and datetime.now() < self._current_end:
self._next_duration = (self._current_end - datetime.now()).total_seconds()
return True
return False
def _get_next_sleep_schedule(self):
now = datetime.now() + self.SCHEDULING_MARGIN
times = []
for index in range(len(self.entries)):
next_time = now.replace(hour=self.entries[index]['time'].hour, minute=self.entries[index]['time'].minute)
next_time += timedelta(seconds=self._get_random_offset(self.entries[index]['time_random_offset']))
# If sleep time is passed add one day
if next_time <= now:
next_time += timedelta(days=1)
times.append(next_time)
diffs = {}
for index in range(len(self.entries)):
diff = (times[index]-now).total_seconds()
if diff >= 0: diffs[index] = diff
closest = min(diffs.iterkeys(), key=lambda x: diffs[x])
next_time = times[closest]
next_duration = self._get_next_duration(self.entries[closest])
location = self.entries[closest]['wake_up_at_location'] if 'wake_up_at_location' in self.entries[closest] else ''
return next_time, next_duration, location
def _get_next_duration(self, entry):
duration = entry['duration'] + self._get_random_offset(entry['duration_random_offset'])
return duration
def _get_random_offset(self, max_offset):
offset = uniform(-max_offset, max_offset)
return int(offset)
def _sleep(self):
sleep_to_go = self._next_duration
sleep_m, sleep_s = divmod(sleep_to_go, 60)
sleep_h, sleep_m = divmod(sleep_m, 60)
sleep_hms = '%02d:%02d:%02d' % (sleep_h, sleep_m, sleep_s)
now = datetime.now()
wake = str(now + timedelta(seconds=sleep_to_go))
self.bot.event_manager.emit(
'bot_sleep',
sender=self,
formatted="Sleeping for {time_hms}, wake at {wake}",
data={
'time_hms': sleep_hms,
'wake': wake
}
)
while sleep_to_go > 0:
if sleep_to_go < self.LOG_INTERVAL_SECONDS:
sleep(sleep_to_go)
sleep_to_go = 0
else:
sleep(self.LOG_INTERVAL_SECONDS)
sleep_to_go -= self.LOG_INTERVAL_SECONDS
<|fim▁end|> | _schedule_next_sleep |
<|file_name|>sleep_schedule.py<|end_file_name|><|fim▁begin|>from datetime import datetime, timedelta
from time import sleep
from random import uniform
class SleepSchedule(object):
"""Pauses the execution of the bot every day for some time
Simulates the user going to sleep every day for some time, the sleep time
and the duration is changed every day by a random offset defined in the
config file
Example Config:
"sleep_schedule": [
{
"time": "12:00",
"duration": "5:30",
"time_random_offset": "00:30",
"duration_random_offset": "00:30",
"wake_up_at_location": ""
},
{
"time": "17:45",
"duration": "3:00",
"time_random_offset": "01:00",
"duration_random_offset": "00:30",
"wake_up_at_location": ""
}
]
time: (HH:MM) local time that the bot should sleep
duration: (HH:MM) the duration of sleep
time_random_offset: (HH:MM) random offset of time that the sleep will start
for this example the possible start time is 11:30-12:30
duration_random_offset: (HH:MM) random offset of duration of sleep
for this example the possible duration is 5:00-6:00
wake_up_at_location: (lat, long | lat, long, alt | "") the location at which the bot wake up
*Note that an empty string ("") will not change the location*. """
LOG_INTERVAL_SECONDS = 600
SCHEDULING_MARGIN = timedelta(minutes=10) # Skip if next sleep is RESCHEDULING_MARGIN from now
def __init__(self, bot, config):
self.bot = bot
self._process_config(config)
self._schedule_next_sleep()
self._calculate_current_sleep()
def work(self):
if self._should_sleep_now():
self._sleep()
wake_up_at_location = self._wake_up_at_location
self._schedule_next_sleep()
if wake_up_at_location:
if hasattr(self.bot, 'api'): # Check if api is already initialized
self.bot.api.set_position(wake_up_at_location[0],wake_up_at_location[1],wake_up_at_location[2])
else:
self.bot.wake_location = wake_up_at_location
if hasattr(self.bot, 'api'): self.bot.login() # Same here
def _process_config(self, config):
self.entries = []
for entry in config:
prepared = {}
prepared['time'] = datetime.strptime(entry['time'] if 'time' in entry else '01:00', '%H:%M')
# Using datetime for easier stripping of timedeltas
raw_duration = datetime.strptime(entry['duration'] if 'duration' in entry else '07:00', '%H:%M')
duration = int(timedelta(hours=raw_duration.hour, minutes=raw_duration.minute).total_seconds())
raw_time_random_offset = datetime.strptime(entry['time_random_offset'] if 'time_random_offset' in entry else '01:00', '%H:%M')
time_random_offset = int(
timedelta(
hours=raw_time_random_offset.hour, minutes=raw_time_random_offset.minute).total_seconds())
raw_duration_random_offset = datetime.strptime(entry['duration_random_offset'] if 'duration_random_offset' in entry else '00:30', '%H:%M')
duration_random_offset = int(
timedelta(
hours=raw_duration_random_offset.hour, minutes=raw_duration_random_offset.minute).total_seconds())
raw_wake_up_at_location = entry['wake_up_at_location'] if 'wake_up_at_location' in entry else ''
if raw_wake_up_at_location:
try:
wake_up_at_location = raw_wake_up_at_location.split(',',2)
lat=float(wake_up_at_location[0])
lng=float(wake_up_at_location[1])
if len(wake_up_at_location) == 3:
alt=float(wake_up_at_location[2])
else:
alt = uniform(self.bot.config.alt_min, self.bot.config.alt_max)
except ValueError:
raise ValueError('SleepSchedule wake_up_at_location, parsing error in location') #TODO there must be a more elegant way to do it...
prepared['wake_up_at_location'] = [lat, lng, alt]
prepared['duration'] = duration
prepared['time_random_offset'] = time_random_offset
prepared['duration_random_offset'] = duration_random_offset
self.entries.append(prepared)
def _schedule_next_sleep(self):
self._next_sleep, self._next_duration, self._wake_up_at_location = self._get_next_sleep_schedule()
self.bot.event_manager.emit(
'next_sleep',
sender=self,
formatted="Next sleep at {time}",
data={
'time': str(self._next_sleep)
}
)
def <|fim_middle|>(self):
self._current_sleep = self._next_sleep - timedelta(days=1)
current_duration = self._next_duration
self._current_end = self._current_sleep + timedelta(seconds = current_duration)
def _should_sleep_now(self):
if datetime.now() >= self._next_sleep:
return True
if datetime.now() >= self._current_sleep and datetime.now() < self._current_end:
self._next_duration = (self._current_end - datetime.now()).total_seconds()
return True
return False
def _get_next_sleep_schedule(self):
now = datetime.now() + self.SCHEDULING_MARGIN
times = []
for index in range(len(self.entries)):
next_time = now.replace(hour=self.entries[index]['time'].hour, minute=self.entries[index]['time'].minute)
next_time += timedelta(seconds=self._get_random_offset(self.entries[index]['time_random_offset']))
# If sleep time is passed add one day
if next_time <= now:
next_time += timedelta(days=1)
times.append(next_time)
diffs = {}
for index in range(len(self.entries)):
diff = (times[index]-now).total_seconds()
if diff >= 0: diffs[index] = diff
closest = min(diffs.iterkeys(), key=lambda x: diffs[x])
next_time = times[closest]
next_duration = self._get_next_duration(self.entries[closest])
location = self.entries[closest]['wake_up_at_location'] if 'wake_up_at_location' in self.entries[closest] else ''
return next_time, next_duration, location
def _get_next_duration(self, entry):
duration = entry['duration'] + self._get_random_offset(entry['duration_random_offset'])
return duration
def _get_random_offset(self, max_offset):
offset = uniform(-max_offset, max_offset)
return int(offset)
def _sleep(self):
sleep_to_go = self._next_duration
sleep_m, sleep_s = divmod(sleep_to_go, 60)
sleep_h, sleep_m = divmod(sleep_m, 60)
sleep_hms = '%02d:%02d:%02d' % (sleep_h, sleep_m, sleep_s)
now = datetime.now()
wake = str(now + timedelta(seconds=sleep_to_go))
self.bot.event_manager.emit(
'bot_sleep',
sender=self,
formatted="Sleeping for {time_hms}, wake at {wake}",
data={
'time_hms': sleep_hms,
'wake': wake
}
)
while sleep_to_go > 0:
if sleep_to_go < self.LOG_INTERVAL_SECONDS:
sleep(sleep_to_go)
sleep_to_go = 0
else:
sleep(self.LOG_INTERVAL_SECONDS)
sleep_to_go -= self.LOG_INTERVAL_SECONDS
<|fim▁end|> | _calculate_current_sleep |
<|file_name|>sleep_schedule.py<|end_file_name|><|fim▁begin|>from datetime import datetime, timedelta
from time import sleep
from random import uniform
class SleepSchedule(object):
"""Pauses the execution of the bot every day for some time
Simulates the user going to sleep every day for some time, the sleep time
and the duration is changed every day by a random offset defined in the
config file
Example Config:
"sleep_schedule": [
{
"time": "12:00",
"duration": "5:30",
"time_random_offset": "00:30",
"duration_random_offset": "00:30",
"wake_up_at_location": ""
},
{
"time": "17:45",
"duration": "3:00",
"time_random_offset": "01:00",
"duration_random_offset": "00:30",
"wake_up_at_location": ""
}
]
time: (HH:MM) local time that the bot should sleep
duration: (HH:MM) the duration of sleep
time_random_offset: (HH:MM) random offset of time that the sleep will start
for this example the possible start time is 11:30-12:30
duration_random_offset: (HH:MM) random offset of duration of sleep
for this example the possible duration is 5:00-6:00
wake_up_at_location: (lat, long | lat, long, alt | "") the location at which the bot wake up
*Note that an empty string ("") will not change the location*. """
LOG_INTERVAL_SECONDS = 600
SCHEDULING_MARGIN = timedelta(minutes=10) # Skip if next sleep is RESCHEDULING_MARGIN from now
def __init__(self, bot, config):
self.bot = bot
self._process_config(config)
self._schedule_next_sleep()
self._calculate_current_sleep()
def work(self):
if self._should_sleep_now():
self._sleep()
wake_up_at_location = self._wake_up_at_location
self._schedule_next_sleep()
if wake_up_at_location:
if hasattr(self.bot, 'api'): # Check if api is already initialized
self.bot.api.set_position(wake_up_at_location[0],wake_up_at_location[1],wake_up_at_location[2])
else:
self.bot.wake_location = wake_up_at_location
if hasattr(self.bot, 'api'): self.bot.login() # Same here
def _process_config(self, config):
self.entries = []
for entry in config:
prepared = {}
prepared['time'] = datetime.strptime(entry['time'] if 'time' in entry else '01:00', '%H:%M')
# Using datetime for easier stripping of timedeltas
raw_duration = datetime.strptime(entry['duration'] if 'duration' in entry else '07:00', '%H:%M')
duration = int(timedelta(hours=raw_duration.hour, minutes=raw_duration.minute).total_seconds())
raw_time_random_offset = datetime.strptime(entry['time_random_offset'] if 'time_random_offset' in entry else '01:00', '%H:%M')
time_random_offset = int(
timedelta(
hours=raw_time_random_offset.hour, minutes=raw_time_random_offset.minute).total_seconds())
raw_duration_random_offset = datetime.strptime(entry['duration_random_offset'] if 'duration_random_offset' in entry else '00:30', '%H:%M')
duration_random_offset = int(
timedelta(
hours=raw_duration_random_offset.hour, minutes=raw_duration_random_offset.minute).total_seconds())
raw_wake_up_at_location = entry['wake_up_at_location'] if 'wake_up_at_location' in entry else ''
if raw_wake_up_at_location:
try:
wake_up_at_location = raw_wake_up_at_location.split(',',2)
lat=float(wake_up_at_location[0])
lng=float(wake_up_at_location[1])
if len(wake_up_at_location) == 3:
alt=float(wake_up_at_location[2])
else:
alt = uniform(self.bot.config.alt_min, self.bot.config.alt_max)
except ValueError:
raise ValueError('SleepSchedule wake_up_at_location, parsing error in location') #TODO there must be a more elegant way to do it...
prepared['wake_up_at_location'] = [lat, lng, alt]
prepared['duration'] = duration
prepared['time_random_offset'] = time_random_offset
prepared['duration_random_offset'] = duration_random_offset
self.entries.append(prepared)
def _schedule_next_sleep(self):
self._next_sleep, self._next_duration, self._wake_up_at_location = self._get_next_sleep_schedule()
self.bot.event_manager.emit(
'next_sleep',
sender=self,
formatted="Next sleep at {time}",
data={
'time': str(self._next_sleep)
}
)
def _calculate_current_sleep(self):
self._current_sleep = self._next_sleep - timedelta(days=1)
current_duration = self._next_duration
self._current_end = self._current_sleep + timedelta(seconds = current_duration)
def <|fim_middle|>(self):
if datetime.now() >= self._next_sleep:
return True
if datetime.now() >= self._current_sleep and datetime.now() < self._current_end:
self._next_duration = (self._current_end - datetime.now()).total_seconds()
return True
return False
def _get_next_sleep_schedule(self):
now = datetime.now() + self.SCHEDULING_MARGIN
times = []
for index in range(len(self.entries)):
next_time = now.replace(hour=self.entries[index]['time'].hour, minute=self.entries[index]['time'].minute)
next_time += timedelta(seconds=self._get_random_offset(self.entries[index]['time_random_offset']))
# If sleep time is passed add one day
if next_time <= now:
next_time += timedelta(days=1)
times.append(next_time)
diffs = {}
for index in range(len(self.entries)):
diff = (times[index]-now).total_seconds()
if diff >= 0: diffs[index] = diff
closest = min(diffs.iterkeys(), key=lambda x: diffs[x])
next_time = times[closest]
next_duration = self._get_next_duration(self.entries[closest])
location = self.entries[closest]['wake_up_at_location'] if 'wake_up_at_location' in self.entries[closest] else ''
return next_time, next_duration, location
def _get_next_duration(self, entry):
duration = entry['duration'] + self._get_random_offset(entry['duration_random_offset'])
return duration
def _get_random_offset(self, max_offset):
offset = uniform(-max_offset, max_offset)
return int(offset)
def _sleep(self):
sleep_to_go = self._next_duration
sleep_m, sleep_s = divmod(sleep_to_go, 60)
sleep_h, sleep_m = divmod(sleep_m, 60)
sleep_hms = '%02d:%02d:%02d' % (sleep_h, sleep_m, sleep_s)
now = datetime.now()
wake = str(now + timedelta(seconds=sleep_to_go))
self.bot.event_manager.emit(
'bot_sleep',
sender=self,
formatted="Sleeping for {time_hms}, wake at {wake}",
data={
'time_hms': sleep_hms,
'wake': wake
}
)
while sleep_to_go > 0:
if sleep_to_go < self.LOG_INTERVAL_SECONDS:
sleep(sleep_to_go)
sleep_to_go = 0
else:
sleep(self.LOG_INTERVAL_SECONDS)
sleep_to_go -= self.LOG_INTERVAL_SECONDS
<|fim▁end|> | _should_sleep_now |
<|file_name|>sleep_schedule.py<|end_file_name|><|fim▁begin|>from datetime import datetime, timedelta
from time import sleep
from random import uniform
class SleepSchedule(object):
"""Pauses the execution of the bot every day for some time
Simulates the user going to sleep every day for some time, the sleep time
and the duration is changed every day by a random offset defined in the
config file
Example Config:
"sleep_schedule": [
{
"time": "12:00",
"duration": "5:30",
"time_random_offset": "00:30",
"duration_random_offset": "00:30",
"wake_up_at_location": ""
},
{
"time": "17:45",
"duration": "3:00",
"time_random_offset": "01:00",
"duration_random_offset": "00:30",
"wake_up_at_location": ""
}
]
time: (HH:MM) local time that the bot should sleep
duration: (HH:MM) the duration of sleep
time_random_offset: (HH:MM) random offset of time that the sleep will start
for this example the possible start time is 11:30-12:30
duration_random_offset: (HH:MM) random offset of duration of sleep
for this example the possible duration is 5:00-6:00
wake_up_at_location: (lat, long | lat, long, alt | "") the location at which the bot wake up
*Note that an empty string ("") will not change the location*. """
LOG_INTERVAL_SECONDS = 600
SCHEDULING_MARGIN = timedelta(minutes=10) # Skip if next sleep is RESCHEDULING_MARGIN from now
def __init__(self, bot, config):
self.bot = bot
self._process_config(config)
self._schedule_next_sleep()
self._calculate_current_sleep()
def work(self):
if self._should_sleep_now():
self._sleep()
wake_up_at_location = self._wake_up_at_location
self._schedule_next_sleep()
if wake_up_at_location:
if hasattr(self.bot, 'api'): # Check if api is already initialized
self.bot.api.set_position(wake_up_at_location[0],wake_up_at_location[1],wake_up_at_location[2])
else:
self.bot.wake_location = wake_up_at_location
if hasattr(self.bot, 'api'): self.bot.login() # Same here
def _process_config(self, config):
self.entries = []
for entry in config:
prepared = {}
prepared['time'] = datetime.strptime(entry['time'] if 'time' in entry else '01:00', '%H:%M')
# Using datetime for easier stripping of timedeltas
raw_duration = datetime.strptime(entry['duration'] if 'duration' in entry else '07:00', '%H:%M')
duration = int(timedelta(hours=raw_duration.hour, minutes=raw_duration.minute).total_seconds())
raw_time_random_offset = datetime.strptime(entry['time_random_offset'] if 'time_random_offset' in entry else '01:00', '%H:%M')
time_random_offset = int(
timedelta(
hours=raw_time_random_offset.hour, minutes=raw_time_random_offset.minute).total_seconds())
raw_duration_random_offset = datetime.strptime(entry['duration_random_offset'] if 'duration_random_offset' in entry else '00:30', '%H:%M')
duration_random_offset = int(
timedelta(
hours=raw_duration_random_offset.hour, minutes=raw_duration_random_offset.minute).total_seconds())
raw_wake_up_at_location = entry['wake_up_at_location'] if 'wake_up_at_location' in entry else ''
if raw_wake_up_at_location:
try:
wake_up_at_location = raw_wake_up_at_location.split(',',2)
lat=float(wake_up_at_location[0])
lng=float(wake_up_at_location[1])
if len(wake_up_at_location) == 3:
alt=float(wake_up_at_location[2])
else:
alt = uniform(self.bot.config.alt_min, self.bot.config.alt_max)
except ValueError:
raise ValueError('SleepSchedule wake_up_at_location, parsing error in location') #TODO there must be a more elegant way to do it...
prepared['wake_up_at_location'] = [lat, lng, alt]
prepared['duration'] = duration
prepared['time_random_offset'] = time_random_offset
prepared['duration_random_offset'] = duration_random_offset
self.entries.append(prepared)
def _schedule_next_sleep(self):
self._next_sleep, self._next_duration, self._wake_up_at_location = self._get_next_sleep_schedule()
self.bot.event_manager.emit(
'next_sleep',
sender=self,
formatted="Next sleep at {time}",
data={
'time': str(self._next_sleep)
}
)
def _calculate_current_sleep(self):
self._current_sleep = self._next_sleep - timedelta(days=1)
current_duration = self._next_duration
self._current_end = self._current_sleep + timedelta(seconds = current_duration)
def _should_sleep_now(self):
if datetime.now() >= self._next_sleep:
return True
if datetime.now() >= self._current_sleep and datetime.now() < self._current_end:
self._next_duration = (self._current_end - datetime.now()).total_seconds()
return True
return False
def <|fim_middle|>(self):
now = datetime.now() + self.SCHEDULING_MARGIN
times = []
for index in range(len(self.entries)):
next_time = now.replace(hour=self.entries[index]['time'].hour, minute=self.entries[index]['time'].minute)
next_time += timedelta(seconds=self._get_random_offset(self.entries[index]['time_random_offset']))
# If sleep time is passed add one day
if next_time <= now:
next_time += timedelta(days=1)
times.append(next_time)
diffs = {}
for index in range(len(self.entries)):
diff = (times[index]-now).total_seconds()
if diff >= 0: diffs[index] = diff
closest = min(diffs.iterkeys(), key=lambda x: diffs[x])
next_time = times[closest]
next_duration = self._get_next_duration(self.entries[closest])
location = self.entries[closest]['wake_up_at_location'] if 'wake_up_at_location' in self.entries[closest] else ''
return next_time, next_duration, location
def _get_next_duration(self, entry):
duration = entry['duration'] + self._get_random_offset(entry['duration_random_offset'])
return duration
def _get_random_offset(self, max_offset):
offset = uniform(-max_offset, max_offset)
return int(offset)
def _sleep(self):
sleep_to_go = self._next_duration
sleep_m, sleep_s = divmod(sleep_to_go, 60)
sleep_h, sleep_m = divmod(sleep_m, 60)
sleep_hms = '%02d:%02d:%02d' % (sleep_h, sleep_m, sleep_s)
now = datetime.now()
wake = str(now + timedelta(seconds=sleep_to_go))
self.bot.event_manager.emit(
'bot_sleep',
sender=self,
formatted="Sleeping for {time_hms}, wake at {wake}",
data={
'time_hms': sleep_hms,
'wake': wake
}
)
while sleep_to_go > 0:
if sleep_to_go < self.LOG_INTERVAL_SECONDS:
sleep(sleep_to_go)
sleep_to_go = 0
else:
sleep(self.LOG_INTERVAL_SECONDS)
sleep_to_go -= self.LOG_INTERVAL_SECONDS
<|fim▁end|> | _get_next_sleep_schedule |
<|file_name|>sleep_schedule.py<|end_file_name|><|fim▁begin|>from datetime import datetime, timedelta
from time import sleep
from random import uniform
class SleepSchedule(object):
"""Pauses the execution of the bot every day for some time
Simulates the user going to sleep every day for some time, the sleep time
and the duration is changed every day by a random offset defined in the
config file
Example Config:
"sleep_schedule": [
{
"time": "12:00",
"duration": "5:30",
"time_random_offset": "00:30",
"duration_random_offset": "00:30",
"wake_up_at_location": ""
},
{
"time": "17:45",
"duration": "3:00",
"time_random_offset": "01:00",
"duration_random_offset": "00:30",
"wake_up_at_location": ""
}
]
time: (HH:MM) local time that the bot should sleep
duration: (HH:MM) the duration of sleep
time_random_offset: (HH:MM) random offset of time that the sleep will start
for this example the possible start time is 11:30-12:30
duration_random_offset: (HH:MM) random offset of duration of sleep
for this example the possible duration is 5:00-6:00
wake_up_at_location: (lat, long | lat, long, alt | "") the location at which the bot wake up
*Note that an empty string ("") will not change the location*. """
LOG_INTERVAL_SECONDS = 600
SCHEDULING_MARGIN = timedelta(minutes=10) # Skip if next sleep is RESCHEDULING_MARGIN from now
def __init__(self, bot, config):
self.bot = bot
self._process_config(config)
self._schedule_next_sleep()
self._calculate_current_sleep()
def work(self):
if self._should_sleep_now():
self._sleep()
wake_up_at_location = self._wake_up_at_location
self._schedule_next_sleep()
if wake_up_at_location:
if hasattr(self.bot, 'api'): # Check if api is already initialized
self.bot.api.set_position(wake_up_at_location[0],wake_up_at_location[1],wake_up_at_location[2])
else:
self.bot.wake_location = wake_up_at_location
if hasattr(self.bot, 'api'): self.bot.login() # Same here
def _process_config(self, config):
self.entries = []
for entry in config:
prepared = {}
prepared['time'] = datetime.strptime(entry['time'] if 'time' in entry else '01:00', '%H:%M')
# Using datetime for easier stripping of timedeltas
raw_duration = datetime.strptime(entry['duration'] if 'duration' in entry else '07:00', '%H:%M')
duration = int(timedelta(hours=raw_duration.hour, minutes=raw_duration.minute).total_seconds())
raw_time_random_offset = datetime.strptime(entry['time_random_offset'] if 'time_random_offset' in entry else '01:00', '%H:%M')
time_random_offset = int(
timedelta(
hours=raw_time_random_offset.hour, minutes=raw_time_random_offset.minute).total_seconds())
raw_duration_random_offset = datetime.strptime(entry['duration_random_offset'] if 'duration_random_offset' in entry else '00:30', '%H:%M')
duration_random_offset = int(
timedelta(
hours=raw_duration_random_offset.hour, minutes=raw_duration_random_offset.minute).total_seconds())
raw_wake_up_at_location = entry['wake_up_at_location'] if 'wake_up_at_location' in entry else ''
if raw_wake_up_at_location:
try:
wake_up_at_location = raw_wake_up_at_location.split(',',2)
lat=float(wake_up_at_location[0])
lng=float(wake_up_at_location[1])
if len(wake_up_at_location) == 3:
alt=float(wake_up_at_location[2])
else:
alt = uniform(self.bot.config.alt_min, self.bot.config.alt_max)
except ValueError:
raise ValueError('SleepSchedule wake_up_at_location, parsing error in location') #TODO there must be a more elegant way to do it...
prepared['wake_up_at_location'] = [lat, lng, alt]
prepared['duration'] = duration
prepared['time_random_offset'] = time_random_offset
prepared['duration_random_offset'] = duration_random_offset
self.entries.append(prepared)
def _schedule_next_sleep(self):
self._next_sleep, self._next_duration, self._wake_up_at_location = self._get_next_sleep_schedule()
self.bot.event_manager.emit(
'next_sleep',
sender=self,
formatted="Next sleep at {time}",
data={
'time': str(self._next_sleep)
}
)
def _calculate_current_sleep(self):
self._current_sleep = self._next_sleep - timedelta(days=1)
current_duration = self._next_duration
self._current_end = self._current_sleep + timedelta(seconds = current_duration)
def _should_sleep_now(self):
if datetime.now() >= self._next_sleep:
return True
if datetime.now() >= self._current_sleep and datetime.now() < self._current_end:
self._next_duration = (self._current_end - datetime.now()).total_seconds()
return True
return False
def _get_next_sleep_schedule(self):
now = datetime.now() + self.SCHEDULING_MARGIN
times = []
for index in range(len(self.entries)):
next_time = now.replace(hour=self.entries[index]['time'].hour, minute=self.entries[index]['time'].minute)
next_time += timedelta(seconds=self._get_random_offset(self.entries[index]['time_random_offset']))
# If sleep time is passed add one day
if next_time <= now:
next_time += timedelta(days=1)
times.append(next_time)
diffs = {}
for index in range(len(self.entries)):
diff = (times[index]-now).total_seconds()
if diff >= 0: diffs[index] = diff
closest = min(diffs.iterkeys(), key=lambda x: diffs[x])
next_time = times[closest]
next_duration = self._get_next_duration(self.entries[closest])
location = self.entries[closest]['wake_up_at_location'] if 'wake_up_at_location' in self.entries[closest] else ''
return next_time, next_duration, location
def <|fim_middle|>(self, entry):
duration = entry['duration'] + self._get_random_offset(entry['duration_random_offset'])
return duration
def _get_random_offset(self, max_offset):
offset = uniform(-max_offset, max_offset)
return int(offset)
def _sleep(self):
sleep_to_go = self._next_duration
sleep_m, sleep_s = divmod(sleep_to_go, 60)
sleep_h, sleep_m = divmod(sleep_m, 60)
sleep_hms = '%02d:%02d:%02d' % (sleep_h, sleep_m, sleep_s)
now = datetime.now()
wake = str(now + timedelta(seconds=sleep_to_go))
self.bot.event_manager.emit(
'bot_sleep',
sender=self,
formatted="Sleeping for {time_hms}, wake at {wake}",
data={
'time_hms': sleep_hms,
'wake': wake
}
)
while sleep_to_go > 0:
if sleep_to_go < self.LOG_INTERVAL_SECONDS:
sleep(sleep_to_go)
sleep_to_go = 0
else:
sleep(self.LOG_INTERVAL_SECONDS)
sleep_to_go -= self.LOG_INTERVAL_SECONDS
<|fim▁end|> | _get_next_duration |
<|file_name|>sleep_schedule.py<|end_file_name|><|fim▁begin|>from datetime import datetime, timedelta
from time import sleep
from random import uniform
class SleepSchedule(object):
"""Pauses the execution of the bot every day for some time
Simulates the user going to sleep every day for some time, the sleep time
and the duration is changed every day by a random offset defined in the
config file
Example Config:
"sleep_schedule": [
{
"time": "12:00",
"duration": "5:30",
"time_random_offset": "00:30",
"duration_random_offset": "00:30",
"wake_up_at_location": ""
},
{
"time": "17:45",
"duration": "3:00",
"time_random_offset": "01:00",
"duration_random_offset": "00:30",
"wake_up_at_location": ""
}
]
time: (HH:MM) local time that the bot should sleep
duration: (HH:MM) the duration of sleep
time_random_offset: (HH:MM) random offset of time that the sleep will start
for this example the possible start time is 11:30-12:30
duration_random_offset: (HH:MM) random offset of duration of sleep
for this example the possible duration is 5:00-6:00
wake_up_at_location: (lat, long | lat, long, alt | "") the location at which the bot wake up
*Note that an empty string ("") will not change the location*. """
LOG_INTERVAL_SECONDS = 600
SCHEDULING_MARGIN = timedelta(minutes=10) # Skip if next sleep is RESCHEDULING_MARGIN from now
def __init__(self, bot, config):
self.bot = bot
self._process_config(config)
self._schedule_next_sleep()
self._calculate_current_sleep()
def work(self):
if self._should_sleep_now():
self._sleep()
wake_up_at_location = self._wake_up_at_location
self._schedule_next_sleep()
if wake_up_at_location:
if hasattr(self.bot, 'api'): # Check if api is already initialized
self.bot.api.set_position(wake_up_at_location[0],wake_up_at_location[1],wake_up_at_location[2])
else:
self.bot.wake_location = wake_up_at_location
if hasattr(self.bot, 'api'): self.bot.login() # Same here
def _process_config(self, config):
self.entries = []
for entry in config:
prepared = {}
prepared['time'] = datetime.strptime(entry['time'] if 'time' in entry else '01:00', '%H:%M')
# Using datetime for easier stripping of timedeltas
raw_duration = datetime.strptime(entry['duration'] if 'duration' in entry else '07:00', '%H:%M')
duration = int(timedelta(hours=raw_duration.hour, minutes=raw_duration.minute).total_seconds())
raw_time_random_offset = datetime.strptime(entry['time_random_offset'] if 'time_random_offset' in entry else '01:00', '%H:%M')
time_random_offset = int(
timedelta(
hours=raw_time_random_offset.hour, minutes=raw_time_random_offset.minute).total_seconds())
raw_duration_random_offset = datetime.strptime(entry['duration_random_offset'] if 'duration_random_offset' in entry else '00:30', '%H:%M')
duration_random_offset = int(
timedelta(
hours=raw_duration_random_offset.hour, minutes=raw_duration_random_offset.minute).total_seconds())
raw_wake_up_at_location = entry['wake_up_at_location'] if 'wake_up_at_location' in entry else ''
if raw_wake_up_at_location:
try:
wake_up_at_location = raw_wake_up_at_location.split(',',2)
lat=float(wake_up_at_location[0])
lng=float(wake_up_at_location[1])
if len(wake_up_at_location) == 3:
alt=float(wake_up_at_location[2])
else:
alt = uniform(self.bot.config.alt_min, self.bot.config.alt_max)
except ValueError:
raise ValueError('SleepSchedule wake_up_at_location, parsing error in location') #TODO there must be a more elegant way to do it...
prepared['wake_up_at_location'] = [lat, lng, alt]
prepared['duration'] = duration
prepared['time_random_offset'] = time_random_offset
prepared['duration_random_offset'] = duration_random_offset
self.entries.append(prepared)
def _schedule_next_sleep(self):
self._next_sleep, self._next_duration, self._wake_up_at_location = self._get_next_sleep_schedule()
self.bot.event_manager.emit(
'next_sleep',
sender=self,
formatted="Next sleep at {time}",
data={
'time': str(self._next_sleep)
}
)
def _calculate_current_sleep(self):
self._current_sleep = self._next_sleep - timedelta(days=1)
current_duration = self._next_duration
self._current_end = self._current_sleep + timedelta(seconds = current_duration)
def _should_sleep_now(self):
if datetime.now() >= self._next_sleep:
return True
if datetime.now() >= self._current_sleep and datetime.now() < self._current_end:
self._next_duration = (self._current_end - datetime.now()).total_seconds()
return True
return False
def _get_next_sleep_schedule(self):
now = datetime.now() + self.SCHEDULING_MARGIN
times = []
for index in range(len(self.entries)):
next_time = now.replace(hour=self.entries[index]['time'].hour, minute=self.entries[index]['time'].minute)
next_time += timedelta(seconds=self._get_random_offset(self.entries[index]['time_random_offset']))
# If sleep time is passed add one day
if next_time <= now:
next_time += timedelta(days=1)
times.append(next_time)
diffs = {}
for index in range(len(self.entries)):
diff = (times[index]-now).total_seconds()
if diff >= 0: diffs[index] = diff
closest = min(diffs.iterkeys(), key=lambda x: diffs[x])
next_time = times[closest]
next_duration = self._get_next_duration(self.entries[closest])
location = self.entries[closest]['wake_up_at_location'] if 'wake_up_at_location' in self.entries[closest] else ''
return next_time, next_duration, location
def _get_next_duration(self, entry):
duration = entry['duration'] + self._get_random_offset(entry['duration_random_offset'])
return duration
def <|fim_middle|>(self, max_offset):
offset = uniform(-max_offset, max_offset)
return int(offset)
def _sleep(self):
sleep_to_go = self._next_duration
sleep_m, sleep_s = divmod(sleep_to_go, 60)
sleep_h, sleep_m = divmod(sleep_m, 60)
sleep_hms = '%02d:%02d:%02d' % (sleep_h, sleep_m, sleep_s)
now = datetime.now()
wake = str(now + timedelta(seconds=sleep_to_go))
self.bot.event_manager.emit(
'bot_sleep',
sender=self,
formatted="Sleeping for {time_hms}, wake at {wake}",
data={
'time_hms': sleep_hms,
'wake': wake
}
)
while sleep_to_go > 0:
if sleep_to_go < self.LOG_INTERVAL_SECONDS:
sleep(sleep_to_go)
sleep_to_go = 0
else:
sleep(self.LOG_INTERVAL_SECONDS)
sleep_to_go -= self.LOG_INTERVAL_SECONDS
<|fim▁end|> | _get_random_offset |
<|file_name|>sleep_schedule.py<|end_file_name|><|fim▁begin|>from datetime import datetime, timedelta
from time import sleep
from random import uniform
class SleepSchedule(object):
"""Pauses the execution of the bot every day for some time
Simulates the user going to sleep every day for some time, the sleep time
and the duration is changed every day by a random offset defined in the
config file
Example Config:
"sleep_schedule": [
{
"time": "12:00",
"duration": "5:30",
"time_random_offset": "00:30",
"duration_random_offset": "00:30",
"wake_up_at_location": ""
},
{
"time": "17:45",
"duration": "3:00",
"time_random_offset": "01:00",
"duration_random_offset": "00:30",
"wake_up_at_location": ""
}
]
time: (HH:MM) local time that the bot should sleep
duration: (HH:MM) the duration of sleep
time_random_offset: (HH:MM) random offset of time that the sleep will start
for this example the possible start time is 11:30-12:30
duration_random_offset: (HH:MM) random offset of duration of sleep
for this example the possible duration is 5:00-6:00
wake_up_at_location: (lat, long | lat, long, alt | "") the location at which the bot wake up
*Note that an empty string ("") will not change the location*. """
LOG_INTERVAL_SECONDS = 600
SCHEDULING_MARGIN = timedelta(minutes=10) # Skip if next sleep is RESCHEDULING_MARGIN from now
def __init__(self, bot, config):
self.bot = bot
self._process_config(config)
self._schedule_next_sleep()
self._calculate_current_sleep()
def work(self):
if self._should_sleep_now():
self._sleep()
wake_up_at_location = self._wake_up_at_location
self._schedule_next_sleep()
if wake_up_at_location:
if hasattr(self.bot, 'api'): # Check if api is already initialized
self.bot.api.set_position(wake_up_at_location[0],wake_up_at_location[1],wake_up_at_location[2])
else:
self.bot.wake_location = wake_up_at_location
if hasattr(self.bot, 'api'): self.bot.login() # Same here
def _process_config(self, config):
self.entries = []
for entry in config:
prepared = {}
prepared['time'] = datetime.strptime(entry['time'] if 'time' in entry else '01:00', '%H:%M')
# Using datetime for easier stripping of timedeltas
raw_duration = datetime.strptime(entry['duration'] if 'duration' in entry else '07:00', '%H:%M')
duration = int(timedelta(hours=raw_duration.hour, minutes=raw_duration.minute).total_seconds())
raw_time_random_offset = datetime.strptime(entry['time_random_offset'] if 'time_random_offset' in entry else '01:00', '%H:%M')
time_random_offset = int(
timedelta(
hours=raw_time_random_offset.hour, minutes=raw_time_random_offset.minute).total_seconds())
raw_duration_random_offset = datetime.strptime(entry['duration_random_offset'] if 'duration_random_offset' in entry else '00:30', '%H:%M')
duration_random_offset = int(
timedelta(
hours=raw_duration_random_offset.hour, minutes=raw_duration_random_offset.minute).total_seconds())
raw_wake_up_at_location = entry['wake_up_at_location'] if 'wake_up_at_location' in entry else ''
if raw_wake_up_at_location:
try:
wake_up_at_location = raw_wake_up_at_location.split(',',2)
lat=float(wake_up_at_location[0])
lng=float(wake_up_at_location[1])
if len(wake_up_at_location) == 3:
alt=float(wake_up_at_location[2])
else:
alt = uniform(self.bot.config.alt_min, self.bot.config.alt_max)
except ValueError:
raise ValueError('SleepSchedule wake_up_at_location, parsing error in location') #TODO there must be a more elegant way to do it...
prepared['wake_up_at_location'] = [lat, lng, alt]
prepared['duration'] = duration
prepared['time_random_offset'] = time_random_offset
prepared['duration_random_offset'] = duration_random_offset
self.entries.append(prepared)
def _schedule_next_sleep(self):
self._next_sleep, self._next_duration, self._wake_up_at_location = self._get_next_sleep_schedule()
self.bot.event_manager.emit(
'next_sleep',
sender=self,
formatted="Next sleep at {time}",
data={
'time': str(self._next_sleep)
}
)
def _calculate_current_sleep(self):
self._current_sleep = self._next_sleep - timedelta(days=1)
current_duration = self._next_duration
self._current_end = self._current_sleep + timedelta(seconds = current_duration)
def _should_sleep_now(self):
if datetime.now() >= self._next_sleep:
return True
if datetime.now() >= self._current_sleep and datetime.now() < self._current_end:
self._next_duration = (self._current_end - datetime.now()).total_seconds()
return True
return False
def _get_next_sleep_schedule(self):
now = datetime.now() + self.SCHEDULING_MARGIN
times = []
for index in range(len(self.entries)):
next_time = now.replace(hour=self.entries[index]['time'].hour, minute=self.entries[index]['time'].minute)
next_time += timedelta(seconds=self._get_random_offset(self.entries[index]['time_random_offset']))
# If sleep time is passed add one day
if next_time <= now:
next_time += timedelta(days=1)
times.append(next_time)
diffs = {}
for index in range(len(self.entries)):
diff = (times[index]-now).total_seconds()
if diff >= 0: diffs[index] = diff
closest = min(diffs.iterkeys(), key=lambda x: diffs[x])
next_time = times[closest]
next_duration = self._get_next_duration(self.entries[closest])
location = self.entries[closest]['wake_up_at_location'] if 'wake_up_at_location' in self.entries[closest] else ''
return next_time, next_duration, location
def _get_next_duration(self, entry):
duration = entry['duration'] + self._get_random_offset(entry['duration_random_offset'])
return duration
def _get_random_offset(self, max_offset):
offset = uniform(-max_offset, max_offset)
return int(offset)
def <|fim_middle|>(self):
sleep_to_go = self._next_duration
sleep_m, sleep_s = divmod(sleep_to_go, 60)
sleep_h, sleep_m = divmod(sleep_m, 60)
sleep_hms = '%02d:%02d:%02d' % (sleep_h, sleep_m, sleep_s)
now = datetime.now()
wake = str(now + timedelta(seconds=sleep_to_go))
self.bot.event_manager.emit(
'bot_sleep',
sender=self,
formatted="Sleeping for {time_hms}, wake at {wake}",
data={
'time_hms': sleep_hms,
'wake': wake
}
)
while sleep_to_go > 0:
if sleep_to_go < self.LOG_INTERVAL_SECONDS:
sleep(sleep_to_go)
sleep_to_go = 0
else:
sleep(self.LOG_INTERVAL_SECONDS)
sleep_to_go -= self.LOG_INTERVAL_SECONDS
<|fim▁end|> | _sleep |
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def __init__(self):
super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu()
def loadToolbar(self):
"""
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
self.restoreState( QtCore.QByteArray.fromBase64(mwState) )
if mwGeom is not None:
self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) )
else:
self.setGeometry(0, 0, 800, 600)
def loadMenu(self):
"""
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator()
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
continue
if show_disabled_items:
# Show all child items
children = root.children
else:
# Filter out those which are disabled
children = [i for i in root.children if i.enabled]
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
continue
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action)
def onCurrentTabChanged(self, index, tabs=None):
if tabs is None:
tabs = self.tabs
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
signal.emit()
def getTabWidget(self, items):
"""
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
widget = QtGui.QWidget()
widget.setEnabled(False)
return widget
elif count == 1:
# If there is only one item, show it as is.
logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget
else:
# If there are many children, add them in a QTabWidget
tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs
def saveWindowState(self):
"""
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save()
def closeEvent(self, event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
<|fim▁hole|> cls.__inits.append(init)
def callInit(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self)<|fim▁end|> | def addInit(cls, init):
"""
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
|
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
<|fim_middle|>
<|fim▁end|> | __inits = []
def __init__(self):
super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu()
def loadToolbar(self):
"""
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
self.restoreState( QtCore.QByteArray.fromBase64(mwState) )
if mwGeom is not None:
self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) )
else:
self.setGeometry(0, 0, 800, 600)
def loadMenu(self):
"""
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator()
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
continue
if show_disabled_items:
# Show all child items
children = root.children
else:
# Filter out those which are disabled
children = [i for i in root.children if i.enabled]
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
continue
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action)
def onCurrentTabChanged(self, index, tabs=None):
if tabs is None:
tabs = self.tabs
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
signal.emit()
def getTabWidget(self, items):
"""
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
widget = QtGui.QWidget()
widget.setEnabled(False)
return widget
elif count == 1:
# If there is only one item, show it as is.
logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget
else:
# If there are many children, add them in a QTabWidget
tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs
def saveWindowState(self):
"""
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save()
def closeEvent(self, event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
def addInit(cls, init):
"""
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
cls.__inits.append(init)
def callInit(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self) |
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def __init__(self):
<|fim_middle|>
def loadToolbar(self):
"""
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
self.restoreState( QtCore.QByteArray.fromBase64(mwState) )
if mwGeom is not None:
self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) )
else:
self.setGeometry(0, 0, 800, 600)
def loadMenu(self):
"""
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator()
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
continue
if show_disabled_items:
# Show all child items
children = root.children
else:
# Filter out those which are disabled
children = [i for i in root.children if i.enabled]
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
continue
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action)
def onCurrentTabChanged(self, index, tabs=None):
if tabs is None:
tabs = self.tabs
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
signal.emit()
def getTabWidget(self, items):
"""
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
widget = QtGui.QWidget()
widget.setEnabled(False)
return widget
elif count == 1:
# If there is only one item, show it as is.
logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget
else:
# If there are many children, add them in a QTabWidget
tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs
def saveWindowState(self):
"""
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save()
def closeEvent(self, event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
def addInit(cls, init):
"""
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
cls.__inits.append(init)
def callInit(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self)
<|fim▁end|> | super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu() |
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def __init__(self):
super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu()
def loadToolbar(self):
<|fim_middle|>
def loadMenu(self):
"""
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator()
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
continue
if show_disabled_items:
# Show all child items
children = root.children
else:
# Filter out those which are disabled
children = [i for i in root.children if i.enabled]
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
continue
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action)
def onCurrentTabChanged(self, index, tabs=None):
if tabs is None:
tabs = self.tabs
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
signal.emit()
def getTabWidget(self, items):
"""
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
widget = QtGui.QWidget()
widget.setEnabled(False)
return widget
elif count == 1:
# If there is only one item, show it as is.
logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget
else:
# If there are many children, add them in a QTabWidget
tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs
def saveWindowState(self):
"""
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save()
def closeEvent(self, event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
def addInit(cls, init):
"""
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
cls.__inits.append(init)
def callInit(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self)
<|fim▁end|> | """
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
self.restoreState( QtCore.QByteArray.fromBase64(mwState) )
if mwGeom is not None:
self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) )
else:
self.setGeometry(0, 0, 800, 600) |
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def __init__(self):
super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu()
def loadToolbar(self):
"""
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
self.restoreState( QtCore.QByteArray.fromBase64(mwState) )
if mwGeom is not None:
self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) )
else:
self.setGeometry(0, 0, 800, 600)
def loadMenu(self):
<|fim_middle|>
def onCurrentTabChanged(self, index, tabs=None):
if tabs is None:
tabs = self.tabs
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
signal.emit()
def getTabWidget(self, items):
"""
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
widget = QtGui.QWidget()
widget.setEnabled(False)
return widget
elif count == 1:
# If there is only one item, show it as is.
logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget
else:
# If there are many children, add them in a QTabWidget
tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs
def saveWindowState(self):
"""
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save()
def closeEvent(self, event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
def addInit(cls, init):
"""
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
cls.__inits.append(init)
def callInit(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self)
<|fim▁end|> | """
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator()
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
continue
if show_disabled_items:
# Show all child items
children = root.children
else:
# Filter out those which are disabled
children = [i for i in root.children if i.enabled]
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
continue
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action) |
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def __init__(self):
super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu()
def loadToolbar(self):
"""
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
self.restoreState( QtCore.QByteArray.fromBase64(mwState) )
if mwGeom is not None:
self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) )
else:
self.setGeometry(0, 0, 800, 600)
def loadMenu(self):
"""
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator()
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
continue
if show_disabled_items:
# Show all child items
children = root.children
else:
# Filter out those which are disabled
children = [i for i in root.children if i.enabled]
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
continue
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action)
def onCurrentTabChanged(self, index, tabs=None):
<|fim_middle|>
def getTabWidget(self, items):
"""
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
widget = QtGui.QWidget()
widget.setEnabled(False)
return widget
elif count == 1:
# If there is only one item, show it as is.
logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget
else:
# If there are many children, add them in a QTabWidget
tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs
def saveWindowState(self):
"""
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save()
def closeEvent(self, event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
def addInit(cls, init):
"""
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
cls.__inits.append(init)
def callInit(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self)
<|fim▁end|> | if tabs is None:
tabs = self.tabs
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
signal.emit() |
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def __init__(self):
super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu()
def loadToolbar(self):
"""
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
self.restoreState( QtCore.QByteArray.fromBase64(mwState) )
if mwGeom is not None:
self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) )
else:
self.setGeometry(0, 0, 800, 600)
def loadMenu(self):
"""
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator()
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
continue
if show_disabled_items:
# Show all child items
children = root.children
else:
# Filter out those which are disabled
children = [i for i in root.children if i.enabled]
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
continue
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action)
def onCurrentTabChanged(self, index, tabs=None):
if tabs is None:
tabs = self.tabs
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
signal.emit()
def getTabWidget(self, items):
<|fim_middle|>
def saveWindowState(self):
"""
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save()
def closeEvent(self, event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
def addInit(cls, init):
"""
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
cls.__inits.append(init)
def callInit(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self)
<|fim▁end|> | """
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
widget = QtGui.QWidget()
widget.setEnabled(False)
return widget
elif count == 1:
# If there is only one item, show it as is.
logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget
else:
# If there are many children, add them in a QTabWidget
tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs |
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def __init__(self):
super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu()
def loadToolbar(self):
"""
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
self.restoreState( QtCore.QByteArray.fromBase64(mwState) )
if mwGeom is not None:
self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) )
else:
self.setGeometry(0, 0, 800, 600)
def loadMenu(self):
"""
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator()
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
continue
if show_disabled_items:
# Show all child items
children = root.children
else:
# Filter out those which are disabled
children = [i for i in root.children if i.enabled]
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
continue
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action)
def onCurrentTabChanged(self, index, tabs=None):
if tabs is None:
tabs = self.tabs
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
signal.emit()
def getTabWidget(self, items):
"""
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
widget = QtGui.QWidget()
widget.setEnabled(False)
return widget
elif count == 1:
# If there is only one item, show it as is.
logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget
else:
# If there are many children, add them in a QTabWidget
tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs
def saveWindowState(self):
<|fim_middle|>
def closeEvent(self, event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
def addInit(cls, init):
"""
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
cls.__inits.append(init)
def callInit(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self)
<|fim▁end|> | """
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save() |
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def __init__(self):
super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu()
def loadToolbar(self):
"""
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
self.restoreState( QtCore.QByteArray.fromBase64(mwState) )
if mwGeom is not None:
self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) )
else:
self.setGeometry(0, 0, 800, 600)
def loadMenu(self):
"""
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator()
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
continue
if show_disabled_items:
# Show all child items
children = root.children
else:
# Filter out those which are disabled
children = [i for i in root.children if i.enabled]
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
continue
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action)
def onCurrentTabChanged(self, index, tabs=None):
if tabs is None:
tabs = self.tabs
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
signal.emit()
def getTabWidget(self, items):
"""
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
widget = QtGui.QWidget()
widget.setEnabled(False)
return widget
elif count == 1:
# If there is only one item, show it as is.
logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget
else:
# If there are many children, add them in a QTabWidget
tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs
def saveWindowState(self):
"""
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save()
def closeEvent(self, event):
<|fim_middle|>
@classmethod
def addInit(cls, init):
"""
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
cls.__inits.append(init)
def callInit(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self)
<|fim▁end|> | """
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept() |
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def __init__(self):
super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu()
def loadToolbar(self):
"""
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
self.restoreState( QtCore.QByteArray.fromBase64(mwState) )
if mwGeom is not None:
self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) )
else:
self.setGeometry(0, 0, 800, 600)
def loadMenu(self):
"""
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator()
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
continue
if show_disabled_items:
# Show all child items
children = root.children
else:
# Filter out those which are disabled
children = [i for i in root.children if i.enabled]
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
continue
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action)
def onCurrentTabChanged(self, index, tabs=None):
if tabs is None:
tabs = self.tabs
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
signal.emit()
def getTabWidget(self, items):
"""
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
widget = QtGui.QWidget()
widget.setEnabled(False)
return widget
elif count == 1:
# If there is only one item, show it as is.
logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget
else:
# If there are many children, add them in a QTabWidget
tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs
def saveWindowState(self):
"""
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save()
def closeEvent(self, event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
def addInit(cls, init):
<|fim_middle|>
def callInit(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self)
<|fim▁end|> | """
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
cls.__inits.append(init) |
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def __init__(self):
super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu()
def loadToolbar(self):
"""
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
self.restoreState( QtCore.QByteArray.fromBase64(mwState) )
if mwGeom is not None:
self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) )
else:
self.setGeometry(0, 0, 800, 600)
def loadMenu(self):
"""
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator()
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
continue
if show_disabled_items:
# Show all child items
children = root.children
else:
# Filter out those which are disabled
children = [i for i in root.children if i.enabled]
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
continue
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action)
def onCurrentTabChanged(self, index, tabs=None):
if tabs is None:
tabs = self.tabs
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
signal.emit()
def getTabWidget(self, items):
"""
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
widget = QtGui.QWidget()
widget.setEnabled(False)
return widget
elif count == 1:
# If there is only one item, show it as is.
logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget
else:
# If there are many children, add them in a QTabWidget
tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs
def saveWindowState(self):
"""
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save()
def closeEvent(self, event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
def addInit(cls, init):
"""
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
cls.__inits.append(init)
def callInit(self):
<|fim_middle|>
<|fim▁end|> | """
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self) |
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def __init__(self):
super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu()
def loadToolbar(self):
"""
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
<|fim_middle|>
if mwGeom is not None:
self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) )
else:
self.setGeometry(0, 0, 800, 600)
def loadMenu(self):
"""
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator()
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
continue
if show_disabled_items:
# Show all child items
children = root.children
else:
# Filter out those which are disabled
children = [i for i in root.children if i.enabled]
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
continue
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action)
def onCurrentTabChanged(self, index, tabs=None):
if tabs is None:
tabs = self.tabs
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
signal.emit()
def getTabWidget(self, items):
"""
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
widget = QtGui.QWidget()
widget.setEnabled(False)
return widget
elif count == 1:
# If there is only one item, show it as is.
logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget
else:
# If there are many children, add them in a QTabWidget
tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs
def saveWindowState(self):
"""
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save()
def closeEvent(self, event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
def addInit(cls, init):
"""
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
cls.__inits.append(init)
def callInit(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self)
<|fim▁end|> | self.restoreState( QtCore.QByteArray.fromBase64(mwState) ) |
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def __init__(self):
super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu()
def loadToolbar(self):
"""
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
self.restoreState( QtCore.QByteArray.fromBase64(mwState) )
if mwGeom is not None:
<|fim_middle|>
else:
self.setGeometry(0, 0, 800, 600)
def loadMenu(self):
"""
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator()
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
continue
if show_disabled_items:
# Show all child items
children = root.children
else:
# Filter out those which are disabled
children = [i for i in root.children if i.enabled]
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
continue
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action)
def onCurrentTabChanged(self, index, tabs=None):
if tabs is None:
tabs = self.tabs
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
signal.emit()
def getTabWidget(self, items):
"""
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
widget = QtGui.QWidget()
widget.setEnabled(False)
return widget
elif count == 1:
# If there is only one item, show it as is.
logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget
else:
# If there are many children, add them in a QTabWidget
tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs
def saveWindowState(self):
"""
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save()
def closeEvent(self, event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
def addInit(cls, init):
"""
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
cls.__inits.append(init)
def callInit(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self)
<|fim▁end|> | self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) ) |
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def __init__(self):
super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu()
def loadToolbar(self):
"""
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
self.restoreState( QtCore.QByteArray.fromBase64(mwState) )
if mwGeom is not None:
self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) )
else:
<|fim_middle|>
def loadMenu(self):
"""
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator()
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
continue
if show_disabled_items:
# Show all child items
children = root.children
else:
# Filter out those which are disabled
children = [i for i in root.children if i.enabled]
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
continue
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action)
def onCurrentTabChanged(self, index, tabs=None):
if tabs is None:
tabs = self.tabs
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
signal.emit()
def getTabWidget(self, items):
"""
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
widget = QtGui.QWidget()
widget.setEnabled(False)
return widget
elif count == 1:
# If there is only one item, show it as is.
logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget
else:
# If there are many children, add them in a QTabWidget
tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs
def saveWindowState(self):
"""
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save()
def closeEvent(self, event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
def addInit(cls, init):
"""
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
cls.__inits.append(init)
def callInit(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self)
<|fim▁end|> | self.setGeometry(0, 0, 800, 600) |
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def __init__(self):
super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu()
def loadToolbar(self):
"""
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
self.restoreState( QtCore.QByteArray.fromBase64(mwState) )
if mwGeom is not None:
self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) )
else:
self.setGeometry(0, 0, 800, 600)
def loadMenu(self):
"""
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
<|fim_middle|>
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
continue
if show_disabled_items:
# Show all child items
children = root.children
else:
# Filter out those which are disabled
children = [i for i in root.children if i.enabled]
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
continue
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action)
def onCurrentTabChanged(self, index, tabs=None):
if tabs is None:
tabs = self.tabs
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
signal.emit()
def getTabWidget(self, items):
"""
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
widget = QtGui.QWidget()
widget.setEnabled(False)
return widget
elif count == 1:
# If there is only one item, show it as is.
logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget
else:
# If there are many children, add them in a QTabWidget
tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs
def saveWindowState(self):
"""
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save()
def closeEvent(self, event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
def addInit(cls, init):
"""
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
cls.__inits.append(init)
def callInit(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self)
<|fim▁end|> | self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator() |
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def __init__(self):
super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu()
def loadToolbar(self):
"""
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
self.restoreState( QtCore.QByteArray.fromBase64(mwState) )
if mwGeom is not None:
self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) )
else:
self.setGeometry(0, 0, 800, 600)
def loadMenu(self):
"""
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator()
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
<|fim_middle|>
if show_disabled_items:
# Show all child items
children = root.children
else:
# Filter out those which are disabled
children = [i for i in root.children if i.enabled]
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
continue
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action)
def onCurrentTabChanged(self, index, tabs=None):
if tabs is None:
tabs = self.tabs
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
signal.emit()
def getTabWidget(self, items):
"""
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
widget = QtGui.QWidget()
widget.setEnabled(False)
return widget
elif count == 1:
# If there is only one item, show it as is.
logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget
else:
# If there are many children, add them in a QTabWidget
tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs
def saveWindowState(self):
"""
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save()
def closeEvent(self, event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
def addInit(cls, init):
"""
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
cls.__inits.append(init)
def callInit(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self)
<|fim▁end|> | continue |
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def __init__(self):
super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu()
def loadToolbar(self):
"""
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
self.restoreState( QtCore.QByteArray.fromBase64(mwState) )
if mwGeom is not None:
self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) )
else:
self.setGeometry(0, 0, 800, 600)
def loadMenu(self):
"""
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator()
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
continue
if show_disabled_items:
# Show all child items
<|fim_middle|>
else:
# Filter out those which are disabled
children = [i for i in root.children if i.enabled]
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
continue
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action)
def onCurrentTabChanged(self, index, tabs=None):
if tabs is None:
tabs = self.tabs
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
signal.emit()
def getTabWidget(self, items):
"""
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
widget = QtGui.QWidget()
widget.setEnabled(False)
return widget
elif count == 1:
# If there is only one item, show it as is.
logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget
else:
# If there are many children, add them in a QTabWidget
tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs
def saveWindowState(self):
"""
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save()
def closeEvent(self, event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
def addInit(cls, init):
"""
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
cls.__inits.append(init)
def callInit(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self)
<|fim▁end|> | children = root.children |
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def __init__(self):
super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu()
def loadToolbar(self):
"""
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
self.restoreState( QtCore.QByteArray.fromBase64(mwState) )
if mwGeom is not None:
self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) )
else:
self.setGeometry(0, 0, 800, 600)
def loadMenu(self):
"""
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator()
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
continue
if show_disabled_items:
# Show all child items
children = root.children
else:
# Filter out those which are disabled
<|fim_middle|>
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
continue
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action)
def onCurrentTabChanged(self, index, tabs=None):
if tabs is None:
tabs = self.tabs
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
signal.emit()
def getTabWidget(self, items):
"""
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
widget = QtGui.QWidget()
widget.setEnabled(False)
return widget
elif count == 1:
# If there is only one item, show it as is.
logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget
else:
# If there are many children, add them in a QTabWidget
tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs
def saveWindowState(self):
"""
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save()
def closeEvent(self, event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
def addInit(cls, init):
"""
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
cls.__inits.append(init)
def callInit(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self)
<|fim▁end|> | children = [i for i in root.children if i.enabled] |
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def __init__(self):
super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu()
def loadToolbar(self):
"""
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
self.restoreState( QtCore.QByteArray.fromBase64(mwState) )
if mwGeom is not None:
self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) )
else:
self.setGeometry(0, 0, 800, 600)
def loadMenu(self):
"""
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator()
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
continue
if show_disabled_items:
# Show all child items
children = root.children
else:
# Filter out those which are disabled
children = [i for i in root.children if i.enabled]
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
<|fim_middle|>
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action)
def onCurrentTabChanged(self, index, tabs=None):
if tabs is None:
tabs = self.tabs
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
signal.emit()
def getTabWidget(self, items):
"""
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
widget = QtGui.QWidget()
widget.setEnabled(False)
return widget
elif count == 1:
# If there is only one item, show it as is.
logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget
else:
# If there are many children, add them in a QTabWidget
tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs
def saveWindowState(self):
"""
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save()
def closeEvent(self, event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
def addInit(cls, init):
"""
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
cls.__inits.append(init)
def callInit(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self)
<|fim▁end|> | continue |
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def __init__(self):
super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu()
def loadToolbar(self):
"""
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
self.restoreState( QtCore.QByteArray.fromBase64(mwState) )
if mwGeom is not None:
self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) )
else:
self.setGeometry(0, 0, 800, 600)
def loadMenu(self):
"""
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator()
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
continue
if show_disabled_items:
# Show all child items
children = root.children
else:
# Filter out those which are disabled
children = [i for i in root.children if i.enabled]
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
continue
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
<|fim_middle|>
def onCurrentTabChanged(self, index, tabs=None):
if tabs is None:
tabs = self.tabs
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
signal.emit()
def getTabWidget(self, items):
"""
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
widget = QtGui.QWidget()
widget.setEnabled(False)
return widget
elif count == 1:
# If there is only one item, show it as is.
logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget
else:
# If there are many children, add them in a QTabWidget
tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs
def saveWindowState(self):
"""
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save()
def closeEvent(self, event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
def addInit(cls, init):
"""
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
cls.__inits.append(init)
def callInit(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self)
<|fim▁end|> | action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action) |
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def __init__(self):
super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu()
def loadToolbar(self):
"""
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
self.restoreState( QtCore.QByteArray.fromBase64(mwState) )
if mwGeom is not None:
self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) )
else:
self.setGeometry(0, 0, 800, 600)
def loadMenu(self):
"""
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator()
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
continue
if show_disabled_items:
# Show all child items
children = root.children
else:
# Filter out those which are disabled
children = [i for i in root.children if i.enabled]
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
continue
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action)
def onCurrentTabChanged(self, index, tabs=None):
if tabs is None:
<|fim_middle|>
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
signal.emit()
def getTabWidget(self, items):
"""
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
widget = QtGui.QWidget()
widget.setEnabled(False)
return widget
elif count == 1:
# If there is only one item, show it as is.
logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget
else:
# If there are many children, add them in a QTabWidget
tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs
def saveWindowState(self):
"""
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save()
def closeEvent(self, event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
def addInit(cls, init):
"""
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
cls.__inits.append(init)
def callInit(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self)
<|fim▁end|> | tabs = self.tabs |
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def __init__(self):
super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu()
def loadToolbar(self):
"""
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
self.restoreState( QtCore.QByteArray.fromBase64(mwState) )
if mwGeom is not None:
self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) )
else:
self.setGeometry(0, 0, 800, 600)
def loadMenu(self):
"""
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator()
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
continue
if show_disabled_items:
# Show all child items
children = root.children
else:
# Filter out those which are disabled
children = [i for i in root.children if i.enabled]
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
continue
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action)
def onCurrentTabChanged(self, index, tabs=None):
if tabs is None:
tabs = self.tabs
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
<|fim_middle|>
def getTabWidget(self, items):
"""
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
widget = QtGui.QWidget()
widget.setEnabled(False)
return widget
elif count == 1:
# If there is only one item, show it as is.
logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget
else:
# If there are many children, add them in a QTabWidget
tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs
def saveWindowState(self):
"""
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save()
def closeEvent(self, event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
def addInit(cls, init):
"""
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
cls.__inits.append(init)
def callInit(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self)
<|fim▁end|> | signal.emit() |
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def __init__(self):
super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu()
def loadToolbar(self):
"""
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
self.restoreState( QtCore.QByteArray.fromBase64(mwState) )
if mwGeom is not None:
self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) )
else:
self.setGeometry(0, 0, 800, 600)
def loadMenu(self):
"""
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator()
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
continue
if show_disabled_items:
# Show all child items
children = root.children
else:
# Filter out those which are disabled
children = [i for i in root.children if i.enabled]
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
continue
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action)
def onCurrentTabChanged(self, index, tabs=None):
if tabs is None:
tabs = self.tabs
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
signal.emit()
def getTabWidget(self, items):
"""
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
<|fim_middle|>
elif count == 1:
# If there is only one item, show it as is.
logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget
else:
# If there are many children, add them in a QTabWidget
tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs
def saveWindowState(self):
"""
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save()
def closeEvent(self, event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
def addInit(cls, init):
"""
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
cls.__inits.append(init)
def callInit(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self)
<|fim▁end|> | widget = QtGui.QWidget()
widget.setEnabled(False)
return widget |
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def __init__(self):
super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu()
def loadToolbar(self):
"""
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
self.restoreState( QtCore.QByteArray.fromBase64(mwState) )
if mwGeom is not None:
self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) )
else:
self.setGeometry(0, 0, 800, 600)
def loadMenu(self):
"""
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator()
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
continue
if show_disabled_items:
# Show all child items
children = root.children
else:
# Filter out those which are disabled
children = [i for i in root.children if i.enabled]
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
continue
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action)
def onCurrentTabChanged(self, index, tabs=None):
if tabs is None:
tabs = self.tabs
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
signal.emit()
def getTabWidget(self, items):
"""
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
widget = QtGui.QWidget()
widget.setEnabled(False)
return widget
elif count == 1:
# If there is only one item, show it as is.
<|fim_middle|>
else:
# If there are many children, add them in a QTabWidget
tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs
def saveWindowState(self):
"""
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save()
def closeEvent(self, event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
def addInit(cls, init):
"""
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
cls.__inits.append(init)
def callInit(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self)
<|fim▁end|> | logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget |
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def __init__(self):
super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu()
def loadToolbar(self):
"""
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
self.restoreState( QtCore.QByteArray.fromBase64(mwState) )
if mwGeom is not None:
self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) )
else:
self.setGeometry(0, 0, 800, 600)
def loadMenu(self):
"""
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator()
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
continue
if show_disabled_items:
# Show all child items
children = root.children
else:
# Filter out those which are disabled
children = [i for i in root.children if i.enabled]
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
continue
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action)
def onCurrentTabChanged(self, index, tabs=None):
if tabs is None:
tabs = self.tabs
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
signal.emit()
def getTabWidget(self, items):
"""
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
widget = QtGui.QWidget()
widget.setEnabled(False)
return widget
elif count == 1:
# If there is only one item, show it as is.
logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget
else:
# If there are many children, add them in a QTabWidget
<|fim_middle|>
def saveWindowState(self):
"""
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save()
def closeEvent(self, event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
def addInit(cls, init):
"""
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
cls.__inits.append(init)
def callInit(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self)
<|fim▁end|> | tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs |
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def <|fim_middle|>(self):
super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu()
def loadToolbar(self):
"""
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
self.restoreState( QtCore.QByteArray.fromBase64(mwState) )
if mwGeom is not None:
self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) )
else:
self.setGeometry(0, 0, 800, 600)
def loadMenu(self):
"""
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator()
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
continue
if show_disabled_items:
# Show all child items
children = root.children
else:
# Filter out those which are disabled
children = [i for i in root.children if i.enabled]
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
continue
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action)
def onCurrentTabChanged(self, index, tabs=None):
if tabs is None:
tabs = self.tabs
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
signal.emit()
def getTabWidget(self, items):
"""
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
widget = QtGui.QWidget()
widget.setEnabled(False)
return widget
elif count == 1:
# If there is only one item, show it as is.
logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget
else:
# If there are many children, add them in a QTabWidget
tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs
def saveWindowState(self):
"""
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save()
def closeEvent(self, event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
def addInit(cls, init):
"""
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
cls.__inits.append(init)
def callInit(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self)
<|fim▁end|> | __init__ |
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def __init__(self):
super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu()
def <|fim_middle|>(self):
"""
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
self.restoreState( QtCore.QByteArray.fromBase64(mwState) )
if mwGeom is not None:
self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) )
else:
self.setGeometry(0, 0, 800, 600)
def loadMenu(self):
"""
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator()
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
continue
if show_disabled_items:
# Show all child items
children = root.children
else:
# Filter out those which are disabled
children = [i for i in root.children if i.enabled]
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
continue
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action)
def onCurrentTabChanged(self, index, tabs=None):
if tabs is None:
tabs = self.tabs
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
signal.emit()
def getTabWidget(self, items):
"""
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
widget = QtGui.QWidget()
widget.setEnabled(False)
return widget
elif count == 1:
# If there is only one item, show it as is.
logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget
else:
# If there are many children, add them in a QTabWidget
tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs
def saveWindowState(self):
"""
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save()
def closeEvent(self, event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
def addInit(cls, init):
"""
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
cls.__inits.append(init)
def callInit(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self)
<|fim▁end|> | loadToolbar |
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def __init__(self):
super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu()
def loadToolbar(self):
"""
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
self.restoreState( QtCore.QByteArray.fromBase64(mwState) )
if mwGeom is not None:
self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) )
else:
self.setGeometry(0, 0, 800, 600)
def <|fim_middle|>(self):
"""
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator()
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
continue
if show_disabled_items:
# Show all child items
children = root.children
else:
# Filter out those which are disabled
children = [i for i in root.children if i.enabled]
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
continue
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action)
def onCurrentTabChanged(self, index, tabs=None):
if tabs is None:
tabs = self.tabs
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
signal.emit()
def getTabWidget(self, items):
"""
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
widget = QtGui.QWidget()
widget.setEnabled(False)
return widget
elif count == 1:
# If there is only one item, show it as is.
logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget
else:
# If there are many children, add them in a QTabWidget
tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs
def saveWindowState(self):
"""
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save()
def closeEvent(self, event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
def addInit(cls, init):
"""
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
cls.__inits.append(init)
def callInit(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self)
<|fim▁end|> | loadMenu |
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def __init__(self):
super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu()
def loadToolbar(self):
"""
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
self.restoreState( QtCore.QByteArray.fromBase64(mwState) )
if mwGeom is not None:
self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) )
else:
self.setGeometry(0, 0, 800, 600)
def loadMenu(self):
"""
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator()
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
continue
if show_disabled_items:
# Show all child items
children = root.children
else:
# Filter out those which are disabled
children = [i for i in root.children if i.enabled]
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
continue
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action)
def <|fim_middle|>(self, index, tabs=None):
if tabs is None:
tabs = self.tabs
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
signal.emit()
def getTabWidget(self, items):
"""
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
widget = QtGui.QWidget()
widget.setEnabled(False)
return widget
elif count == 1:
# If there is only one item, show it as is.
logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget
else:
# If there are many children, add them in a QTabWidget
tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs
def saveWindowState(self):
"""
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save()
def closeEvent(self, event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
def addInit(cls, init):
"""
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
cls.__inits.append(init)
def callInit(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self)
<|fim▁end|> | onCurrentTabChanged |
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def __init__(self):
super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu()
def loadToolbar(self):
"""
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
self.restoreState( QtCore.QByteArray.fromBase64(mwState) )
if mwGeom is not None:
self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) )
else:
self.setGeometry(0, 0, 800, 600)
def loadMenu(self):
"""
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator()
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
continue
if show_disabled_items:
# Show all child items
children = root.children
else:
# Filter out those which are disabled
children = [i for i in root.children if i.enabled]
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
continue
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action)
def onCurrentTabChanged(self, index, tabs=None):
if tabs is None:
tabs = self.tabs
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
signal.emit()
def <|fim_middle|>(self, items):
"""
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
widget = QtGui.QWidget()
widget.setEnabled(False)
return widget
elif count == 1:
# If there is only one item, show it as is.
logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget
else:
# If there are many children, add them in a QTabWidget
tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs
def saveWindowState(self):
"""
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save()
def closeEvent(self, event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
def addInit(cls, init):
"""
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
cls.__inits.append(init)
def callInit(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self)
<|fim▁end|> | getTabWidget |
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def __init__(self):
super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu()
def loadToolbar(self):
"""
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
self.restoreState( QtCore.QByteArray.fromBase64(mwState) )
if mwGeom is not None:
self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) )
else:
self.setGeometry(0, 0, 800, 600)
def loadMenu(self):
"""
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator()
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
continue
if show_disabled_items:
# Show all child items
children = root.children
else:
# Filter out those which are disabled
children = [i for i in root.children if i.enabled]
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
continue
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action)
def onCurrentTabChanged(self, index, tabs=None):
if tabs is None:
tabs = self.tabs
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
signal.emit()
def getTabWidget(self, items):
"""
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
widget = QtGui.QWidget()
widget.setEnabled(False)
return widget
elif count == 1:
# If there is only one item, show it as is.
logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget
else:
# If there are many children, add them in a QTabWidget
tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs
def <|fim_middle|>(self):
"""
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save()
def closeEvent(self, event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
def addInit(cls, init):
"""
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
cls.__inits.append(init)
def callInit(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self)
<|fim▁end|> | saveWindowState |
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def __init__(self):
super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu()
def loadToolbar(self):
"""
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
self.restoreState( QtCore.QByteArray.fromBase64(mwState) )
if mwGeom is not None:
self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) )
else:
self.setGeometry(0, 0, 800, 600)
def loadMenu(self):
"""
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator()
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
continue
if show_disabled_items:
# Show all child items
children = root.children
else:
# Filter out those which are disabled
children = [i for i in root.children if i.enabled]
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
continue
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action)
def onCurrentTabChanged(self, index, tabs=None):
if tabs is None:
tabs = self.tabs
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
signal.emit()
def getTabWidget(self, items):
"""
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
widget = QtGui.QWidget()
widget.setEnabled(False)
return widget
elif count == 1:
# If there is only one item, show it as is.
logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget
else:
# If there are many children, add them in a QTabWidget
tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs
def saveWindowState(self):
"""
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save()
def <|fim_middle|>(self, event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
def addInit(cls, init):
"""
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
cls.__inits.append(init)
def callInit(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self)
<|fim▁end|> | closeEvent |
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def __init__(self):
super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu()
def loadToolbar(self):
"""
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
self.restoreState( QtCore.QByteArray.fromBase64(mwState) )
if mwGeom is not None:
self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) )
else:
self.setGeometry(0, 0, 800, 600)
def loadMenu(self):
"""
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator()
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
continue
if show_disabled_items:
# Show all child items
children = root.children
else:
# Filter out those which are disabled
children = [i for i in root.children if i.enabled]
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
continue
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action)
def onCurrentTabChanged(self, index, tabs=None):
if tabs is None:
tabs = self.tabs
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
signal.emit()
def getTabWidget(self, items):
"""
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
widget = QtGui.QWidget()
widget.setEnabled(False)
return widget
elif count == 1:
# If there is only one item, show it as is.
logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget
else:
# If there are many children, add them in a QTabWidget
tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs
def saveWindowState(self):
"""
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save()
def closeEvent(self, event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
def <|fim_middle|>(cls, init):
"""
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
cls.__inits.append(init)
def callInit(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self)
<|fim▁end|> | addInit |
<|file_name|>window.py<|end_file_name|><|fim▁begin|>from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def __init__(self):
super(MainWindow, self).__init__()
self.tabs = QtGui.QTabWidget(self)
self.tabs.setTabsClosable(False)
self.tabs.setIconSize(QtCore.QSize(32, 32))
self.tabs.currentChanged.connect(self.onCurrentTabChanged)
self.toolbar = self.addToolBar('Base')
self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens
self.toolbar.setObjectName('BaseToolbar')
toolbarStyle = cbpos.config['menu', 'toolbar_style']
# The index in this list is the same as that in the configuration page
available_styles = (
QtCore.Qt.ToolButtonFollowStyle,
QtCore.Qt.ToolButtonIconOnly,
QtCore.Qt.ToolButtonTextOnly,
QtCore.Qt.ToolButtonTextBesideIcon,
QtCore.Qt.ToolButtonTextUnderIcon,
)
try:
toolbarStyle = available_styles[int(toolbarStyle)]
except (ValueError, TypeError, IndexError):
toolbarStyle = QtCore.Qt.ToolButtonFollowStyle
self.toolbar.setToolButtonStyle(toolbarStyle)
self.setCentralWidget(self.tabs)
self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.'))
self.setWindowTitle('Coinbox')
self.callInit()
self.loadToolbar()
self.loadMenu()
def loadToolbar(self):
"""
Loads the toolbar actions, restore toolbar state, and restore window geometry.
"""
mwState = cbpos.config['mainwindow', 'state']
mwGeom = cbpos.config['mainwindow', 'geometry']
for act in cbpos.menu.actions:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self)
action.setShortcut(act.shortcut)
action.triggered.connect(act.trigger)
self.toolbar.addAction(action)
#Restores the saved mainwindow's toolbars and docks, and then the window geometry.
if mwState is not None:
self.restoreState( QtCore.QByteArray.fromBase64(mwState) )
if mwGeom is not None:
self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) )
else:
self.setGeometry(0, 0, 800, 600)
def loadMenu(self):
"""
Load the menu root items and items into the QTabWidget with the appropriate pages.
"""
show_empty_root_items = cbpos.config['menu', 'show_empty_root_items']
show_disabled_items = cbpos.config['menu', 'show_disabled_items']
hide_tab_bar = not cbpos.config['menu', 'show_tab_bar']
if hide_tab_bar:
# Hide the tab bar and prepare the toolbar for extra QAction's
self.tabs.tabBar().hide()
# This pre-supposes that the menu items will come after the actions
self.toolbar.addSeparator()
for root in cbpos.menu.items:
if not root.enabled and not show_disabled_items:
continue
if show_disabled_items:
# Show all child items
children = root.children
else:
# Filter out those which are disabled
children = [i for i in root.children if i.enabled]
# Hide empty menu root items
if len(children) == 0 and not show_empty_root_items:
continue
# Add the tab
widget = self.getTabWidget(children)
icon = QtGui.QIcon(root.icon)
index = self.tabs.addTab(widget, icon, root.label)
widget.setEnabled(root.enabled)
# Add the toolbar action if enabled
if hide_tab_bar:
# TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens)
action = QtGui.QAction(QtGui.QIcon(icon), root.label, self)
action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n)
action.triggered.connect(action.onTrigger)
self.toolbar.addAction(action)
def onCurrentTabChanged(self, index, tabs=None):
if tabs is None:
tabs = self.tabs
widget = tabs.widget(index)
try:
signal = widget.shown
except AttributeError:
pass
else:
signal.emit()
def getTabWidget(self, items):
"""
Returns the appropriate window to be placed in the main QTabWidget,
depending on the number of children of a root menu item.
"""
count = len(items)
if count == 0:
# If there are no child items, just return an empty widget
widget = QtGui.QWidget()
widget.setEnabled(False)
return widget
elif count == 1:
# If there is only one item, show it as is.
logger.debug('Loading menu page for %s', items[0].name)
widget = items[0].page()
widget.setEnabled(items[0].enabled)
return widget
else:
# If there are many children, add them in a QTabWidget
tabs = QtGui.QTabWidget()
tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t))
for item in items:
logger.debug('Loading menu page for %s', item.name)
widget = item.page()
icon = QtGui.QIcon(item.icon)
tabs.addTab(widget, icon, item.label)
widget.setEnabled(item.enabled)
return tabs
def saveWindowState(self):
"""
Saves the main window state (position, size, toolbar positions)
"""
mwState = self.saveState().toBase64()
mwGeom = self.saveGeometry().toBase64()
cbpos.config['mainwindow', 'state'] = unicode(mwState)
cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom)
cbpos.config.save()
def closeEvent(self, event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
def addInit(cls, init):
"""
Adds the `init` method to the list of extensions of the `MainWindow.__init__`.
"""
cls.__inits.append(init)
def <|fim_middle|>(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self)
<|fim▁end|> | callInit |
<|file_name|>settings.py<|end_file_name|><|fim▁begin|>"""
Django settings for apps project.
Generated by 'django-admin startproject' using Django 1.9.7.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
from local_settings import SECRET_KEY, DATABASES, DEBUG
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/
SECRET_KEY = SECRET_KEY
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = DEBUG
ALLOWED_HOSTS = [
'learningdjango.in',
'localhost',
'127.0.0.1'
]
# Application definition
INSTALLED_APPS = [
'home.apps.HomeConfig',
'polls.apps.PollsConfig',
'blog.apps.BlogConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'apps.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'apps.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = DATABASES
# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Kolkata'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# Media Files
MEDIA_URL = '/media/'<|fim▁hole|><|fim▁end|> | MEDIA_ROOT = os.path.join(BASE_DIR, 'media') |
<|file_name|>pyunit_link_functions_tweedie_basicGLM.py<|end_file_name|><|fim▁begin|>import sys
sys.path.insert(1, "../../../")
import h2o
def link_functions_tweedie_basic(ip,port):
# Connect to h2o
h2o.init(ip,port)
print "Read in prostate data."
hdf = h2o.upload_file(h2o.locate("smalldata/prostate/prostate_complete.csv.zip"))
print "Testing for family: TWEEDIE"
print "Set variables for h2o."
y = "CAPSULE"
x = ["AGE","RACE","DCAPS","PSA","VOL","DPROS","GLEASON"]
print "Create models with canonical link: TWEEDIE"<|fim▁hole|> print "Compare model deviances for link function tweedie (using precomputed values from R)"
deviance_h2o_tweedie = model_h2o_tweedie.residual_deviance() / model_h2o_tweedie.null_deviance()
assert 0.721452 - deviance_h2o_tweedie <= 0.01, "h2o's residual/null deviance is more than 0.01 lower than R's. h2o: " \
"{0}, r: {1}".format(deviance_h2o_tweedie, 0.721452)
if __name__ == "__main__":
h2o.run_test(sys.argv, link_functions_tweedie_basic)<|fim▁end|> | model_h2o_tweedie = h2o.glm(x=hdf[x], y=hdf[y], family="tweedie", link="tweedie", alpha=[0.5], Lambda = [0])
|
<|file_name|>pyunit_link_functions_tweedie_basicGLM.py<|end_file_name|><|fim▁begin|>import sys
sys.path.insert(1, "../../../")
import h2o
def link_functions_tweedie_basic(ip,port):
# Connect to h2o
<|fim_middle|>
if __name__ == "__main__":
h2o.run_test(sys.argv, link_functions_tweedie_basic)
<|fim▁end|> | h2o.init(ip,port)
print "Read in prostate data."
hdf = h2o.upload_file(h2o.locate("smalldata/prostate/prostate_complete.csv.zip"))
print "Testing for family: TWEEDIE"
print "Set variables for h2o."
y = "CAPSULE"
x = ["AGE","RACE","DCAPS","PSA","VOL","DPROS","GLEASON"]
print "Create models with canonical link: TWEEDIE"
model_h2o_tweedie = h2o.glm(x=hdf[x], y=hdf[y], family="tweedie", link="tweedie", alpha=[0.5], Lambda = [0])
print "Compare model deviances for link function tweedie (using precomputed values from R)"
deviance_h2o_tweedie = model_h2o_tweedie.residual_deviance() / model_h2o_tweedie.null_deviance()
assert 0.721452 - deviance_h2o_tweedie <= 0.01, "h2o's residual/null deviance is more than 0.01 lower than R's. h2o: " \
"{0}, r: {1}".format(deviance_h2o_tweedie, 0.721452) |
<|file_name|>pyunit_link_functions_tweedie_basicGLM.py<|end_file_name|><|fim▁begin|>import sys
sys.path.insert(1, "../../../")
import h2o
def link_functions_tweedie_basic(ip,port):
# Connect to h2o
h2o.init(ip,port)
print "Read in prostate data."
hdf = h2o.upload_file(h2o.locate("smalldata/prostate/prostate_complete.csv.zip"))
print "Testing for family: TWEEDIE"
print "Set variables for h2o."
y = "CAPSULE"
x = ["AGE","RACE","DCAPS","PSA","VOL","DPROS","GLEASON"]
print "Create models with canonical link: TWEEDIE"
model_h2o_tweedie = h2o.glm(x=hdf[x], y=hdf[y], family="tweedie", link="tweedie", alpha=[0.5], Lambda = [0])
print "Compare model deviances for link function tweedie (using precomputed values from R)"
deviance_h2o_tweedie = model_h2o_tweedie.residual_deviance() / model_h2o_tweedie.null_deviance()
assert 0.721452 - deviance_h2o_tweedie <= 0.01, "h2o's residual/null deviance is more than 0.01 lower than R's. h2o: " \
"{0}, r: {1}".format(deviance_h2o_tweedie, 0.721452)
if __name__ == "__main__":
<|fim_middle|>
<|fim▁end|> | h2o.run_test(sys.argv, link_functions_tweedie_basic) |
<|file_name|>pyunit_link_functions_tweedie_basicGLM.py<|end_file_name|><|fim▁begin|>import sys
sys.path.insert(1, "../../../")
import h2o
def <|fim_middle|>(ip,port):
# Connect to h2o
h2o.init(ip,port)
print "Read in prostate data."
hdf = h2o.upload_file(h2o.locate("smalldata/prostate/prostate_complete.csv.zip"))
print "Testing for family: TWEEDIE"
print "Set variables for h2o."
y = "CAPSULE"
x = ["AGE","RACE","DCAPS","PSA","VOL","DPROS","GLEASON"]
print "Create models with canonical link: TWEEDIE"
model_h2o_tweedie = h2o.glm(x=hdf[x], y=hdf[y], family="tweedie", link="tweedie", alpha=[0.5], Lambda = [0])
print "Compare model deviances for link function tweedie (using precomputed values from R)"
deviance_h2o_tweedie = model_h2o_tweedie.residual_deviance() / model_h2o_tweedie.null_deviance()
assert 0.721452 - deviance_h2o_tweedie <= 0.01, "h2o's residual/null deviance is more than 0.01 lower than R's. h2o: " \
"{0}, r: {1}".format(deviance_h2o_tweedie, 0.721452)
if __name__ == "__main__":
h2o.run_test(sys.argv, link_functions_tweedie_basic)
<|fim▁end|> | link_functions_tweedie_basic |
<|file_name|>addUser.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
#
#
# This file is part of librix-thinclient.
#
# librix-thinclient is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# librix-thinclient is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
#
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with librix-thinclient. If not, see <http://www.gnu.org/licenses/>.
import os
from PyQt4 import QtGui
from ltmt.ui.users.add_user.Ui_addUser import Ui_AddUser
class AddUser(QtGui.QDialog):
"""This class provides a add user dialog feature to users page of LTMT"""
def __init__(self, configparser, parent=None):
"""Init method
@param self A AddUser instance
@param parent Parent QtGui.QWidget object
"""
self.configparser = configparser
self.parent = parent
QtGui.QDialog.__init__(self)
self.ui = Ui_AddUser()
self.ui.setupUi(self)
self.parseDefaults()
self.ui.detailsWid.hide()
def parseDefaults(self):
"""Parse some default values for new user accounts
@param self A AddUser instance
"""
with open("/etc/default/useradd", 'r') as ua:
for l in ua:
L = l.strip().split('=')
if len(L) >= 2:
if L[0] == "GROUP":
self.group = L[1]
elif L[0] == "HOME":
self.home = L[1]
elif L[0] == "SHELL":
self.shell = L[1]
def userChanged(self, username):
"""Slot called when user name was changed, updating entries
@param self A AddUser instance
@param username String username
"""
self.ui.initGLine.setText(self.group)
self.ui.homeLine.setText(os.path.join(self.home, username))
self.ui.shellLine.setText(self.shell)
def accept(self):
"""Reimplemented method QtGui.QDialog.accept
Add user to configparser before accept dialog
@param self A AddUser instance
"""
user = self.ui.nameLine.text()
print("__accepted__", user)
if user in self.configparser.getUsersList():<|fim▁hole|> .format(user), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
QtGui.QMessageBox.No) == QtGui.QMessageBox.Yes:
self.configparser.delUser(user)
else:
return
self.configparser.addUser(user)
if self.ui.syncCheck.isChecked():
self.configparser.setUserSync(user, passwd=self.ui.pwLine.text(),
uid=self.ui.uidSpin.text(), init_group=self.ui.initGLine.text(),
groups=[g.strip() for g in self.ui.groupsLine.text().split(',')],
home=self.ui.homeLine.text(), shell=self.ui.shellLine.text())
QtGui.QDialog.accept(self)<|fim▁end|> | if QtGui.QMessageBox.warning(self, self.tr("Replace User"),
self.tr("Are you sure you want to overwrite \"{0}\" user?")\ |
<|file_name|>addUser.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
#
#
# This file is part of librix-thinclient.
#
# librix-thinclient is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# librix-thinclient is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
#
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with librix-thinclient. If not, see <http://www.gnu.org/licenses/>.
import os
from PyQt4 import QtGui
from ltmt.ui.users.add_user.Ui_addUser import Ui_AddUser
class AddUser(QtGui.QDialog):
<|fim_middle|>
<|fim▁end|> | """This class provides a add user dialog feature to users page of LTMT"""
def __init__(self, configparser, parent=None):
"""Init method
@param self A AddUser instance
@param parent Parent QtGui.QWidget object
"""
self.configparser = configparser
self.parent = parent
QtGui.QDialog.__init__(self)
self.ui = Ui_AddUser()
self.ui.setupUi(self)
self.parseDefaults()
self.ui.detailsWid.hide()
def parseDefaults(self):
"""Parse some default values for new user accounts
@param self A AddUser instance
"""
with open("/etc/default/useradd", 'r') as ua:
for l in ua:
L = l.strip().split('=')
if len(L) >= 2:
if L[0] == "GROUP":
self.group = L[1]
elif L[0] == "HOME":
self.home = L[1]
elif L[0] == "SHELL":
self.shell = L[1]
def userChanged(self, username):
"""Slot called when user name was changed, updating entries
@param self A AddUser instance
@param username String username
"""
self.ui.initGLine.setText(self.group)
self.ui.homeLine.setText(os.path.join(self.home, username))
self.ui.shellLine.setText(self.shell)
def accept(self):
"""Reimplemented method QtGui.QDialog.accept
Add user to configparser before accept dialog
@param self A AddUser instance
"""
user = self.ui.nameLine.text()
print("__accepted__", user)
if user in self.configparser.getUsersList():
if QtGui.QMessageBox.warning(self, self.tr("Replace User"),
self.tr("Are you sure you want to overwrite \"{0}\" user?")\
.format(user), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
QtGui.QMessageBox.No) == QtGui.QMessageBox.Yes:
self.configparser.delUser(user)
else:
return
self.configparser.addUser(user)
if self.ui.syncCheck.isChecked():
self.configparser.setUserSync(user, passwd=self.ui.pwLine.text(),
uid=self.ui.uidSpin.text(), init_group=self.ui.initGLine.text(),
groups=[g.strip() for g in self.ui.groupsLine.text().split(',')],
home=self.ui.homeLine.text(), shell=self.ui.shellLine.text())
QtGui.QDialog.accept(self) |
<|file_name|>addUser.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
#
#
# This file is part of librix-thinclient.
#
# librix-thinclient is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# librix-thinclient is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
#
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with librix-thinclient. If not, see <http://www.gnu.org/licenses/>.
import os
from PyQt4 import QtGui
from ltmt.ui.users.add_user.Ui_addUser import Ui_AddUser
class AddUser(QtGui.QDialog):
"""This class provides a add user dialog feature to users page of LTMT"""
def __init__(self, configparser, parent=None):
<|fim_middle|>
def parseDefaults(self):
"""Parse some default values for new user accounts
@param self A AddUser instance
"""
with open("/etc/default/useradd", 'r') as ua:
for l in ua:
L = l.strip().split('=')
if len(L) >= 2:
if L[0] == "GROUP":
self.group = L[1]
elif L[0] == "HOME":
self.home = L[1]
elif L[0] == "SHELL":
self.shell = L[1]
def userChanged(self, username):
"""Slot called when user name was changed, updating entries
@param self A AddUser instance
@param username String username
"""
self.ui.initGLine.setText(self.group)
self.ui.homeLine.setText(os.path.join(self.home, username))
self.ui.shellLine.setText(self.shell)
def accept(self):
"""Reimplemented method QtGui.QDialog.accept
Add user to configparser before accept dialog
@param self A AddUser instance
"""
user = self.ui.nameLine.text()
print("__accepted__", user)
if user in self.configparser.getUsersList():
if QtGui.QMessageBox.warning(self, self.tr("Replace User"),
self.tr("Are you sure you want to overwrite \"{0}\" user?")\
.format(user), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
QtGui.QMessageBox.No) == QtGui.QMessageBox.Yes:
self.configparser.delUser(user)
else:
return
self.configparser.addUser(user)
if self.ui.syncCheck.isChecked():
self.configparser.setUserSync(user, passwd=self.ui.pwLine.text(),
uid=self.ui.uidSpin.text(), init_group=self.ui.initGLine.text(),
groups=[g.strip() for g in self.ui.groupsLine.text().split(',')],
home=self.ui.homeLine.text(), shell=self.ui.shellLine.text())
QtGui.QDialog.accept(self)
<|fim▁end|> | """Init method
@param self A AddUser instance
@param parent Parent QtGui.QWidget object
"""
self.configparser = configparser
self.parent = parent
QtGui.QDialog.__init__(self)
self.ui = Ui_AddUser()
self.ui.setupUi(self)
self.parseDefaults()
self.ui.detailsWid.hide() |
<|file_name|>addUser.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
#
#
# This file is part of librix-thinclient.
#
# librix-thinclient is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# librix-thinclient is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
#
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with librix-thinclient. If not, see <http://www.gnu.org/licenses/>.
import os
from PyQt4 import QtGui
from ltmt.ui.users.add_user.Ui_addUser import Ui_AddUser
class AddUser(QtGui.QDialog):
"""This class provides a add user dialog feature to users page of LTMT"""
def __init__(self, configparser, parent=None):
"""Init method
@param self A AddUser instance
@param parent Parent QtGui.QWidget object
"""
self.configparser = configparser
self.parent = parent
QtGui.QDialog.__init__(self)
self.ui = Ui_AddUser()
self.ui.setupUi(self)
self.parseDefaults()
self.ui.detailsWid.hide()
def parseDefaults(self):
<|fim_middle|>
def userChanged(self, username):
"""Slot called when user name was changed, updating entries
@param self A AddUser instance
@param username String username
"""
self.ui.initGLine.setText(self.group)
self.ui.homeLine.setText(os.path.join(self.home, username))
self.ui.shellLine.setText(self.shell)
def accept(self):
"""Reimplemented method QtGui.QDialog.accept
Add user to configparser before accept dialog
@param self A AddUser instance
"""
user = self.ui.nameLine.text()
print("__accepted__", user)
if user in self.configparser.getUsersList():
if QtGui.QMessageBox.warning(self, self.tr("Replace User"),
self.tr("Are you sure you want to overwrite \"{0}\" user?")\
.format(user), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
QtGui.QMessageBox.No) == QtGui.QMessageBox.Yes:
self.configparser.delUser(user)
else:
return
self.configparser.addUser(user)
if self.ui.syncCheck.isChecked():
self.configparser.setUserSync(user, passwd=self.ui.pwLine.text(),
uid=self.ui.uidSpin.text(), init_group=self.ui.initGLine.text(),
groups=[g.strip() for g in self.ui.groupsLine.text().split(',')],
home=self.ui.homeLine.text(), shell=self.ui.shellLine.text())
QtGui.QDialog.accept(self)
<|fim▁end|> | """Parse some default values for new user accounts
@param self A AddUser instance
"""
with open("/etc/default/useradd", 'r') as ua:
for l in ua:
L = l.strip().split('=')
if len(L) >= 2:
if L[0] == "GROUP":
self.group = L[1]
elif L[0] == "HOME":
self.home = L[1]
elif L[0] == "SHELL":
self.shell = L[1] |
<|file_name|>addUser.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
#
#
# This file is part of librix-thinclient.
#
# librix-thinclient is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# librix-thinclient is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
#
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with librix-thinclient. If not, see <http://www.gnu.org/licenses/>.
import os
from PyQt4 import QtGui
from ltmt.ui.users.add_user.Ui_addUser import Ui_AddUser
class AddUser(QtGui.QDialog):
"""This class provides a add user dialog feature to users page of LTMT"""
def __init__(self, configparser, parent=None):
"""Init method
@param self A AddUser instance
@param parent Parent QtGui.QWidget object
"""
self.configparser = configparser
self.parent = parent
QtGui.QDialog.__init__(self)
self.ui = Ui_AddUser()
self.ui.setupUi(self)
self.parseDefaults()
self.ui.detailsWid.hide()
def parseDefaults(self):
"""Parse some default values for new user accounts
@param self A AddUser instance
"""
with open("/etc/default/useradd", 'r') as ua:
for l in ua:
L = l.strip().split('=')
if len(L) >= 2:
if L[0] == "GROUP":
self.group = L[1]
elif L[0] == "HOME":
self.home = L[1]
elif L[0] == "SHELL":
self.shell = L[1]
def userChanged(self, username):
<|fim_middle|>
def accept(self):
"""Reimplemented method QtGui.QDialog.accept
Add user to configparser before accept dialog
@param self A AddUser instance
"""
user = self.ui.nameLine.text()
print("__accepted__", user)
if user in self.configparser.getUsersList():
if QtGui.QMessageBox.warning(self, self.tr("Replace User"),
self.tr("Are you sure you want to overwrite \"{0}\" user?")\
.format(user), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
QtGui.QMessageBox.No) == QtGui.QMessageBox.Yes:
self.configparser.delUser(user)
else:
return
self.configparser.addUser(user)
if self.ui.syncCheck.isChecked():
self.configparser.setUserSync(user, passwd=self.ui.pwLine.text(),
uid=self.ui.uidSpin.text(), init_group=self.ui.initGLine.text(),
groups=[g.strip() for g in self.ui.groupsLine.text().split(',')],
home=self.ui.homeLine.text(), shell=self.ui.shellLine.text())
QtGui.QDialog.accept(self)
<|fim▁end|> | """Slot called when user name was changed, updating entries
@param self A AddUser instance
@param username String username
"""
self.ui.initGLine.setText(self.group)
self.ui.homeLine.setText(os.path.join(self.home, username))
self.ui.shellLine.setText(self.shell) |
<|file_name|>addUser.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
#
#
# This file is part of librix-thinclient.
#
# librix-thinclient is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# librix-thinclient is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
#
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with librix-thinclient. If not, see <http://www.gnu.org/licenses/>.
import os
from PyQt4 import QtGui
from ltmt.ui.users.add_user.Ui_addUser import Ui_AddUser
class AddUser(QtGui.QDialog):
"""This class provides a add user dialog feature to users page of LTMT"""
def __init__(self, configparser, parent=None):
"""Init method
@param self A AddUser instance
@param parent Parent QtGui.QWidget object
"""
self.configparser = configparser
self.parent = parent
QtGui.QDialog.__init__(self)
self.ui = Ui_AddUser()
self.ui.setupUi(self)
self.parseDefaults()
self.ui.detailsWid.hide()
def parseDefaults(self):
"""Parse some default values for new user accounts
@param self A AddUser instance
"""
with open("/etc/default/useradd", 'r') as ua:
for l in ua:
L = l.strip().split('=')
if len(L) >= 2:
if L[0] == "GROUP":
self.group = L[1]
elif L[0] == "HOME":
self.home = L[1]
elif L[0] == "SHELL":
self.shell = L[1]
def userChanged(self, username):
"""Slot called when user name was changed, updating entries
@param self A AddUser instance
@param username String username
"""
self.ui.initGLine.setText(self.group)
self.ui.homeLine.setText(os.path.join(self.home, username))
self.ui.shellLine.setText(self.shell)
def accept(self):
<|fim_middle|>
<|fim▁end|> | """Reimplemented method QtGui.QDialog.accept
Add user to configparser before accept dialog
@param self A AddUser instance
"""
user = self.ui.nameLine.text()
print("__accepted__", user)
if user in self.configparser.getUsersList():
if QtGui.QMessageBox.warning(self, self.tr("Replace User"),
self.tr("Are you sure you want to overwrite \"{0}\" user?")\
.format(user), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
QtGui.QMessageBox.No) == QtGui.QMessageBox.Yes:
self.configparser.delUser(user)
else:
return
self.configparser.addUser(user)
if self.ui.syncCheck.isChecked():
self.configparser.setUserSync(user, passwd=self.ui.pwLine.text(),
uid=self.ui.uidSpin.text(), init_group=self.ui.initGLine.text(),
groups=[g.strip() for g in self.ui.groupsLine.text().split(',')],
home=self.ui.homeLine.text(), shell=self.ui.shellLine.text())
QtGui.QDialog.accept(self) |
<|file_name|>addUser.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
#
#
# This file is part of librix-thinclient.
#
# librix-thinclient is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# librix-thinclient is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
#
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with librix-thinclient. If not, see <http://www.gnu.org/licenses/>.
import os
from PyQt4 import QtGui
from ltmt.ui.users.add_user.Ui_addUser import Ui_AddUser
class AddUser(QtGui.QDialog):
"""This class provides a add user dialog feature to users page of LTMT"""
def __init__(self, configparser, parent=None):
"""Init method
@param self A AddUser instance
@param parent Parent QtGui.QWidget object
"""
self.configparser = configparser
self.parent = parent
QtGui.QDialog.__init__(self)
self.ui = Ui_AddUser()
self.ui.setupUi(self)
self.parseDefaults()
self.ui.detailsWid.hide()
def parseDefaults(self):
"""Parse some default values for new user accounts
@param self A AddUser instance
"""
with open("/etc/default/useradd", 'r') as ua:
for l in ua:
L = l.strip().split('=')
if len(L) >= 2:
<|fim_middle|>
def userChanged(self, username):
"""Slot called when user name was changed, updating entries
@param self A AddUser instance
@param username String username
"""
self.ui.initGLine.setText(self.group)
self.ui.homeLine.setText(os.path.join(self.home, username))
self.ui.shellLine.setText(self.shell)
def accept(self):
"""Reimplemented method QtGui.QDialog.accept
Add user to configparser before accept dialog
@param self A AddUser instance
"""
user = self.ui.nameLine.text()
print("__accepted__", user)
if user in self.configparser.getUsersList():
if QtGui.QMessageBox.warning(self, self.tr("Replace User"),
self.tr("Are you sure you want to overwrite \"{0}\" user?")\
.format(user), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
QtGui.QMessageBox.No) == QtGui.QMessageBox.Yes:
self.configparser.delUser(user)
else:
return
self.configparser.addUser(user)
if self.ui.syncCheck.isChecked():
self.configparser.setUserSync(user, passwd=self.ui.pwLine.text(),
uid=self.ui.uidSpin.text(), init_group=self.ui.initGLine.text(),
groups=[g.strip() for g in self.ui.groupsLine.text().split(',')],
home=self.ui.homeLine.text(), shell=self.ui.shellLine.text())
QtGui.QDialog.accept(self)
<|fim▁end|> | if L[0] == "GROUP":
self.group = L[1]
elif L[0] == "HOME":
self.home = L[1]
elif L[0] == "SHELL":
self.shell = L[1] |
<|file_name|>addUser.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
#
#
# This file is part of librix-thinclient.
#
# librix-thinclient is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# librix-thinclient is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
#
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with librix-thinclient. If not, see <http://www.gnu.org/licenses/>.
import os
from PyQt4 import QtGui
from ltmt.ui.users.add_user.Ui_addUser import Ui_AddUser
class AddUser(QtGui.QDialog):
"""This class provides a add user dialog feature to users page of LTMT"""
def __init__(self, configparser, parent=None):
"""Init method
@param self A AddUser instance
@param parent Parent QtGui.QWidget object
"""
self.configparser = configparser
self.parent = parent
QtGui.QDialog.__init__(self)
self.ui = Ui_AddUser()
self.ui.setupUi(self)
self.parseDefaults()
self.ui.detailsWid.hide()
def parseDefaults(self):
"""Parse some default values for new user accounts
@param self A AddUser instance
"""
with open("/etc/default/useradd", 'r') as ua:
for l in ua:
L = l.strip().split('=')
if len(L) >= 2:
if L[0] == "GROUP":
<|fim_middle|>
elif L[0] == "HOME":
self.home = L[1]
elif L[0] == "SHELL":
self.shell = L[1]
def userChanged(self, username):
"""Slot called when user name was changed, updating entries
@param self A AddUser instance
@param username String username
"""
self.ui.initGLine.setText(self.group)
self.ui.homeLine.setText(os.path.join(self.home, username))
self.ui.shellLine.setText(self.shell)
def accept(self):
"""Reimplemented method QtGui.QDialog.accept
Add user to configparser before accept dialog
@param self A AddUser instance
"""
user = self.ui.nameLine.text()
print("__accepted__", user)
if user in self.configparser.getUsersList():
if QtGui.QMessageBox.warning(self, self.tr("Replace User"),
self.tr("Are you sure you want to overwrite \"{0}\" user?")\
.format(user), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
QtGui.QMessageBox.No) == QtGui.QMessageBox.Yes:
self.configparser.delUser(user)
else:
return
self.configparser.addUser(user)
if self.ui.syncCheck.isChecked():
self.configparser.setUserSync(user, passwd=self.ui.pwLine.text(),
uid=self.ui.uidSpin.text(), init_group=self.ui.initGLine.text(),
groups=[g.strip() for g in self.ui.groupsLine.text().split(',')],
home=self.ui.homeLine.text(), shell=self.ui.shellLine.text())
QtGui.QDialog.accept(self)
<|fim▁end|> | self.group = L[1] |
<|file_name|>addUser.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
#
#
# This file is part of librix-thinclient.
#
# librix-thinclient is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# librix-thinclient is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
#
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with librix-thinclient. If not, see <http://www.gnu.org/licenses/>.
import os
from PyQt4 import QtGui
from ltmt.ui.users.add_user.Ui_addUser import Ui_AddUser
class AddUser(QtGui.QDialog):
"""This class provides a add user dialog feature to users page of LTMT"""
def __init__(self, configparser, parent=None):
"""Init method
@param self A AddUser instance
@param parent Parent QtGui.QWidget object
"""
self.configparser = configparser
self.parent = parent
QtGui.QDialog.__init__(self)
self.ui = Ui_AddUser()
self.ui.setupUi(self)
self.parseDefaults()
self.ui.detailsWid.hide()
def parseDefaults(self):
"""Parse some default values for new user accounts
@param self A AddUser instance
"""
with open("/etc/default/useradd", 'r') as ua:
for l in ua:
L = l.strip().split('=')
if len(L) >= 2:
if L[0] == "GROUP":
self.group = L[1]
elif L[0] == "HOME":
<|fim_middle|>
elif L[0] == "SHELL":
self.shell = L[1]
def userChanged(self, username):
"""Slot called when user name was changed, updating entries
@param self A AddUser instance
@param username String username
"""
self.ui.initGLine.setText(self.group)
self.ui.homeLine.setText(os.path.join(self.home, username))
self.ui.shellLine.setText(self.shell)
def accept(self):
"""Reimplemented method QtGui.QDialog.accept
Add user to configparser before accept dialog
@param self A AddUser instance
"""
user = self.ui.nameLine.text()
print("__accepted__", user)
if user in self.configparser.getUsersList():
if QtGui.QMessageBox.warning(self, self.tr("Replace User"),
self.tr("Are you sure you want to overwrite \"{0}\" user?")\
.format(user), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
QtGui.QMessageBox.No) == QtGui.QMessageBox.Yes:
self.configparser.delUser(user)
else:
return
self.configparser.addUser(user)
if self.ui.syncCheck.isChecked():
self.configparser.setUserSync(user, passwd=self.ui.pwLine.text(),
uid=self.ui.uidSpin.text(), init_group=self.ui.initGLine.text(),
groups=[g.strip() for g in self.ui.groupsLine.text().split(',')],
home=self.ui.homeLine.text(), shell=self.ui.shellLine.text())
QtGui.QDialog.accept(self)
<|fim▁end|> | self.home = L[1] |
<|file_name|>addUser.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
#
#
# This file is part of librix-thinclient.
#
# librix-thinclient is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# librix-thinclient is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
#
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with librix-thinclient. If not, see <http://www.gnu.org/licenses/>.
import os
from PyQt4 import QtGui
from ltmt.ui.users.add_user.Ui_addUser import Ui_AddUser
class AddUser(QtGui.QDialog):
"""This class provides a add user dialog feature to users page of LTMT"""
def __init__(self, configparser, parent=None):
"""Init method
@param self A AddUser instance
@param parent Parent QtGui.QWidget object
"""
self.configparser = configparser
self.parent = parent
QtGui.QDialog.__init__(self)
self.ui = Ui_AddUser()
self.ui.setupUi(self)
self.parseDefaults()
self.ui.detailsWid.hide()
def parseDefaults(self):
"""Parse some default values for new user accounts
@param self A AddUser instance
"""
with open("/etc/default/useradd", 'r') as ua:
for l in ua:
L = l.strip().split('=')
if len(L) >= 2:
if L[0] == "GROUP":
self.group = L[1]
elif L[0] == "HOME":
self.home = L[1]
elif L[0] == "SHELL":
<|fim_middle|>
def userChanged(self, username):
"""Slot called when user name was changed, updating entries
@param self A AddUser instance
@param username String username
"""
self.ui.initGLine.setText(self.group)
self.ui.homeLine.setText(os.path.join(self.home, username))
self.ui.shellLine.setText(self.shell)
def accept(self):
"""Reimplemented method QtGui.QDialog.accept
Add user to configparser before accept dialog
@param self A AddUser instance
"""
user = self.ui.nameLine.text()
print("__accepted__", user)
if user in self.configparser.getUsersList():
if QtGui.QMessageBox.warning(self, self.tr("Replace User"),
self.tr("Are you sure you want to overwrite \"{0}\" user?")\
.format(user), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
QtGui.QMessageBox.No) == QtGui.QMessageBox.Yes:
self.configparser.delUser(user)
else:
return
self.configparser.addUser(user)
if self.ui.syncCheck.isChecked():
self.configparser.setUserSync(user, passwd=self.ui.pwLine.text(),
uid=self.ui.uidSpin.text(), init_group=self.ui.initGLine.text(),
groups=[g.strip() for g in self.ui.groupsLine.text().split(',')],
home=self.ui.homeLine.text(), shell=self.ui.shellLine.text())
QtGui.QDialog.accept(self)
<|fim▁end|> | self.shell = L[1] |
<|file_name|>addUser.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
#
#
# This file is part of librix-thinclient.
#
# librix-thinclient is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# librix-thinclient is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
#
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with librix-thinclient. If not, see <http://www.gnu.org/licenses/>.
import os
from PyQt4 import QtGui
from ltmt.ui.users.add_user.Ui_addUser import Ui_AddUser
class AddUser(QtGui.QDialog):
"""This class provides a add user dialog feature to users page of LTMT"""
def __init__(self, configparser, parent=None):
"""Init method
@param self A AddUser instance
@param parent Parent QtGui.QWidget object
"""
self.configparser = configparser
self.parent = parent
QtGui.QDialog.__init__(self)
self.ui = Ui_AddUser()
self.ui.setupUi(self)
self.parseDefaults()
self.ui.detailsWid.hide()
def parseDefaults(self):
"""Parse some default values for new user accounts
@param self A AddUser instance
"""
with open("/etc/default/useradd", 'r') as ua:
for l in ua:
L = l.strip().split('=')
if len(L) >= 2:
if L[0] == "GROUP":
self.group = L[1]
elif L[0] == "HOME":
self.home = L[1]
elif L[0] == "SHELL":
self.shell = L[1]
def userChanged(self, username):
"""Slot called when user name was changed, updating entries
@param self A AddUser instance
@param username String username
"""
self.ui.initGLine.setText(self.group)
self.ui.homeLine.setText(os.path.join(self.home, username))
self.ui.shellLine.setText(self.shell)
def accept(self):
"""Reimplemented method QtGui.QDialog.accept
Add user to configparser before accept dialog
@param self A AddUser instance
"""
user = self.ui.nameLine.text()
print("__accepted__", user)
if user in self.configparser.getUsersList():
<|fim_middle|>
self.configparser.addUser(user)
if self.ui.syncCheck.isChecked():
self.configparser.setUserSync(user, passwd=self.ui.pwLine.text(),
uid=self.ui.uidSpin.text(), init_group=self.ui.initGLine.text(),
groups=[g.strip() for g in self.ui.groupsLine.text().split(',')],
home=self.ui.homeLine.text(), shell=self.ui.shellLine.text())
QtGui.QDialog.accept(self)
<|fim▁end|> | if QtGui.QMessageBox.warning(self, self.tr("Replace User"),
self.tr("Are you sure you want to overwrite \"{0}\" user?")\
.format(user), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
QtGui.QMessageBox.No) == QtGui.QMessageBox.Yes:
self.configparser.delUser(user)
else:
return |
<|file_name|>addUser.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
#
#
# This file is part of librix-thinclient.
#
# librix-thinclient is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# librix-thinclient is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
#
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with librix-thinclient. If not, see <http://www.gnu.org/licenses/>.
import os
from PyQt4 import QtGui
from ltmt.ui.users.add_user.Ui_addUser import Ui_AddUser
class AddUser(QtGui.QDialog):
"""This class provides a add user dialog feature to users page of LTMT"""
def __init__(self, configparser, parent=None):
"""Init method
@param self A AddUser instance
@param parent Parent QtGui.QWidget object
"""
self.configparser = configparser
self.parent = parent
QtGui.QDialog.__init__(self)
self.ui = Ui_AddUser()
self.ui.setupUi(self)
self.parseDefaults()
self.ui.detailsWid.hide()
def parseDefaults(self):
"""Parse some default values for new user accounts
@param self A AddUser instance
"""
with open("/etc/default/useradd", 'r') as ua:
for l in ua:
L = l.strip().split('=')
if len(L) >= 2:
if L[0] == "GROUP":
self.group = L[1]
elif L[0] == "HOME":
self.home = L[1]
elif L[0] == "SHELL":
self.shell = L[1]
def userChanged(self, username):
"""Slot called when user name was changed, updating entries
@param self A AddUser instance
@param username String username
"""
self.ui.initGLine.setText(self.group)
self.ui.homeLine.setText(os.path.join(self.home, username))
self.ui.shellLine.setText(self.shell)
def accept(self):
"""Reimplemented method QtGui.QDialog.accept
Add user to configparser before accept dialog
@param self A AddUser instance
"""
user = self.ui.nameLine.text()
print("__accepted__", user)
if user in self.configparser.getUsersList():
if QtGui.QMessageBox.warning(self, self.tr("Replace User"),
self.tr("Are you sure you want to overwrite \"{0}\" user?")\
.format(user), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
QtGui.QMessageBox.No) == QtGui.QMessageBox.Yes:
<|fim_middle|>
else:
return
self.configparser.addUser(user)
if self.ui.syncCheck.isChecked():
self.configparser.setUserSync(user, passwd=self.ui.pwLine.text(),
uid=self.ui.uidSpin.text(), init_group=self.ui.initGLine.text(),
groups=[g.strip() for g in self.ui.groupsLine.text().split(',')],
home=self.ui.homeLine.text(), shell=self.ui.shellLine.text())
QtGui.QDialog.accept(self)
<|fim▁end|> | self.configparser.delUser(user) |
<|file_name|>addUser.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
#
#
# This file is part of librix-thinclient.
#
# librix-thinclient is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# librix-thinclient is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
#
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with librix-thinclient. If not, see <http://www.gnu.org/licenses/>.
import os
from PyQt4 import QtGui
from ltmt.ui.users.add_user.Ui_addUser import Ui_AddUser
class AddUser(QtGui.QDialog):
"""This class provides a add user dialog feature to users page of LTMT"""
def __init__(self, configparser, parent=None):
"""Init method
@param self A AddUser instance
@param parent Parent QtGui.QWidget object
"""
self.configparser = configparser
self.parent = parent
QtGui.QDialog.__init__(self)
self.ui = Ui_AddUser()
self.ui.setupUi(self)
self.parseDefaults()
self.ui.detailsWid.hide()
def parseDefaults(self):
"""Parse some default values for new user accounts
@param self A AddUser instance
"""
with open("/etc/default/useradd", 'r') as ua:
for l in ua:
L = l.strip().split('=')
if len(L) >= 2:
if L[0] == "GROUP":
self.group = L[1]
elif L[0] == "HOME":
self.home = L[1]
elif L[0] == "SHELL":
self.shell = L[1]
def userChanged(self, username):
"""Slot called when user name was changed, updating entries
@param self A AddUser instance
@param username String username
"""
self.ui.initGLine.setText(self.group)
self.ui.homeLine.setText(os.path.join(self.home, username))
self.ui.shellLine.setText(self.shell)
def accept(self):
"""Reimplemented method QtGui.QDialog.accept
Add user to configparser before accept dialog
@param self A AddUser instance
"""
user = self.ui.nameLine.text()
print("__accepted__", user)
if user in self.configparser.getUsersList():
if QtGui.QMessageBox.warning(self, self.tr("Replace User"),
self.tr("Are you sure you want to overwrite \"{0}\" user?")\
.format(user), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
QtGui.QMessageBox.No) == QtGui.QMessageBox.Yes:
self.configparser.delUser(user)
else:
<|fim_middle|>
self.configparser.addUser(user)
if self.ui.syncCheck.isChecked():
self.configparser.setUserSync(user, passwd=self.ui.pwLine.text(),
uid=self.ui.uidSpin.text(), init_group=self.ui.initGLine.text(),
groups=[g.strip() for g in self.ui.groupsLine.text().split(',')],
home=self.ui.homeLine.text(), shell=self.ui.shellLine.text())
QtGui.QDialog.accept(self)
<|fim▁end|> | return |
<|file_name|>addUser.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
#
#
# This file is part of librix-thinclient.
#
# librix-thinclient is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# librix-thinclient is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
#
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with librix-thinclient. If not, see <http://www.gnu.org/licenses/>.
import os
from PyQt4 import QtGui
from ltmt.ui.users.add_user.Ui_addUser import Ui_AddUser
class AddUser(QtGui.QDialog):
"""This class provides a add user dialog feature to users page of LTMT"""
def __init__(self, configparser, parent=None):
"""Init method
@param self A AddUser instance
@param parent Parent QtGui.QWidget object
"""
self.configparser = configparser
self.parent = parent
QtGui.QDialog.__init__(self)
self.ui = Ui_AddUser()
self.ui.setupUi(self)
self.parseDefaults()
self.ui.detailsWid.hide()
def parseDefaults(self):
"""Parse some default values for new user accounts
@param self A AddUser instance
"""
with open("/etc/default/useradd", 'r') as ua:
for l in ua:
L = l.strip().split('=')
if len(L) >= 2:
if L[0] == "GROUP":
self.group = L[1]
elif L[0] == "HOME":
self.home = L[1]
elif L[0] == "SHELL":
self.shell = L[1]
def userChanged(self, username):
"""Slot called when user name was changed, updating entries
@param self A AddUser instance
@param username String username
"""
self.ui.initGLine.setText(self.group)
self.ui.homeLine.setText(os.path.join(self.home, username))
self.ui.shellLine.setText(self.shell)
def accept(self):
"""Reimplemented method QtGui.QDialog.accept
Add user to configparser before accept dialog
@param self A AddUser instance
"""
user = self.ui.nameLine.text()
print("__accepted__", user)
if user in self.configparser.getUsersList():
if QtGui.QMessageBox.warning(self, self.tr("Replace User"),
self.tr("Are you sure you want to overwrite \"{0}\" user?")\
.format(user), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
QtGui.QMessageBox.No) == QtGui.QMessageBox.Yes:
self.configparser.delUser(user)
else:
return
self.configparser.addUser(user)
if self.ui.syncCheck.isChecked():
<|fim_middle|>
QtGui.QDialog.accept(self)
<|fim▁end|> | self.configparser.setUserSync(user, passwd=self.ui.pwLine.text(),
uid=self.ui.uidSpin.text(), init_group=self.ui.initGLine.text(),
groups=[g.strip() for g in self.ui.groupsLine.text().split(',')],
home=self.ui.homeLine.text(), shell=self.ui.shellLine.text()) |
<|file_name|>addUser.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
#
#
# This file is part of librix-thinclient.
#
# librix-thinclient is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# librix-thinclient is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
#
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with librix-thinclient. If not, see <http://www.gnu.org/licenses/>.
import os
from PyQt4 import QtGui
from ltmt.ui.users.add_user.Ui_addUser import Ui_AddUser
class AddUser(QtGui.QDialog):
"""This class provides a add user dialog feature to users page of LTMT"""
def <|fim_middle|>(self, configparser, parent=None):
"""Init method
@param self A AddUser instance
@param parent Parent QtGui.QWidget object
"""
self.configparser = configparser
self.parent = parent
QtGui.QDialog.__init__(self)
self.ui = Ui_AddUser()
self.ui.setupUi(self)
self.parseDefaults()
self.ui.detailsWid.hide()
def parseDefaults(self):
"""Parse some default values for new user accounts
@param self A AddUser instance
"""
with open("/etc/default/useradd", 'r') as ua:
for l in ua:
L = l.strip().split('=')
if len(L) >= 2:
if L[0] == "GROUP":
self.group = L[1]
elif L[0] == "HOME":
self.home = L[1]
elif L[0] == "SHELL":
self.shell = L[1]
def userChanged(self, username):
"""Slot called when user name was changed, updating entries
@param self A AddUser instance
@param username String username
"""
self.ui.initGLine.setText(self.group)
self.ui.homeLine.setText(os.path.join(self.home, username))
self.ui.shellLine.setText(self.shell)
def accept(self):
"""Reimplemented method QtGui.QDialog.accept
Add user to configparser before accept dialog
@param self A AddUser instance
"""
user = self.ui.nameLine.text()
print("__accepted__", user)
if user in self.configparser.getUsersList():
if QtGui.QMessageBox.warning(self, self.tr("Replace User"),
self.tr("Are you sure you want to overwrite \"{0}\" user?")\
.format(user), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
QtGui.QMessageBox.No) == QtGui.QMessageBox.Yes:
self.configparser.delUser(user)
else:
return
self.configparser.addUser(user)
if self.ui.syncCheck.isChecked():
self.configparser.setUserSync(user, passwd=self.ui.pwLine.text(),
uid=self.ui.uidSpin.text(), init_group=self.ui.initGLine.text(),
groups=[g.strip() for g in self.ui.groupsLine.text().split(',')],
home=self.ui.homeLine.text(), shell=self.ui.shellLine.text())
QtGui.QDialog.accept(self)
<|fim▁end|> | __init__ |
<|file_name|>addUser.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
#
#
# This file is part of librix-thinclient.
#
# librix-thinclient is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# librix-thinclient is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
#
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with librix-thinclient. If not, see <http://www.gnu.org/licenses/>.
import os
from PyQt4 import QtGui
from ltmt.ui.users.add_user.Ui_addUser import Ui_AddUser
class AddUser(QtGui.QDialog):
"""This class provides a add user dialog feature to users page of LTMT"""
def __init__(self, configparser, parent=None):
"""Init method
@param self A AddUser instance
@param parent Parent QtGui.QWidget object
"""
self.configparser = configparser
self.parent = parent
QtGui.QDialog.__init__(self)
self.ui = Ui_AddUser()
self.ui.setupUi(self)
self.parseDefaults()
self.ui.detailsWid.hide()
def <|fim_middle|>(self):
"""Parse some default values for new user accounts
@param self A AddUser instance
"""
with open("/etc/default/useradd", 'r') as ua:
for l in ua:
L = l.strip().split('=')
if len(L) >= 2:
if L[0] == "GROUP":
self.group = L[1]
elif L[0] == "HOME":
self.home = L[1]
elif L[0] == "SHELL":
self.shell = L[1]
def userChanged(self, username):
"""Slot called when user name was changed, updating entries
@param self A AddUser instance
@param username String username
"""
self.ui.initGLine.setText(self.group)
self.ui.homeLine.setText(os.path.join(self.home, username))
self.ui.shellLine.setText(self.shell)
def accept(self):
"""Reimplemented method QtGui.QDialog.accept
Add user to configparser before accept dialog
@param self A AddUser instance
"""
user = self.ui.nameLine.text()
print("__accepted__", user)
if user in self.configparser.getUsersList():
if QtGui.QMessageBox.warning(self, self.tr("Replace User"),
self.tr("Are you sure you want to overwrite \"{0}\" user?")\
.format(user), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
QtGui.QMessageBox.No) == QtGui.QMessageBox.Yes:
self.configparser.delUser(user)
else:
return
self.configparser.addUser(user)
if self.ui.syncCheck.isChecked():
self.configparser.setUserSync(user, passwd=self.ui.pwLine.text(),
uid=self.ui.uidSpin.text(), init_group=self.ui.initGLine.text(),
groups=[g.strip() for g in self.ui.groupsLine.text().split(',')],
home=self.ui.homeLine.text(), shell=self.ui.shellLine.text())
QtGui.QDialog.accept(self)
<|fim▁end|> | parseDefaults |
<|file_name|>addUser.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
#
#
# This file is part of librix-thinclient.
#
# librix-thinclient is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# librix-thinclient is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
#
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with librix-thinclient. If not, see <http://www.gnu.org/licenses/>.
import os
from PyQt4 import QtGui
from ltmt.ui.users.add_user.Ui_addUser import Ui_AddUser
class AddUser(QtGui.QDialog):
"""This class provides a add user dialog feature to users page of LTMT"""
def __init__(self, configparser, parent=None):
"""Init method
@param self A AddUser instance
@param parent Parent QtGui.QWidget object
"""
self.configparser = configparser
self.parent = parent
QtGui.QDialog.__init__(self)
self.ui = Ui_AddUser()
self.ui.setupUi(self)
self.parseDefaults()
self.ui.detailsWid.hide()
def parseDefaults(self):
"""Parse some default values for new user accounts
@param self A AddUser instance
"""
with open("/etc/default/useradd", 'r') as ua:
for l in ua:
L = l.strip().split('=')
if len(L) >= 2:
if L[0] == "GROUP":
self.group = L[1]
elif L[0] == "HOME":
self.home = L[1]
elif L[0] == "SHELL":
self.shell = L[1]
def <|fim_middle|>(self, username):
"""Slot called when user name was changed, updating entries
@param self A AddUser instance
@param username String username
"""
self.ui.initGLine.setText(self.group)
self.ui.homeLine.setText(os.path.join(self.home, username))
self.ui.shellLine.setText(self.shell)
def accept(self):
"""Reimplemented method QtGui.QDialog.accept
Add user to configparser before accept dialog
@param self A AddUser instance
"""
user = self.ui.nameLine.text()
print("__accepted__", user)
if user in self.configparser.getUsersList():
if QtGui.QMessageBox.warning(self, self.tr("Replace User"),
self.tr("Are you sure you want to overwrite \"{0}\" user?")\
.format(user), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
QtGui.QMessageBox.No) == QtGui.QMessageBox.Yes:
self.configparser.delUser(user)
else:
return
self.configparser.addUser(user)
if self.ui.syncCheck.isChecked():
self.configparser.setUserSync(user, passwd=self.ui.pwLine.text(),
uid=self.ui.uidSpin.text(), init_group=self.ui.initGLine.text(),
groups=[g.strip() for g in self.ui.groupsLine.text().split(',')],
home=self.ui.homeLine.text(), shell=self.ui.shellLine.text())
QtGui.QDialog.accept(self)
<|fim▁end|> | userChanged |
<|file_name|>addUser.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
#
#
# This file is part of librix-thinclient.
#
# librix-thinclient is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# librix-thinclient is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
#
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with librix-thinclient. If not, see <http://www.gnu.org/licenses/>.
import os
from PyQt4 import QtGui
from ltmt.ui.users.add_user.Ui_addUser import Ui_AddUser
class AddUser(QtGui.QDialog):
"""This class provides a add user dialog feature to users page of LTMT"""
def __init__(self, configparser, parent=None):
"""Init method
@param self A AddUser instance
@param parent Parent QtGui.QWidget object
"""
self.configparser = configparser
self.parent = parent
QtGui.QDialog.__init__(self)
self.ui = Ui_AddUser()
self.ui.setupUi(self)
self.parseDefaults()
self.ui.detailsWid.hide()
def parseDefaults(self):
"""Parse some default values for new user accounts
@param self A AddUser instance
"""
with open("/etc/default/useradd", 'r') as ua:
for l in ua:
L = l.strip().split('=')
if len(L) >= 2:
if L[0] == "GROUP":
self.group = L[1]
elif L[0] == "HOME":
self.home = L[1]
elif L[0] == "SHELL":
self.shell = L[1]
def userChanged(self, username):
"""Slot called when user name was changed, updating entries
@param self A AddUser instance
@param username String username
"""
self.ui.initGLine.setText(self.group)
self.ui.homeLine.setText(os.path.join(self.home, username))
self.ui.shellLine.setText(self.shell)
def <|fim_middle|>(self):
"""Reimplemented method QtGui.QDialog.accept
Add user to configparser before accept dialog
@param self A AddUser instance
"""
user = self.ui.nameLine.text()
print("__accepted__", user)
if user in self.configparser.getUsersList():
if QtGui.QMessageBox.warning(self, self.tr("Replace User"),
self.tr("Are you sure you want to overwrite \"{0}\" user?")\
.format(user), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
QtGui.QMessageBox.No) == QtGui.QMessageBox.Yes:
self.configparser.delUser(user)
else:
return
self.configparser.addUser(user)
if self.ui.syncCheck.isChecked():
self.configparser.setUserSync(user, passwd=self.ui.pwLine.text(),
uid=self.ui.uidSpin.text(), init_group=self.ui.initGLine.text(),
groups=[g.strip() for g in self.ui.groupsLine.text().split(',')],
home=self.ui.homeLine.text(), shell=self.ui.shellLine.text())
QtGui.QDialog.accept(self)
<|fim▁end|> | accept |
<|file_name|>exceptions.py<|end_file_name|><|fim▁begin|>from rest_framework import status<|fim▁hole|>
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response:
message = response.data
if isinstance(message, dict):
for error_key, error_description in message.iteritems():
if error_key in top_level_error_keys:
errors.append({error_key: error_description})
else:
if isinstance(error_description, basestring):
error_description = [error_description]
errors.extend([{'source': {'pointer': '/data/attributes/' + error_key}, 'detail': reason}
for reason in error_description])
else:
if isinstance(message, basestring):
message = [message]
errors.extend([{'detail': error} for error in message])
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
class InvalidFilterError(ParseError):
"""Raised when client passes an invalid filter in the querystring."""
default_detail = 'Querystring contains an invalid filter.'<|fim▁end|> | from rest_framework.exceptions import APIException, ParseError |
<|file_name|>exceptions.py<|end_file_name|><|fim▁begin|>
from rest_framework import status
from rest_framework.exceptions import APIException, ParseError
def json_api_exception_handler(exc, context):
<|fim_middle|>
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
class InvalidFilterError(ParseError):
"""Raised when client passes an invalid filter in the querystring."""
default_detail = 'Querystring contains an invalid filter.'
<|fim▁end|> | """ Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response:
message = response.data
if isinstance(message, dict):
for error_key, error_description in message.iteritems():
if error_key in top_level_error_keys:
errors.append({error_key: error_description})
else:
if isinstance(error_description, basestring):
error_description = [error_description]
errors.extend([{'source': {'pointer': '/data/attributes/' + error_key}, 'detail': reason}
for reason in error_description])
else:
if isinstance(message, basestring):
message = [message]
errors.extend([{'detail': error} for error in message])
response.data = {'errors': errors}
return response |
<|file_name|>exceptions.py<|end_file_name|><|fim▁begin|>
from rest_framework import status
from rest_framework.exceptions import APIException, ParseError
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response:
message = response.data
if isinstance(message, dict):
for error_key, error_description in message.iteritems():
if error_key in top_level_error_keys:
errors.append({error_key: error_description})
else:
if isinstance(error_description, basestring):
error_description = [error_description]
errors.extend([{'source': {'pointer': '/data/attributes/' + error_key}, 'detail': reason}
for reason in error_description])
else:
if isinstance(message, basestring):
message = [message]
errors.extend([{'detail': error} for error in message])
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
<|fim_middle|>
class InvalidFilterError(ParseError):
"""Raised when client passes an invalid filter in the querystring."""
default_detail = 'Querystring contains an invalid filter.'
<|fim▁end|> | status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.') |
<|file_name|>exceptions.py<|end_file_name|><|fim▁begin|>
from rest_framework import status
from rest_framework.exceptions import APIException, ParseError
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response:
message = response.data
if isinstance(message, dict):
for error_key, error_description in message.iteritems():
if error_key in top_level_error_keys:
errors.append({error_key: error_description})
else:
if isinstance(error_description, basestring):
error_description = [error_description]
errors.extend([{'source': {'pointer': '/data/attributes/' + error_key}, 'detail': reason}
for reason in error_description])
else:
if isinstance(message, basestring):
message = [message]
errors.extend([{'detail': error} for error in message])
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
class InvalidFilterError(ParseError):
<|fim_middle|>
<|fim▁end|> | """Raised when client passes an invalid filter in the querystring."""
default_detail = 'Querystring contains an invalid filter.' |
<|file_name|>exceptions.py<|end_file_name|><|fim▁begin|>
from rest_framework import status
from rest_framework.exceptions import APIException, ParseError
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response:
<|fim_middle|>
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
class InvalidFilterError(ParseError):
"""Raised when client passes an invalid filter in the querystring."""
default_detail = 'Querystring contains an invalid filter.'
<|fim▁end|> | message = response.data
if isinstance(message, dict):
for error_key, error_description in message.iteritems():
if error_key in top_level_error_keys:
errors.append({error_key: error_description})
else:
if isinstance(error_description, basestring):
error_description = [error_description]
errors.extend([{'source': {'pointer': '/data/attributes/' + error_key}, 'detail': reason}
for reason in error_description])
else:
if isinstance(message, basestring):
message = [message]
errors.extend([{'detail': error} for error in message])
response.data = {'errors': errors} |
<|file_name|>exceptions.py<|end_file_name|><|fim▁begin|>
from rest_framework import status
from rest_framework.exceptions import APIException, ParseError
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response:
message = response.data
if isinstance(message, dict):
<|fim_middle|>
else:
if isinstance(message, basestring):
message = [message]
errors.extend([{'detail': error} for error in message])
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
class InvalidFilterError(ParseError):
"""Raised when client passes an invalid filter in the querystring."""
default_detail = 'Querystring contains an invalid filter.'
<|fim▁end|> | for error_key, error_description in message.iteritems():
if error_key in top_level_error_keys:
errors.append({error_key: error_description})
else:
if isinstance(error_description, basestring):
error_description = [error_description]
errors.extend([{'source': {'pointer': '/data/attributes/' + error_key}, 'detail': reason}
for reason in error_description]) |
<|file_name|>exceptions.py<|end_file_name|><|fim▁begin|>
from rest_framework import status
from rest_framework.exceptions import APIException, ParseError
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response:
message = response.data
if isinstance(message, dict):
for error_key, error_description in message.iteritems():
if error_key in top_level_error_keys:
<|fim_middle|>
else:
if isinstance(error_description, basestring):
error_description = [error_description]
errors.extend([{'source': {'pointer': '/data/attributes/' + error_key}, 'detail': reason}
for reason in error_description])
else:
if isinstance(message, basestring):
message = [message]
errors.extend([{'detail': error} for error in message])
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
class InvalidFilterError(ParseError):
"""Raised when client passes an invalid filter in the querystring."""
default_detail = 'Querystring contains an invalid filter.'
<|fim▁end|> | errors.append({error_key: error_description}) |
<|file_name|>exceptions.py<|end_file_name|><|fim▁begin|>
from rest_framework import status
from rest_framework.exceptions import APIException, ParseError
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response:
message = response.data
if isinstance(message, dict):
for error_key, error_description in message.iteritems():
if error_key in top_level_error_keys:
errors.append({error_key: error_description})
else:
<|fim_middle|>
else:
if isinstance(message, basestring):
message = [message]
errors.extend([{'detail': error} for error in message])
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
class InvalidFilterError(ParseError):
"""Raised when client passes an invalid filter in the querystring."""
default_detail = 'Querystring contains an invalid filter.'
<|fim▁end|> | if isinstance(error_description, basestring):
error_description = [error_description]
errors.extend([{'source': {'pointer': '/data/attributes/' + error_key}, 'detail': reason}
for reason in error_description]) |
<|file_name|>exceptions.py<|end_file_name|><|fim▁begin|>
from rest_framework import status
from rest_framework.exceptions import APIException, ParseError
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response:
message = response.data
if isinstance(message, dict):
for error_key, error_description in message.iteritems():
if error_key in top_level_error_keys:
errors.append({error_key: error_description})
else:
if isinstance(error_description, basestring):
<|fim_middle|>
errors.extend([{'source': {'pointer': '/data/attributes/' + error_key}, 'detail': reason}
for reason in error_description])
else:
if isinstance(message, basestring):
message = [message]
errors.extend([{'detail': error} for error in message])
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
class InvalidFilterError(ParseError):
"""Raised when client passes an invalid filter in the querystring."""
default_detail = 'Querystring contains an invalid filter.'
<|fim▁end|> | error_description = [error_description] |
<|file_name|>exceptions.py<|end_file_name|><|fim▁begin|>
from rest_framework import status
from rest_framework.exceptions import APIException, ParseError
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response:
message = response.data
if isinstance(message, dict):
for error_key, error_description in message.iteritems():
if error_key in top_level_error_keys:
errors.append({error_key: error_description})
else:
if isinstance(error_description, basestring):
error_description = [error_description]
errors.extend([{'source': {'pointer': '/data/attributes/' + error_key}, 'detail': reason}
for reason in error_description])
else:
<|fim_middle|>
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
class InvalidFilterError(ParseError):
"""Raised when client passes an invalid filter in the querystring."""
default_detail = 'Querystring contains an invalid filter.'
<|fim▁end|> | if isinstance(message, basestring):
message = [message]
errors.extend([{'detail': error} for error in message]) |
<|file_name|>exceptions.py<|end_file_name|><|fim▁begin|>
from rest_framework import status
from rest_framework.exceptions import APIException, ParseError
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response:
message = response.data
if isinstance(message, dict):
for error_key, error_description in message.iteritems():
if error_key in top_level_error_keys:
errors.append({error_key: error_description})
else:
if isinstance(error_description, basestring):
error_description = [error_description]
errors.extend([{'source': {'pointer': '/data/attributes/' + error_key}, 'detail': reason}
for reason in error_description])
else:
if isinstance(message, basestring):
<|fim_middle|>
errors.extend([{'detail': error} for error in message])
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
class InvalidFilterError(ParseError):
"""Raised when client passes an invalid filter in the querystring."""
default_detail = 'Querystring contains an invalid filter.'
<|fim▁end|> | message = [message] |
<|file_name|>exceptions.py<|end_file_name|><|fim▁begin|>
from rest_framework import status
from rest_framework.exceptions import APIException, ParseError
def <|fim_middle|>(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response:
message = response.data
if isinstance(message, dict):
for error_key, error_description in message.iteritems():
if error_key in top_level_error_keys:
errors.append({error_key: error_description})
else:
if isinstance(error_description, basestring):
error_description = [error_description]
errors.extend([{'source': {'pointer': '/data/attributes/' + error_key}, 'detail': reason}
for reason in error_description])
else:
if isinstance(message, basestring):
message = [message]
errors.extend([{'detail': error} for error in message])
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
class InvalidFilterError(ParseError):
"""Raised when client passes an invalid filter in the querystring."""
default_detail = 'Querystring contains an invalid filter.'
<|fim▁end|> | json_api_exception_handler |
<|file_name|>mobile_uploader.py<|end_file_name|><|fim▁begin|># Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at<|fim▁hole|># Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import apache_beam as beam
import logging
from typing import List, Dict, Any
from uploaders.google_ads.customer_match.abstract_uploader import GoogleAdsCustomerMatchAbstractUploaderDoFn
from uploaders import utils as utils
from models.execution import DestinationType, AccountConfig
from models.oauth_credentials import OAuthCredentials
class GoogleAdsCustomerMatchMobileUploaderDoFn(GoogleAdsCustomerMatchAbstractUploaderDoFn):
def get_list_definition(self, account_config: AccountConfig, destination_metadata: List[str]) -> Dict[str, Any]:
list_name = destination_metadata[0]
app_id = account_config.app_id
#overwrite app_id from default to custom
if len(destination_metadata) >=4 and len(destination_metadata[3]) > 0:
app_id = destination_metadata[3]
return {
'membership_status': 'OPEN',
'name': list_name,
'description': 'List created automatically by Megalista',
'membership_life_span': 10000,
'crm_based_user_list': {
'upload_key_type': 'MOBILE_ADVERTISING_ID', #CONTACT_INFO, CRM_ID, MOBILE_ADVERTISING_ID
'data_source_type': 'FIRST_PARTY',
'app_id': app_id
}
}
def get_row_keys(self) -> List[str]:
return ['mobile_id']
def get_action_type(self) -> DestinationType:
return DestinationType.ADS_CUSTOMER_MATCH_MOBILE_DEVICE_ID_UPLOAD<|fim▁end|> | #
# https://www.apache.org/licenses/LICENSE-2.0
# |
<|file_name|>mobile_uploader.py<|end_file_name|><|fim▁begin|># Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import apache_beam as beam
import logging
from typing import List, Dict, Any
from uploaders.google_ads.customer_match.abstract_uploader import GoogleAdsCustomerMatchAbstractUploaderDoFn
from uploaders import utils as utils
from models.execution import DestinationType, AccountConfig
from models.oauth_credentials import OAuthCredentials
class GoogleAdsCustomerMatchMobileUploaderDoFn(GoogleAdsCustomerMatchAbstractUploaderDoFn):
<|fim_middle|>
<|fim▁end|> | def get_list_definition(self, account_config: AccountConfig, destination_metadata: List[str]) -> Dict[str, Any]:
list_name = destination_metadata[0]
app_id = account_config.app_id
#overwrite app_id from default to custom
if len(destination_metadata) >=4 and len(destination_metadata[3]) > 0:
app_id = destination_metadata[3]
return {
'membership_status': 'OPEN',
'name': list_name,
'description': 'List created automatically by Megalista',
'membership_life_span': 10000,
'crm_based_user_list': {
'upload_key_type': 'MOBILE_ADVERTISING_ID', #CONTACT_INFO, CRM_ID, MOBILE_ADVERTISING_ID
'data_source_type': 'FIRST_PARTY',
'app_id': app_id
}
}
def get_row_keys(self) -> List[str]:
return ['mobile_id']
def get_action_type(self) -> DestinationType:
return DestinationType.ADS_CUSTOMER_MATCH_MOBILE_DEVICE_ID_UPLOAD |
<|file_name|>mobile_uploader.py<|end_file_name|><|fim▁begin|># Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import apache_beam as beam
import logging
from typing import List, Dict, Any
from uploaders.google_ads.customer_match.abstract_uploader import GoogleAdsCustomerMatchAbstractUploaderDoFn
from uploaders import utils as utils
from models.execution import DestinationType, AccountConfig
from models.oauth_credentials import OAuthCredentials
class GoogleAdsCustomerMatchMobileUploaderDoFn(GoogleAdsCustomerMatchAbstractUploaderDoFn):
def get_list_definition(self, account_config: AccountConfig, destination_metadata: List[str]) -> Dict[str, Any]:
<|fim_middle|>
def get_row_keys(self) -> List[str]:
return ['mobile_id']
def get_action_type(self) -> DestinationType:
return DestinationType.ADS_CUSTOMER_MATCH_MOBILE_DEVICE_ID_UPLOAD
<|fim▁end|> | list_name = destination_metadata[0]
app_id = account_config.app_id
#overwrite app_id from default to custom
if len(destination_metadata) >=4 and len(destination_metadata[3]) > 0:
app_id = destination_metadata[3]
return {
'membership_status': 'OPEN',
'name': list_name,
'description': 'List created automatically by Megalista',
'membership_life_span': 10000,
'crm_based_user_list': {
'upload_key_type': 'MOBILE_ADVERTISING_ID', #CONTACT_INFO, CRM_ID, MOBILE_ADVERTISING_ID
'data_source_type': 'FIRST_PARTY',
'app_id': app_id
}
} |
<|file_name|>mobile_uploader.py<|end_file_name|><|fim▁begin|># Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import apache_beam as beam
import logging
from typing import List, Dict, Any
from uploaders.google_ads.customer_match.abstract_uploader import GoogleAdsCustomerMatchAbstractUploaderDoFn
from uploaders import utils as utils
from models.execution import DestinationType, AccountConfig
from models.oauth_credentials import OAuthCredentials
class GoogleAdsCustomerMatchMobileUploaderDoFn(GoogleAdsCustomerMatchAbstractUploaderDoFn):
def get_list_definition(self, account_config: AccountConfig, destination_metadata: List[str]) -> Dict[str, Any]:
list_name = destination_metadata[0]
app_id = account_config.app_id
#overwrite app_id from default to custom
if len(destination_metadata) >=4 and len(destination_metadata[3]) > 0:
app_id = destination_metadata[3]
return {
'membership_status': 'OPEN',
'name': list_name,
'description': 'List created automatically by Megalista',
'membership_life_span': 10000,
'crm_based_user_list': {
'upload_key_type': 'MOBILE_ADVERTISING_ID', #CONTACT_INFO, CRM_ID, MOBILE_ADVERTISING_ID
'data_source_type': 'FIRST_PARTY',
'app_id': app_id
}
}
def get_row_keys(self) -> List[str]:
<|fim_middle|>
def get_action_type(self) -> DestinationType:
return DestinationType.ADS_CUSTOMER_MATCH_MOBILE_DEVICE_ID_UPLOAD
<|fim▁end|> | return ['mobile_id'] |
<|file_name|>mobile_uploader.py<|end_file_name|><|fim▁begin|># Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import apache_beam as beam
import logging
from typing import List, Dict, Any
from uploaders.google_ads.customer_match.abstract_uploader import GoogleAdsCustomerMatchAbstractUploaderDoFn
from uploaders import utils as utils
from models.execution import DestinationType, AccountConfig
from models.oauth_credentials import OAuthCredentials
class GoogleAdsCustomerMatchMobileUploaderDoFn(GoogleAdsCustomerMatchAbstractUploaderDoFn):
def get_list_definition(self, account_config: AccountConfig, destination_metadata: List[str]) -> Dict[str, Any]:
list_name = destination_metadata[0]
app_id = account_config.app_id
#overwrite app_id from default to custom
if len(destination_metadata) >=4 and len(destination_metadata[3]) > 0:
app_id = destination_metadata[3]
return {
'membership_status': 'OPEN',
'name': list_name,
'description': 'List created automatically by Megalista',
'membership_life_span': 10000,
'crm_based_user_list': {
'upload_key_type': 'MOBILE_ADVERTISING_ID', #CONTACT_INFO, CRM_ID, MOBILE_ADVERTISING_ID
'data_source_type': 'FIRST_PARTY',
'app_id': app_id
}
}
def get_row_keys(self) -> List[str]:
return ['mobile_id']
def get_action_type(self) -> DestinationType:
<|fim_middle|>
<|fim▁end|> | return DestinationType.ADS_CUSTOMER_MATCH_MOBILE_DEVICE_ID_UPLOAD |
<|file_name|>mobile_uploader.py<|end_file_name|><|fim▁begin|># Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import apache_beam as beam
import logging
from typing import List, Dict, Any
from uploaders.google_ads.customer_match.abstract_uploader import GoogleAdsCustomerMatchAbstractUploaderDoFn
from uploaders import utils as utils
from models.execution import DestinationType, AccountConfig
from models.oauth_credentials import OAuthCredentials
class GoogleAdsCustomerMatchMobileUploaderDoFn(GoogleAdsCustomerMatchAbstractUploaderDoFn):
def get_list_definition(self, account_config: AccountConfig, destination_metadata: List[str]) -> Dict[str, Any]:
list_name = destination_metadata[0]
app_id = account_config.app_id
#overwrite app_id from default to custom
if len(destination_metadata) >=4 and len(destination_metadata[3]) > 0:
<|fim_middle|>
return {
'membership_status': 'OPEN',
'name': list_name,
'description': 'List created automatically by Megalista',
'membership_life_span': 10000,
'crm_based_user_list': {
'upload_key_type': 'MOBILE_ADVERTISING_ID', #CONTACT_INFO, CRM_ID, MOBILE_ADVERTISING_ID
'data_source_type': 'FIRST_PARTY',
'app_id': app_id
}
}
def get_row_keys(self) -> List[str]:
return ['mobile_id']
def get_action_type(self) -> DestinationType:
return DestinationType.ADS_CUSTOMER_MATCH_MOBILE_DEVICE_ID_UPLOAD
<|fim▁end|> | app_id = destination_metadata[3] |
<|file_name|>mobile_uploader.py<|end_file_name|><|fim▁begin|># Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import apache_beam as beam
import logging
from typing import List, Dict, Any
from uploaders.google_ads.customer_match.abstract_uploader import GoogleAdsCustomerMatchAbstractUploaderDoFn
from uploaders import utils as utils
from models.execution import DestinationType, AccountConfig
from models.oauth_credentials import OAuthCredentials
class GoogleAdsCustomerMatchMobileUploaderDoFn(GoogleAdsCustomerMatchAbstractUploaderDoFn):
def <|fim_middle|>(self, account_config: AccountConfig, destination_metadata: List[str]) -> Dict[str, Any]:
list_name = destination_metadata[0]
app_id = account_config.app_id
#overwrite app_id from default to custom
if len(destination_metadata) >=4 and len(destination_metadata[3]) > 0:
app_id = destination_metadata[3]
return {
'membership_status': 'OPEN',
'name': list_name,
'description': 'List created automatically by Megalista',
'membership_life_span': 10000,
'crm_based_user_list': {
'upload_key_type': 'MOBILE_ADVERTISING_ID', #CONTACT_INFO, CRM_ID, MOBILE_ADVERTISING_ID
'data_source_type': 'FIRST_PARTY',
'app_id': app_id
}
}
def get_row_keys(self) -> List[str]:
return ['mobile_id']
def get_action_type(self) -> DestinationType:
return DestinationType.ADS_CUSTOMER_MATCH_MOBILE_DEVICE_ID_UPLOAD
<|fim▁end|> | get_list_definition |
<|file_name|>mobile_uploader.py<|end_file_name|><|fim▁begin|># Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import apache_beam as beam
import logging
from typing import List, Dict, Any
from uploaders.google_ads.customer_match.abstract_uploader import GoogleAdsCustomerMatchAbstractUploaderDoFn
from uploaders import utils as utils
from models.execution import DestinationType, AccountConfig
from models.oauth_credentials import OAuthCredentials
class GoogleAdsCustomerMatchMobileUploaderDoFn(GoogleAdsCustomerMatchAbstractUploaderDoFn):
def get_list_definition(self, account_config: AccountConfig, destination_metadata: List[str]) -> Dict[str, Any]:
list_name = destination_metadata[0]
app_id = account_config.app_id
#overwrite app_id from default to custom
if len(destination_metadata) >=4 and len(destination_metadata[3]) > 0:
app_id = destination_metadata[3]
return {
'membership_status': 'OPEN',
'name': list_name,
'description': 'List created automatically by Megalista',
'membership_life_span': 10000,
'crm_based_user_list': {
'upload_key_type': 'MOBILE_ADVERTISING_ID', #CONTACT_INFO, CRM_ID, MOBILE_ADVERTISING_ID
'data_source_type': 'FIRST_PARTY',
'app_id': app_id
}
}
def <|fim_middle|>(self) -> List[str]:
return ['mobile_id']
def get_action_type(self) -> DestinationType:
return DestinationType.ADS_CUSTOMER_MATCH_MOBILE_DEVICE_ID_UPLOAD
<|fim▁end|> | get_row_keys |
<|file_name|>mobile_uploader.py<|end_file_name|><|fim▁begin|># Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import apache_beam as beam
import logging
from typing import List, Dict, Any
from uploaders.google_ads.customer_match.abstract_uploader import GoogleAdsCustomerMatchAbstractUploaderDoFn
from uploaders import utils as utils
from models.execution import DestinationType, AccountConfig
from models.oauth_credentials import OAuthCredentials
class GoogleAdsCustomerMatchMobileUploaderDoFn(GoogleAdsCustomerMatchAbstractUploaderDoFn):
def get_list_definition(self, account_config: AccountConfig, destination_metadata: List[str]) -> Dict[str, Any]:
list_name = destination_metadata[0]
app_id = account_config.app_id
#overwrite app_id from default to custom
if len(destination_metadata) >=4 and len(destination_metadata[3]) > 0:
app_id = destination_metadata[3]
return {
'membership_status': 'OPEN',
'name': list_name,
'description': 'List created automatically by Megalista',
'membership_life_span': 10000,
'crm_based_user_list': {
'upload_key_type': 'MOBILE_ADVERTISING_ID', #CONTACT_INFO, CRM_ID, MOBILE_ADVERTISING_ID
'data_source_type': 'FIRST_PARTY',
'app_id': app_id
}
}
def get_row_keys(self) -> List[str]:
return ['mobile_id']
def <|fim_middle|>(self) -> DestinationType:
return DestinationType.ADS_CUSTOMER_MATCH_MOBILE_DEVICE_ID_UPLOAD
<|fim▁end|> | get_action_type |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|> | from opencvBuilder import exists,generate |
<|file_name|>authentication.py<|end_file_name|><|fim▁begin|>from . import config
from django.shortcuts import render
from mwoauth import ConsumerToken, Handshaker, tokens
def requests_handshaker():
consumer_key = config.OAUTH_CONSUMER_KEY
consumer_secret = config.OAUTH_CONSUMER_SECRET<|fim▁hole|>def get_username(request):
handshaker = requests_handshaker()
if 'access_token_key' in request.session:
access_key = request.session['access_token_key'].encode('utf-8')
access_secret = request.session['access_token_secret'].encode('utf-8')
access_token = tokens.AccessToken(key=access_key, secret=access_secret)
return handshaker.identify(access_token)['username']
else:
return None<|fim▁end|> | consumer_token = ConsumerToken(consumer_key, consumer_secret)
return Handshaker("https://meta.wikimedia.org/w/index.php", consumer_token)
|
<|file_name|>authentication.py<|end_file_name|><|fim▁begin|>from . import config
from django.shortcuts import render
from mwoauth import ConsumerToken, Handshaker, tokens
def requests_handshaker():
<|fim_middle|>
def get_username(request):
handshaker = requests_handshaker()
if 'access_token_key' in request.session:
access_key = request.session['access_token_key'].encode('utf-8')
access_secret = request.session['access_token_secret'].encode('utf-8')
access_token = tokens.AccessToken(key=access_key, secret=access_secret)
return handshaker.identify(access_token)['username']
else:
return None
<|fim▁end|> | consumer_key = config.OAUTH_CONSUMER_KEY
consumer_secret = config.OAUTH_CONSUMER_SECRET
consumer_token = ConsumerToken(consumer_key, consumer_secret)
return Handshaker("https://meta.wikimedia.org/w/index.php", consumer_token) |
<|file_name|>authentication.py<|end_file_name|><|fim▁begin|>from . import config
from django.shortcuts import render
from mwoauth import ConsumerToken, Handshaker, tokens
def requests_handshaker():
consumer_key = config.OAUTH_CONSUMER_KEY
consumer_secret = config.OAUTH_CONSUMER_SECRET
consumer_token = ConsumerToken(consumer_key, consumer_secret)
return Handshaker("https://meta.wikimedia.org/w/index.php", consumer_token)
def get_username(request):
<|fim_middle|>
<|fim▁end|> | handshaker = requests_handshaker()
if 'access_token_key' in request.session:
access_key = request.session['access_token_key'].encode('utf-8')
access_secret = request.session['access_token_secret'].encode('utf-8')
access_token = tokens.AccessToken(key=access_key, secret=access_secret)
return handshaker.identify(access_token)['username']
else:
return None |
<|file_name|>authentication.py<|end_file_name|><|fim▁begin|>from . import config
from django.shortcuts import render
from mwoauth import ConsumerToken, Handshaker, tokens
def requests_handshaker():
consumer_key = config.OAUTH_CONSUMER_KEY
consumer_secret = config.OAUTH_CONSUMER_SECRET
consumer_token = ConsumerToken(consumer_key, consumer_secret)
return Handshaker("https://meta.wikimedia.org/w/index.php", consumer_token)
def get_username(request):
handshaker = requests_handshaker()
if 'access_token_key' in request.session:
<|fim_middle|>
else:
return None
<|fim▁end|> | access_key = request.session['access_token_key'].encode('utf-8')
access_secret = request.session['access_token_secret'].encode('utf-8')
access_token = tokens.AccessToken(key=access_key, secret=access_secret)
return handshaker.identify(access_token)['username'] |
<|file_name|>authentication.py<|end_file_name|><|fim▁begin|>from . import config
from django.shortcuts import render
from mwoauth import ConsumerToken, Handshaker, tokens
def requests_handshaker():
consumer_key = config.OAUTH_CONSUMER_KEY
consumer_secret = config.OAUTH_CONSUMER_SECRET
consumer_token = ConsumerToken(consumer_key, consumer_secret)
return Handshaker("https://meta.wikimedia.org/w/index.php", consumer_token)
def get_username(request):
handshaker = requests_handshaker()
if 'access_token_key' in request.session:
access_key = request.session['access_token_key'].encode('utf-8')
access_secret = request.session['access_token_secret'].encode('utf-8')
access_token = tokens.AccessToken(key=access_key, secret=access_secret)
return handshaker.identify(access_token)['username']
else:
<|fim_middle|>
<|fim▁end|> | return None |
<|file_name|>authentication.py<|end_file_name|><|fim▁begin|>from . import config
from django.shortcuts import render
from mwoauth import ConsumerToken, Handshaker, tokens
def <|fim_middle|>():
consumer_key = config.OAUTH_CONSUMER_KEY
consumer_secret = config.OAUTH_CONSUMER_SECRET
consumer_token = ConsumerToken(consumer_key, consumer_secret)
return Handshaker("https://meta.wikimedia.org/w/index.php", consumer_token)
def get_username(request):
handshaker = requests_handshaker()
if 'access_token_key' in request.session:
access_key = request.session['access_token_key'].encode('utf-8')
access_secret = request.session['access_token_secret'].encode('utf-8')
access_token = tokens.AccessToken(key=access_key, secret=access_secret)
return handshaker.identify(access_token)['username']
else:
return None
<|fim▁end|> | requests_handshaker |
<|file_name|>authentication.py<|end_file_name|><|fim▁begin|>from . import config
from django.shortcuts import render
from mwoauth import ConsumerToken, Handshaker, tokens
def requests_handshaker():
consumer_key = config.OAUTH_CONSUMER_KEY
consumer_secret = config.OAUTH_CONSUMER_SECRET
consumer_token = ConsumerToken(consumer_key, consumer_secret)
return Handshaker("https://meta.wikimedia.org/w/index.php", consumer_token)
def <|fim_middle|>(request):
handshaker = requests_handshaker()
if 'access_token_key' in request.session:
access_key = request.session['access_token_key'].encode('utf-8')
access_secret = request.session['access_token_secret'].encode('utf-8')
access_token = tokens.AccessToken(key=access_key, secret=access_secret)
return handshaker.identify(access_token)['username']
else:
return None
<|fim▁end|> | get_username |
<|file_name|>media_operations.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import os
import arrow
import magic
import hashlib
import logging
import requests
from io import BytesIO
from PIL import Image
from flask import json
from .image import get_meta
from .video import get_meta as video_meta
import base64
from superdesk.errors import SuperdeskApiError
logger = logging.getLogger(__name__)
def hash_file(afile, hasher, blocksize=65536):
buf = afile.read(blocksize)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(blocksize)
return hasher.hexdigest()
def get_file_name(file):
return hash_file(file, hashlib.sha256())
def download_file_from_url(url):
rv = requests.get(url, timeout=15)
if rv.status_code not in (200, 201):
raise SuperdeskApiError.internalError('Failed to retrieve file from URL: %s' % url)
mime = magic.from_buffer(rv.content, mime=True).decode('UTF-8')
ext = mime.split('/')[1]
name = 'stub.' + ext
return BytesIO(rv.content), name, mime
def download_file_from_encoded_str(encoded_str):
content = encoded_str.split(';base64,')
mime = content[0].split(':')[1]
ext = content[0].split('/')[1]
name = 'web_capture.' + ext
content = base64.b64decode(content[1])
return BytesIO(content), name, mime
def process_file_from_stream(content, content_type=None):
content_type = content_type or content.content_type
content = BytesIO(content.read())
if 'application/' in content_type:
content_type = magic.from_buffer(content.getvalue(), mime=True).decode('UTF-8')
content.seek(0)
file_type, ext = content_type.split('/')
try:
metadata = process_file(content, file_type)
except OSError: # error from PIL when image is supposed to be an image but is not.
raise SuperdeskApiError.internalError('Failed to process file')
file_name = get_file_name(content)
content.seek(0)
metadata = encode_metadata(metadata)
metadata.update({'length': json.dumps(len(content.getvalue()))})
return file_name, content_type, metadata
def encode_metadata(metadata):
return dict((k.lower(), json.dumps(v)) for k, v in metadata.items())
<|fim▁hole|>
def decode_val(string_val):
"""Format dates that elastic will try to convert automatically."""
val = json.loads(string_val)
try:
arrow.get(val, 'YYYY-MM-DD') # test if it will get matched by elastic
return str(arrow.get(val))
except (Exception):
return val
def process_file(content, type):
if type == 'image':
return process_image(content, type)
if type in ('audio', 'video'):
return process_video(content, type)
return {}
def process_video(content, type):
content.seek(0)
meta = video_meta(content)
content.seek(0)
return meta
def process_image(content, type):
content.seek(0)
meta = get_meta(content)
content.seek(0)
return meta
def crop_image(content, file_name, cropping_data):
if cropping_data:
file_ext = os.path.splitext(file_name)[1][1:]
if file_ext in ('JPG', 'jpg'):
file_ext = 'jpeg'
logger.debug('Opened image from stream, going to crop it s')
content.seek(0)
img = Image.open(content)
cropped = img.crop(cropping_data)
logger.debug('Cropped image from stream, going to save it')
try:
out = BytesIO()
cropped.save(out, file_ext)
out.seek(0)
return (True, out)
except Exception as io:
logger.exception(io)
return (False, content)<|fim▁end|> |
def decode_metadata(metadata):
return dict((k.lower(), decode_val(v)) for k, v in metadata.items()) |
<|file_name|>media_operations.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import os
import arrow
import magic
import hashlib
import logging
import requests
from io import BytesIO
from PIL import Image
from flask import json
from .image import get_meta
from .video import get_meta as video_meta
import base64
from superdesk.errors import SuperdeskApiError
logger = logging.getLogger(__name__)
def hash_file(afile, hasher, blocksize=65536):
<|fim_middle|>
def get_file_name(file):
return hash_file(file, hashlib.sha256())
def download_file_from_url(url):
rv = requests.get(url, timeout=15)
if rv.status_code not in (200, 201):
raise SuperdeskApiError.internalError('Failed to retrieve file from URL: %s' % url)
mime = magic.from_buffer(rv.content, mime=True).decode('UTF-8')
ext = mime.split('/')[1]
name = 'stub.' + ext
return BytesIO(rv.content), name, mime
def download_file_from_encoded_str(encoded_str):
content = encoded_str.split(';base64,')
mime = content[0].split(':')[1]
ext = content[0].split('/')[1]
name = 'web_capture.' + ext
content = base64.b64decode(content[1])
return BytesIO(content), name, mime
def process_file_from_stream(content, content_type=None):
content_type = content_type or content.content_type
content = BytesIO(content.read())
if 'application/' in content_type:
content_type = magic.from_buffer(content.getvalue(), mime=True).decode('UTF-8')
content.seek(0)
file_type, ext = content_type.split('/')
try:
metadata = process_file(content, file_type)
except OSError: # error from PIL when image is supposed to be an image but is not.
raise SuperdeskApiError.internalError('Failed to process file')
file_name = get_file_name(content)
content.seek(0)
metadata = encode_metadata(metadata)
metadata.update({'length': json.dumps(len(content.getvalue()))})
return file_name, content_type, metadata
def encode_metadata(metadata):
return dict((k.lower(), json.dumps(v)) for k, v in metadata.items())
def decode_metadata(metadata):
return dict((k.lower(), decode_val(v)) for k, v in metadata.items())
def decode_val(string_val):
"""Format dates that elastic will try to convert automatically."""
val = json.loads(string_val)
try:
arrow.get(val, 'YYYY-MM-DD') # test if it will get matched by elastic
return str(arrow.get(val))
except (Exception):
return val
def process_file(content, type):
if type == 'image':
return process_image(content, type)
if type in ('audio', 'video'):
return process_video(content, type)
return {}
def process_video(content, type):
content.seek(0)
meta = video_meta(content)
content.seek(0)
return meta
def process_image(content, type):
content.seek(0)
meta = get_meta(content)
content.seek(0)
return meta
def crop_image(content, file_name, cropping_data):
if cropping_data:
file_ext = os.path.splitext(file_name)[1][1:]
if file_ext in ('JPG', 'jpg'):
file_ext = 'jpeg'
logger.debug('Opened image from stream, going to crop it s')
content.seek(0)
img = Image.open(content)
cropped = img.crop(cropping_data)
logger.debug('Cropped image from stream, going to save it')
try:
out = BytesIO()
cropped.save(out, file_ext)
out.seek(0)
return (True, out)
except Exception as io:
logger.exception(io)
return (False, content)
<|fim▁end|> | buf = afile.read(blocksize)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(blocksize)
return hasher.hexdigest() |
<|file_name|>media_operations.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import os
import arrow
import magic
import hashlib
import logging
import requests
from io import BytesIO
from PIL import Image
from flask import json
from .image import get_meta
from .video import get_meta as video_meta
import base64
from superdesk.errors import SuperdeskApiError
logger = logging.getLogger(__name__)
def hash_file(afile, hasher, blocksize=65536):
buf = afile.read(blocksize)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(blocksize)
return hasher.hexdigest()
def get_file_name(file):
<|fim_middle|>
def download_file_from_url(url):
rv = requests.get(url, timeout=15)
if rv.status_code not in (200, 201):
raise SuperdeskApiError.internalError('Failed to retrieve file from URL: %s' % url)
mime = magic.from_buffer(rv.content, mime=True).decode('UTF-8')
ext = mime.split('/')[1]
name = 'stub.' + ext
return BytesIO(rv.content), name, mime
def download_file_from_encoded_str(encoded_str):
content = encoded_str.split(';base64,')
mime = content[0].split(':')[1]
ext = content[0].split('/')[1]
name = 'web_capture.' + ext
content = base64.b64decode(content[1])
return BytesIO(content), name, mime
def process_file_from_stream(content, content_type=None):
content_type = content_type or content.content_type
content = BytesIO(content.read())
if 'application/' in content_type:
content_type = magic.from_buffer(content.getvalue(), mime=True).decode('UTF-8')
content.seek(0)
file_type, ext = content_type.split('/')
try:
metadata = process_file(content, file_type)
except OSError: # error from PIL when image is supposed to be an image but is not.
raise SuperdeskApiError.internalError('Failed to process file')
file_name = get_file_name(content)
content.seek(0)
metadata = encode_metadata(metadata)
metadata.update({'length': json.dumps(len(content.getvalue()))})
return file_name, content_type, metadata
def encode_metadata(metadata):
return dict((k.lower(), json.dumps(v)) for k, v in metadata.items())
def decode_metadata(metadata):
return dict((k.lower(), decode_val(v)) for k, v in metadata.items())
def decode_val(string_val):
"""Format dates that elastic will try to convert automatically."""
val = json.loads(string_val)
try:
arrow.get(val, 'YYYY-MM-DD') # test if it will get matched by elastic
return str(arrow.get(val))
except (Exception):
return val
def process_file(content, type):
if type == 'image':
return process_image(content, type)
if type in ('audio', 'video'):
return process_video(content, type)
return {}
def process_video(content, type):
content.seek(0)
meta = video_meta(content)
content.seek(0)
return meta
def process_image(content, type):
content.seek(0)
meta = get_meta(content)
content.seek(0)
return meta
def crop_image(content, file_name, cropping_data):
if cropping_data:
file_ext = os.path.splitext(file_name)[1][1:]
if file_ext in ('JPG', 'jpg'):
file_ext = 'jpeg'
logger.debug('Opened image from stream, going to crop it s')
content.seek(0)
img = Image.open(content)
cropped = img.crop(cropping_data)
logger.debug('Cropped image from stream, going to save it')
try:
out = BytesIO()
cropped.save(out, file_ext)
out.seek(0)
return (True, out)
except Exception as io:
logger.exception(io)
return (False, content)
<|fim▁end|> | return hash_file(file, hashlib.sha256()) |
<|file_name|>media_operations.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import os
import arrow
import magic
import hashlib
import logging
import requests
from io import BytesIO
from PIL import Image
from flask import json
from .image import get_meta
from .video import get_meta as video_meta
import base64
from superdesk.errors import SuperdeskApiError
logger = logging.getLogger(__name__)
def hash_file(afile, hasher, blocksize=65536):
buf = afile.read(blocksize)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(blocksize)
return hasher.hexdigest()
def get_file_name(file):
return hash_file(file, hashlib.sha256())
def download_file_from_url(url):
<|fim_middle|>
def download_file_from_encoded_str(encoded_str):
content = encoded_str.split(';base64,')
mime = content[0].split(':')[1]
ext = content[0].split('/')[1]
name = 'web_capture.' + ext
content = base64.b64decode(content[1])
return BytesIO(content), name, mime
def process_file_from_stream(content, content_type=None):
content_type = content_type or content.content_type
content = BytesIO(content.read())
if 'application/' in content_type:
content_type = magic.from_buffer(content.getvalue(), mime=True).decode('UTF-8')
content.seek(0)
file_type, ext = content_type.split('/')
try:
metadata = process_file(content, file_type)
except OSError: # error from PIL when image is supposed to be an image but is not.
raise SuperdeskApiError.internalError('Failed to process file')
file_name = get_file_name(content)
content.seek(0)
metadata = encode_metadata(metadata)
metadata.update({'length': json.dumps(len(content.getvalue()))})
return file_name, content_type, metadata
def encode_metadata(metadata):
return dict((k.lower(), json.dumps(v)) for k, v in metadata.items())
def decode_metadata(metadata):
return dict((k.lower(), decode_val(v)) for k, v in metadata.items())
def decode_val(string_val):
"""Format dates that elastic will try to convert automatically."""
val = json.loads(string_val)
try:
arrow.get(val, 'YYYY-MM-DD') # test if it will get matched by elastic
return str(arrow.get(val))
except (Exception):
return val
def process_file(content, type):
if type == 'image':
return process_image(content, type)
if type in ('audio', 'video'):
return process_video(content, type)
return {}
def process_video(content, type):
content.seek(0)
meta = video_meta(content)
content.seek(0)
return meta
def process_image(content, type):
content.seek(0)
meta = get_meta(content)
content.seek(0)
return meta
def crop_image(content, file_name, cropping_data):
if cropping_data:
file_ext = os.path.splitext(file_name)[1][1:]
if file_ext in ('JPG', 'jpg'):
file_ext = 'jpeg'
logger.debug('Opened image from stream, going to crop it s')
content.seek(0)
img = Image.open(content)
cropped = img.crop(cropping_data)
logger.debug('Cropped image from stream, going to save it')
try:
out = BytesIO()
cropped.save(out, file_ext)
out.seek(0)
return (True, out)
except Exception as io:
logger.exception(io)
return (False, content)
<|fim▁end|> | rv = requests.get(url, timeout=15)
if rv.status_code not in (200, 201):
raise SuperdeskApiError.internalError('Failed to retrieve file from URL: %s' % url)
mime = magic.from_buffer(rv.content, mime=True).decode('UTF-8')
ext = mime.split('/')[1]
name = 'stub.' + ext
return BytesIO(rv.content), name, mime |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.