prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>DistributedGoofySpeedwayAI.py<|end_file_name|><|fim▁begin|>from otp.ai.AIBaseGlobal import *
import DistributedCCharBaseAI
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from direct.task import Task
import random
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
import CharStateDatasAI
class DistributedGoofySpeedwayAI(DistributedCCharBaseAI.DistributedCCharBaseAI):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedGoofySpeedwayAI')
def __init__(self, air):
DistributedCCharBaseAI.DistributedCCharBaseAI.__init__(self, air, TTLocalizer.Goofy)
self.fsm = ClassicFSM.ClassicFSM('DistributedGoofySpeedwayAI', [State.State('Off', self.enterOff, self.exitOff, ['Lonely', 'TransitionToCostume', 'Walk']),
State.State('Lonely', self.enterLonely, self.exitLonely, ['Chatty', 'Walk', 'TransitionToCostume']),
State.State('Chatty', self.enterChatty, self.exitChatty, ['Lonely', 'Walk', 'TransitionToCostume']),
State.State('Walk', self.enterWalk, self.exitWalk, ['Lonely', 'Chatty', 'TransitionToCostume']),
State.State('TransitionToCostume', self.enterTransitionToCostume, self.exitTransitionToCostume, ['Off'])], 'Off', 'Off')
self.fsm.enterInitialState()
self.handleHolidays()
def delete(self):
self.fsm.requestFinalState()
DistributedCCharBaseAI.DistributedCCharBaseAI.delete(self)
self.lonelyDoneEvent = None
self.lonely = None
self.chattyDoneEvent = None
self.chatty = None
self.walkDoneEvent = None
self.walk = None
return
def generate(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.generate(self)
name = self.getName()
self.lonelyDoneEvent = self.taskName(name + '-lonely-done')
self.lonely = CharStateDatasAI.CharLonelyStateAI(self.lonelyDoneEvent, self)
self.chattyDoneEvent = self.taskName(name + '-chatty-done')
self.chatty = CharStateDatasAI.CharChattyStateAI(self.chattyDoneEvent, self)
self.walkDoneEvent = self.taskName(name + '-walk-done')
if self.diffPath == None:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self)
else:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self, self.diffPath)
return
def walkSpeed(self):
return ToontownGlobals.GoofySpeed
def start(self):
self.fsm.request('Lonely')
def __decideNextState(self, doneStatus):
if self.transitionToCostume == 1:
curWalkNode = self.walk.getDestNode()
if simbase.air.holidayManager:
if ToontownGlobals.HALLOWEEN_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
elif ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
else:
self.notify.warning('transitionToCostume == 1 but no costume holiday')
else:
self.notify.warning('transitionToCostume == 1 but no holiday Manager')
if doneStatus['state'] == 'lonely' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'chatty' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'walk' and doneStatus['status'] == 'done':
if len(self.nearbyAvatars) > 0:
self.fsm.request('Chatty')
else:
self.fsm.request('Lonely')
def enterOff(self):
pass
def exitOff(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.exitOff(self)
def enterLonely(self):
self.lonely.enter()
self.acceptOnce(self.lonelyDoneEvent, self.__decideNextState)
def exitLonely(self):
self.ignore(self.lonelyDoneEvent)
self.lonely.exit()
def __goForAWalk(self, task):
self.notify.debug('going for a walk')
self.fsm.request('Walk')
return Task.done
def enterChatty(self):
self.chatty.enter()
self.acceptOnce(self.chattyDoneEvent, self.__decideNextState)
def exitChatty(self):
self.ignore(self.chattyDoneEvent)
self.chatty.exit()
def enterWalk(self):
self.notify.debug('going for a walk')
self.walk.enter()
self.acceptOnce(self.walkDoneEvent, self.__decideNextState)
def exitWalk(self):
self.ignore(self.walkDoneEvent)
self.walk.exit()
def avatarEnterNextState(self):
if len(self.nearbyAvatars) == 1:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Chatty')
else:
self.notify.debug('avatarEnterNextState: in walk state')
else:
self.notify.debug('avatarEnterNextState: num avatars: ' + str(len(self.nearbyAvatars)))
def avatarExitNextState(self):
if len(self.nearbyAvatars) == 0:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Lonely')
def handleHolidays(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.handleHolidays(self)
if hasattr(simbase.air, 'holidayManager'):
if ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays:
if simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES] != None and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].getRunningState():
self.diffPath = TTLocalizer.Donald
return
def getCCLocation(self):
if self.diffPath == None:
<|fim_middle|>
else:
return 0
return
def enterTransitionToCostume(self):
pass
def exitTransitionToCostume(self):
pass
<|fim▁end|> | return 1 |
<|file_name|>DistributedGoofySpeedwayAI.py<|end_file_name|><|fim▁begin|>from otp.ai.AIBaseGlobal import *
import DistributedCCharBaseAI
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from direct.task import Task
import random
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
import CharStateDatasAI
class DistributedGoofySpeedwayAI(DistributedCCharBaseAI.DistributedCCharBaseAI):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedGoofySpeedwayAI')
def __init__(self, air):
DistributedCCharBaseAI.DistributedCCharBaseAI.__init__(self, air, TTLocalizer.Goofy)
self.fsm = ClassicFSM.ClassicFSM('DistributedGoofySpeedwayAI', [State.State('Off', self.enterOff, self.exitOff, ['Lonely', 'TransitionToCostume', 'Walk']),
State.State('Lonely', self.enterLonely, self.exitLonely, ['Chatty', 'Walk', 'TransitionToCostume']),
State.State('Chatty', self.enterChatty, self.exitChatty, ['Lonely', 'Walk', 'TransitionToCostume']),
State.State('Walk', self.enterWalk, self.exitWalk, ['Lonely', 'Chatty', 'TransitionToCostume']),
State.State('TransitionToCostume', self.enterTransitionToCostume, self.exitTransitionToCostume, ['Off'])], 'Off', 'Off')
self.fsm.enterInitialState()
self.handleHolidays()
def delete(self):
self.fsm.requestFinalState()
DistributedCCharBaseAI.DistributedCCharBaseAI.delete(self)
self.lonelyDoneEvent = None
self.lonely = None
self.chattyDoneEvent = None
self.chatty = None
self.walkDoneEvent = None
self.walk = None
return
def generate(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.generate(self)
name = self.getName()
self.lonelyDoneEvent = self.taskName(name + '-lonely-done')
self.lonely = CharStateDatasAI.CharLonelyStateAI(self.lonelyDoneEvent, self)
self.chattyDoneEvent = self.taskName(name + '-chatty-done')
self.chatty = CharStateDatasAI.CharChattyStateAI(self.chattyDoneEvent, self)
self.walkDoneEvent = self.taskName(name + '-walk-done')
if self.diffPath == None:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self)
else:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self, self.diffPath)
return
def walkSpeed(self):
return ToontownGlobals.GoofySpeed
def start(self):
self.fsm.request('Lonely')
def __decideNextState(self, doneStatus):
if self.transitionToCostume == 1:
curWalkNode = self.walk.getDestNode()
if simbase.air.holidayManager:
if ToontownGlobals.HALLOWEEN_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
elif ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
else:
self.notify.warning('transitionToCostume == 1 but no costume holiday')
else:
self.notify.warning('transitionToCostume == 1 but no holiday Manager')
if doneStatus['state'] == 'lonely' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'chatty' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'walk' and doneStatus['status'] == 'done':
if len(self.nearbyAvatars) > 0:
self.fsm.request('Chatty')
else:
self.fsm.request('Lonely')
def enterOff(self):
pass
def exitOff(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.exitOff(self)
def enterLonely(self):
self.lonely.enter()
self.acceptOnce(self.lonelyDoneEvent, self.__decideNextState)
def exitLonely(self):
self.ignore(self.lonelyDoneEvent)
self.lonely.exit()
def __goForAWalk(self, task):
self.notify.debug('going for a walk')
self.fsm.request('Walk')
return Task.done
def enterChatty(self):
self.chatty.enter()
self.acceptOnce(self.chattyDoneEvent, self.__decideNextState)
def exitChatty(self):
self.ignore(self.chattyDoneEvent)
self.chatty.exit()
def enterWalk(self):
self.notify.debug('going for a walk')
self.walk.enter()
self.acceptOnce(self.walkDoneEvent, self.__decideNextState)
def exitWalk(self):
self.ignore(self.walkDoneEvent)
self.walk.exit()
def avatarEnterNextState(self):
if len(self.nearbyAvatars) == 1:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Chatty')
else:
self.notify.debug('avatarEnterNextState: in walk state')
else:
self.notify.debug('avatarEnterNextState: num avatars: ' + str(len(self.nearbyAvatars)))
def avatarExitNextState(self):
if len(self.nearbyAvatars) == 0:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Lonely')
def handleHolidays(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.handleHolidays(self)
if hasattr(simbase.air, 'holidayManager'):
if ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays:
if simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES] != None and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].getRunningState():
self.diffPath = TTLocalizer.Donald
return
def getCCLocation(self):
if self.diffPath == None:
return 1
else:
<|fim_middle|>
return
def enterTransitionToCostume(self):
pass
def exitTransitionToCostume(self):
pass
<|fim▁end|> | return 0 |
<|file_name|>DistributedGoofySpeedwayAI.py<|end_file_name|><|fim▁begin|>from otp.ai.AIBaseGlobal import *
import DistributedCCharBaseAI
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from direct.task import Task
import random
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
import CharStateDatasAI
class DistributedGoofySpeedwayAI(DistributedCCharBaseAI.DistributedCCharBaseAI):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedGoofySpeedwayAI')
def <|fim_middle|>(self, air):
DistributedCCharBaseAI.DistributedCCharBaseAI.__init__(self, air, TTLocalizer.Goofy)
self.fsm = ClassicFSM.ClassicFSM('DistributedGoofySpeedwayAI', [State.State('Off', self.enterOff, self.exitOff, ['Lonely', 'TransitionToCostume', 'Walk']),
State.State('Lonely', self.enterLonely, self.exitLonely, ['Chatty', 'Walk', 'TransitionToCostume']),
State.State('Chatty', self.enterChatty, self.exitChatty, ['Lonely', 'Walk', 'TransitionToCostume']),
State.State('Walk', self.enterWalk, self.exitWalk, ['Lonely', 'Chatty', 'TransitionToCostume']),
State.State('TransitionToCostume', self.enterTransitionToCostume, self.exitTransitionToCostume, ['Off'])], 'Off', 'Off')
self.fsm.enterInitialState()
self.handleHolidays()
def delete(self):
self.fsm.requestFinalState()
DistributedCCharBaseAI.DistributedCCharBaseAI.delete(self)
self.lonelyDoneEvent = None
self.lonely = None
self.chattyDoneEvent = None
self.chatty = None
self.walkDoneEvent = None
self.walk = None
return
def generate(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.generate(self)
name = self.getName()
self.lonelyDoneEvent = self.taskName(name + '-lonely-done')
self.lonely = CharStateDatasAI.CharLonelyStateAI(self.lonelyDoneEvent, self)
self.chattyDoneEvent = self.taskName(name + '-chatty-done')
self.chatty = CharStateDatasAI.CharChattyStateAI(self.chattyDoneEvent, self)
self.walkDoneEvent = self.taskName(name + '-walk-done')
if self.diffPath == None:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self)
else:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self, self.diffPath)
return
def walkSpeed(self):
return ToontownGlobals.GoofySpeed
def start(self):
self.fsm.request('Lonely')
def __decideNextState(self, doneStatus):
if self.transitionToCostume == 1:
curWalkNode = self.walk.getDestNode()
if simbase.air.holidayManager:
if ToontownGlobals.HALLOWEEN_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
elif ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
else:
self.notify.warning('transitionToCostume == 1 but no costume holiday')
else:
self.notify.warning('transitionToCostume == 1 but no holiday Manager')
if doneStatus['state'] == 'lonely' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'chatty' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'walk' and doneStatus['status'] == 'done':
if len(self.nearbyAvatars) > 0:
self.fsm.request('Chatty')
else:
self.fsm.request('Lonely')
def enterOff(self):
pass
def exitOff(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.exitOff(self)
def enterLonely(self):
self.lonely.enter()
self.acceptOnce(self.lonelyDoneEvent, self.__decideNextState)
def exitLonely(self):
self.ignore(self.lonelyDoneEvent)
self.lonely.exit()
def __goForAWalk(self, task):
self.notify.debug('going for a walk')
self.fsm.request('Walk')
return Task.done
def enterChatty(self):
self.chatty.enter()
self.acceptOnce(self.chattyDoneEvent, self.__decideNextState)
def exitChatty(self):
self.ignore(self.chattyDoneEvent)
self.chatty.exit()
def enterWalk(self):
self.notify.debug('going for a walk')
self.walk.enter()
self.acceptOnce(self.walkDoneEvent, self.__decideNextState)
def exitWalk(self):
self.ignore(self.walkDoneEvent)
self.walk.exit()
def avatarEnterNextState(self):
if len(self.nearbyAvatars) == 1:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Chatty')
else:
self.notify.debug('avatarEnterNextState: in walk state')
else:
self.notify.debug('avatarEnterNextState: num avatars: ' + str(len(self.nearbyAvatars)))
def avatarExitNextState(self):
if len(self.nearbyAvatars) == 0:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Lonely')
def handleHolidays(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.handleHolidays(self)
if hasattr(simbase.air, 'holidayManager'):
if ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays:
if simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES] != None and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].getRunningState():
self.diffPath = TTLocalizer.Donald
return
def getCCLocation(self):
if self.diffPath == None:
return 1
else:
return 0
return
def enterTransitionToCostume(self):
pass
def exitTransitionToCostume(self):
pass
<|fim▁end|> | __init__ |
<|file_name|>DistributedGoofySpeedwayAI.py<|end_file_name|><|fim▁begin|>from otp.ai.AIBaseGlobal import *
import DistributedCCharBaseAI
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from direct.task import Task
import random
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
import CharStateDatasAI
class DistributedGoofySpeedwayAI(DistributedCCharBaseAI.DistributedCCharBaseAI):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedGoofySpeedwayAI')
def __init__(self, air):
DistributedCCharBaseAI.DistributedCCharBaseAI.__init__(self, air, TTLocalizer.Goofy)
self.fsm = ClassicFSM.ClassicFSM('DistributedGoofySpeedwayAI', [State.State('Off', self.enterOff, self.exitOff, ['Lonely', 'TransitionToCostume', 'Walk']),
State.State('Lonely', self.enterLonely, self.exitLonely, ['Chatty', 'Walk', 'TransitionToCostume']),
State.State('Chatty', self.enterChatty, self.exitChatty, ['Lonely', 'Walk', 'TransitionToCostume']),
State.State('Walk', self.enterWalk, self.exitWalk, ['Lonely', 'Chatty', 'TransitionToCostume']),
State.State('TransitionToCostume', self.enterTransitionToCostume, self.exitTransitionToCostume, ['Off'])], 'Off', 'Off')
self.fsm.enterInitialState()
self.handleHolidays()
def <|fim_middle|>(self):
self.fsm.requestFinalState()
DistributedCCharBaseAI.DistributedCCharBaseAI.delete(self)
self.lonelyDoneEvent = None
self.lonely = None
self.chattyDoneEvent = None
self.chatty = None
self.walkDoneEvent = None
self.walk = None
return
def generate(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.generate(self)
name = self.getName()
self.lonelyDoneEvent = self.taskName(name + '-lonely-done')
self.lonely = CharStateDatasAI.CharLonelyStateAI(self.lonelyDoneEvent, self)
self.chattyDoneEvent = self.taskName(name + '-chatty-done')
self.chatty = CharStateDatasAI.CharChattyStateAI(self.chattyDoneEvent, self)
self.walkDoneEvent = self.taskName(name + '-walk-done')
if self.diffPath == None:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self)
else:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self, self.diffPath)
return
def walkSpeed(self):
return ToontownGlobals.GoofySpeed
def start(self):
self.fsm.request('Lonely')
def __decideNextState(self, doneStatus):
if self.transitionToCostume == 1:
curWalkNode = self.walk.getDestNode()
if simbase.air.holidayManager:
if ToontownGlobals.HALLOWEEN_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
elif ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
else:
self.notify.warning('transitionToCostume == 1 but no costume holiday')
else:
self.notify.warning('transitionToCostume == 1 but no holiday Manager')
if doneStatus['state'] == 'lonely' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'chatty' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'walk' and doneStatus['status'] == 'done':
if len(self.nearbyAvatars) > 0:
self.fsm.request('Chatty')
else:
self.fsm.request('Lonely')
def enterOff(self):
pass
def exitOff(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.exitOff(self)
def enterLonely(self):
self.lonely.enter()
self.acceptOnce(self.lonelyDoneEvent, self.__decideNextState)
def exitLonely(self):
self.ignore(self.lonelyDoneEvent)
self.lonely.exit()
def __goForAWalk(self, task):
self.notify.debug('going for a walk')
self.fsm.request('Walk')
return Task.done
def enterChatty(self):
self.chatty.enter()
self.acceptOnce(self.chattyDoneEvent, self.__decideNextState)
def exitChatty(self):
self.ignore(self.chattyDoneEvent)
self.chatty.exit()
def enterWalk(self):
self.notify.debug('going for a walk')
self.walk.enter()
self.acceptOnce(self.walkDoneEvent, self.__decideNextState)
def exitWalk(self):
self.ignore(self.walkDoneEvent)
self.walk.exit()
def avatarEnterNextState(self):
if len(self.nearbyAvatars) == 1:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Chatty')
else:
self.notify.debug('avatarEnterNextState: in walk state')
else:
self.notify.debug('avatarEnterNextState: num avatars: ' + str(len(self.nearbyAvatars)))
def avatarExitNextState(self):
if len(self.nearbyAvatars) == 0:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Lonely')
def handleHolidays(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.handleHolidays(self)
if hasattr(simbase.air, 'holidayManager'):
if ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays:
if simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES] != None and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].getRunningState():
self.diffPath = TTLocalizer.Donald
return
def getCCLocation(self):
if self.diffPath == None:
return 1
else:
return 0
return
def enterTransitionToCostume(self):
pass
def exitTransitionToCostume(self):
pass
<|fim▁end|> | delete |
<|file_name|>DistributedGoofySpeedwayAI.py<|end_file_name|><|fim▁begin|>from otp.ai.AIBaseGlobal import *
import DistributedCCharBaseAI
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from direct.task import Task
import random
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
import CharStateDatasAI
class DistributedGoofySpeedwayAI(DistributedCCharBaseAI.DistributedCCharBaseAI):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedGoofySpeedwayAI')
def __init__(self, air):
DistributedCCharBaseAI.DistributedCCharBaseAI.__init__(self, air, TTLocalizer.Goofy)
self.fsm = ClassicFSM.ClassicFSM('DistributedGoofySpeedwayAI', [State.State('Off', self.enterOff, self.exitOff, ['Lonely', 'TransitionToCostume', 'Walk']),
State.State('Lonely', self.enterLonely, self.exitLonely, ['Chatty', 'Walk', 'TransitionToCostume']),
State.State('Chatty', self.enterChatty, self.exitChatty, ['Lonely', 'Walk', 'TransitionToCostume']),
State.State('Walk', self.enterWalk, self.exitWalk, ['Lonely', 'Chatty', 'TransitionToCostume']),
State.State('TransitionToCostume', self.enterTransitionToCostume, self.exitTransitionToCostume, ['Off'])], 'Off', 'Off')
self.fsm.enterInitialState()
self.handleHolidays()
def delete(self):
self.fsm.requestFinalState()
DistributedCCharBaseAI.DistributedCCharBaseAI.delete(self)
self.lonelyDoneEvent = None
self.lonely = None
self.chattyDoneEvent = None
self.chatty = None
self.walkDoneEvent = None
self.walk = None
return
def <|fim_middle|>(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.generate(self)
name = self.getName()
self.lonelyDoneEvent = self.taskName(name + '-lonely-done')
self.lonely = CharStateDatasAI.CharLonelyStateAI(self.lonelyDoneEvent, self)
self.chattyDoneEvent = self.taskName(name + '-chatty-done')
self.chatty = CharStateDatasAI.CharChattyStateAI(self.chattyDoneEvent, self)
self.walkDoneEvent = self.taskName(name + '-walk-done')
if self.diffPath == None:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self)
else:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self, self.diffPath)
return
def walkSpeed(self):
return ToontownGlobals.GoofySpeed
def start(self):
self.fsm.request('Lonely')
def __decideNextState(self, doneStatus):
if self.transitionToCostume == 1:
curWalkNode = self.walk.getDestNode()
if simbase.air.holidayManager:
if ToontownGlobals.HALLOWEEN_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
elif ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
else:
self.notify.warning('transitionToCostume == 1 but no costume holiday')
else:
self.notify.warning('transitionToCostume == 1 but no holiday Manager')
if doneStatus['state'] == 'lonely' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'chatty' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'walk' and doneStatus['status'] == 'done':
if len(self.nearbyAvatars) > 0:
self.fsm.request('Chatty')
else:
self.fsm.request('Lonely')
def enterOff(self):
pass
def exitOff(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.exitOff(self)
def enterLonely(self):
self.lonely.enter()
self.acceptOnce(self.lonelyDoneEvent, self.__decideNextState)
def exitLonely(self):
self.ignore(self.lonelyDoneEvent)
self.lonely.exit()
def __goForAWalk(self, task):
self.notify.debug('going for a walk')
self.fsm.request('Walk')
return Task.done
def enterChatty(self):
self.chatty.enter()
self.acceptOnce(self.chattyDoneEvent, self.__decideNextState)
def exitChatty(self):
self.ignore(self.chattyDoneEvent)
self.chatty.exit()
def enterWalk(self):
self.notify.debug('going for a walk')
self.walk.enter()
self.acceptOnce(self.walkDoneEvent, self.__decideNextState)
def exitWalk(self):
self.ignore(self.walkDoneEvent)
self.walk.exit()
def avatarEnterNextState(self):
if len(self.nearbyAvatars) == 1:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Chatty')
else:
self.notify.debug('avatarEnterNextState: in walk state')
else:
self.notify.debug('avatarEnterNextState: num avatars: ' + str(len(self.nearbyAvatars)))
def avatarExitNextState(self):
if len(self.nearbyAvatars) == 0:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Lonely')
def handleHolidays(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.handleHolidays(self)
if hasattr(simbase.air, 'holidayManager'):
if ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays:
if simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES] != None and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].getRunningState():
self.diffPath = TTLocalizer.Donald
return
def getCCLocation(self):
if self.diffPath == None:
return 1
else:
return 0
return
def enterTransitionToCostume(self):
pass
def exitTransitionToCostume(self):
pass
<|fim▁end|> | generate |
<|file_name|>DistributedGoofySpeedwayAI.py<|end_file_name|><|fim▁begin|>from otp.ai.AIBaseGlobal import *
import DistributedCCharBaseAI
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from direct.task import Task
import random
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
import CharStateDatasAI
class DistributedGoofySpeedwayAI(DistributedCCharBaseAI.DistributedCCharBaseAI):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedGoofySpeedwayAI')
def __init__(self, air):
DistributedCCharBaseAI.DistributedCCharBaseAI.__init__(self, air, TTLocalizer.Goofy)
self.fsm = ClassicFSM.ClassicFSM('DistributedGoofySpeedwayAI', [State.State('Off', self.enterOff, self.exitOff, ['Lonely', 'TransitionToCostume', 'Walk']),
State.State('Lonely', self.enterLonely, self.exitLonely, ['Chatty', 'Walk', 'TransitionToCostume']),
State.State('Chatty', self.enterChatty, self.exitChatty, ['Lonely', 'Walk', 'TransitionToCostume']),
State.State('Walk', self.enterWalk, self.exitWalk, ['Lonely', 'Chatty', 'TransitionToCostume']),
State.State('TransitionToCostume', self.enterTransitionToCostume, self.exitTransitionToCostume, ['Off'])], 'Off', 'Off')
self.fsm.enterInitialState()
self.handleHolidays()
def delete(self):
self.fsm.requestFinalState()
DistributedCCharBaseAI.DistributedCCharBaseAI.delete(self)
self.lonelyDoneEvent = None
self.lonely = None
self.chattyDoneEvent = None
self.chatty = None
self.walkDoneEvent = None
self.walk = None
return
def generate(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.generate(self)
name = self.getName()
self.lonelyDoneEvent = self.taskName(name + '-lonely-done')
self.lonely = CharStateDatasAI.CharLonelyStateAI(self.lonelyDoneEvent, self)
self.chattyDoneEvent = self.taskName(name + '-chatty-done')
self.chatty = CharStateDatasAI.CharChattyStateAI(self.chattyDoneEvent, self)
self.walkDoneEvent = self.taskName(name + '-walk-done')
if self.diffPath == None:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self)
else:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self, self.diffPath)
return
def <|fim_middle|>(self):
return ToontownGlobals.GoofySpeed
def start(self):
self.fsm.request('Lonely')
def __decideNextState(self, doneStatus):
if self.transitionToCostume == 1:
curWalkNode = self.walk.getDestNode()
if simbase.air.holidayManager:
if ToontownGlobals.HALLOWEEN_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
elif ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
else:
self.notify.warning('transitionToCostume == 1 but no costume holiday')
else:
self.notify.warning('transitionToCostume == 1 but no holiday Manager')
if doneStatus['state'] == 'lonely' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'chatty' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'walk' and doneStatus['status'] == 'done':
if len(self.nearbyAvatars) > 0:
self.fsm.request('Chatty')
else:
self.fsm.request('Lonely')
def enterOff(self):
pass
def exitOff(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.exitOff(self)
def enterLonely(self):
self.lonely.enter()
self.acceptOnce(self.lonelyDoneEvent, self.__decideNextState)
def exitLonely(self):
self.ignore(self.lonelyDoneEvent)
self.lonely.exit()
def __goForAWalk(self, task):
self.notify.debug('going for a walk')
self.fsm.request('Walk')
return Task.done
def enterChatty(self):
self.chatty.enter()
self.acceptOnce(self.chattyDoneEvent, self.__decideNextState)
def exitChatty(self):
self.ignore(self.chattyDoneEvent)
self.chatty.exit()
def enterWalk(self):
self.notify.debug('going for a walk')
self.walk.enter()
self.acceptOnce(self.walkDoneEvent, self.__decideNextState)
def exitWalk(self):
self.ignore(self.walkDoneEvent)
self.walk.exit()
def avatarEnterNextState(self):
if len(self.nearbyAvatars) == 1:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Chatty')
else:
self.notify.debug('avatarEnterNextState: in walk state')
else:
self.notify.debug('avatarEnterNextState: num avatars: ' + str(len(self.nearbyAvatars)))
def avatarExitNextState(self):
if len(self.nearbyAvatars) == 0:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Lonely')
def handleHolidays(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.handleHolidays(self)
if hasattr(simbase.air, 'holidayManager'):
if ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays:
if simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES] != None and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].getRunningState():
self.diffPath = TTLocalizer.Donald
return
def getCCLocation(self):
if self.diffPath == None:
return 1
else:
return 0
return
def enterTransitionToCostume(self):
pass
def exitTransitionToCostume(self):
pass
<|fim▁end|> | walkSpeed |
<|file_name|>DistributedGoofySpeedwayAI.py<|end_file_name|><|fim▁begin|>from otp.ai.AIBaseGlobal import *
import DistributedCCharBaseAI
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from direct.task import Task
import random
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
import CharStateDatasAI
class DistributedGoofySpeedwayAI(DistributedCCharBaseAI.DistributedCCharBaseAI):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedGoofySpeedwayAI')
def __init__(self, air):
DistributedCCharBaseAI.DistributedCCharBaseAI.__init__(self, air, TTLocalizer.Goofy)
self.fsm = ClassicFSM.ClassicFSM('DistributedGoofySpeedwayAI', [State.State('Off', self.enterOff, self.exitOff, ['Lonely', 'TransitionToCostume', 'Walk']),
State.State('Lonely', self.enterLonely, self.exitLonely, ['Chatty', 'Walk', 'TransitionToCostume']),
State.State('Chatty', self.enterChatty, self.exitChatty, ['Lonely', 'Walk', 'TransitionToCostume']),
State.State('Walk', self.enterWalk, self.exitWalk, ['Lonely', 'Chatty', 'TransitionToCostume']),
State.State('TransitionToCostume', self.enterTransitionToCostume, self.exitTransitionToCostume, ['Off'])], 'Off', 'Off')
self.fsm.enterInitialState()
self.handleHolidays()
def delete(self):
self.fsm.requestFinalState()
DistributedCCharBaseAI.DistributedCCharBaseAI.delete(self)
self.lonelyDoneEvent = None
self.lonely = None
self.chattyDoneEvent = None
self.chatty = None
self.walkDoneEvent = None
self.walk = None
return
def generate(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.generate(self)
name = self.getName()
self.lonelyDoneEvent = self.taskName(name + '-lonely-done')
self.lonely = CharStateDatasAI.CharLonelyStateAI(self.lonelyDoneEvent, self)
self.chattyDoneEvent = self.taskName(name + '-chatty-done')
self.chatty = CharStateDatasAI.CharChattyStateAI(self.chattyDoneEvent, self)
self.walkDoneEvent = self.taskName(name + '-walk-done')
if self.diffPath == None:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self)
else:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self, self.diffPath)
return
def walkSpeed(self):
return ToontownGlobals.GoofySpeed
def <|fim_middle|>(self):
self.fsm.request('Lonely')
def __decideNextState(self, doneStatus):
if self.transitionToCostume == 1:
curWalkNode = self.walk.getDestNode()
if simbase.air.holidayManager:
if ToontownGlobals.HALLOWEEN_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
elif ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
else:
self.notify.warning('transitionToCostume == 1 but no costume holiday')
else:
self.notify.warning('transitionToCostume == 1 but no holiday Manager')
if doneStatus['state'] == 'lonely' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'chatty' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'walk' and doneStatus['status'] == 'done':
if len(self.nearbyAvatars) > 0:
self.fsm.request('Chatty')
else:
self.fsm.request('Lonely')
def enterOff(self):
pass
def exitOff(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.exitOff(self)
def enterLonely(self):
self.lonely.enter()
self.acceptOnce(self.lonelyDoneEvent, self.__decideNextState)
def exitLonely(self):
self.ignore(self.lonelyDoneEvent)
self.lonely.exit()
def __goForAWalk(self, task):
self.notify.debug('going for a walk')
self.fsm.request('Walk')
return Task.done
def enterChatty(self):
self.chatty.enter()
self.acceptOnce(self.chattyDoneEvent, self.__decideNextState)
def exitChatty(self):
self.ignore(self.chattyDoneEvent)
self.chatty.exit()
def enterWalk(self):
self.notify.debug('going for a walk')
self.walk.enter()
self.acceptOnce(self.walkDoneEvent, self.__decideNextState)
def exitWalk(self):
self.ignore(self.walkDoneEvent)
self.walk.exit()
def avatarEnterNextState(self):
if len(self.nearbyAvatars) == 1:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Chatty')
else:
self.notify.debug('avatarEnterNextState: in walk state')
else:
self.notify.debug('avatarEnterNextState: num avatars: ' + str(len(self.nearbyAvatars)))
def avatarExitNextState(self):
if len(self.nearbyAvatars) == 0:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Lonely')
def handleHolidays(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.handleHolidays(self)
if hasattr(simbase.air, 'holidayManager'):
if ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays:
if simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES] != None and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].getRunningState():
self.diffPath = TTLocalizer.Donald
return
def getCCLocation(self):
if self.diffPath == None:
return 1
else:
return 0
return
def enterTransitionToCostume(self):
pass
def exitTransitionToCostume(self):
pass
<|fim▁end|> | start |
<|file_name|>DistributedGoofySpeedwayAI.py<|end_file_name|><|fim▁begin|>from otp.ai.AIBaseGlobal import *
import DistributedCCharBaseAI
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from direct.task import Task
import random
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
import CharStateDatasAI
class DistributedGoofySpeedwayAI(DistributedCCharBaseAI.DistributedCCharBaseAI):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedGoofySpeedwayAI')
def __init__(self, air):
DistributedCCharBaseAI.DistributedCCharBaseAI.__init__(self, air, TTLocalizer.Goofy)
self.fsm = ClassicFSM.ClassicFSM('DistributedGoofySpeedwayAI', [State.State('Off', self.enterOff, self.exitOff, ['Lonely', 'TransitionToCostume', 'Walk']),
State.State('Lonely', self.enterLonely, self.exitLonely, ['Chatty', 'Walk', 'TransitionToCostume']),
State.State('Chatty', self.enterChatty, self.exitChatty, ['Lonely', 'Walk', 'TransitionToCostume']),
State.State('Walk', self.enterWalk, self.exitWalk, ['Lonely', 'Chatty', 'TransitionToCostume']),
State.State('TransitionToCostume', self.enterTransitionToCostume, self.exitTransitionToCostume, ['Off'])], 'Off', 'Off')
self.fsm.enterInitialState()
self.handleHolidays()
def delete(self):
self.fsm.requestFinalState()
DistributedCCharBaseAI.DistributedCCharBaseAI.delete(self)
self.lonelyDoneEvent = None
self.lonely = None
self.chattyDoneEvent = None
self.chatty = None
self.walkDoneEvent = None
self.walk = None
return
def generate(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.generate(self)
name = self.getName()
self.lonelyDoneEvent = self.taskName(name + '-lonely-done')
self.lonely = CharStateDatasAI.CharLonelyStateAI(self.lonelyDoneEvent, self)
self.chattyDoneEvent = self.taskName(name + '-chatty-done')
self.chatty = CharStateDatasAI.CharChattyStateAI(self.chattyDoneEvent, self)
self.walkDoneEvent = self.taskName(name + '-walk-done')
if self.diffPath == None:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self)
else:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self, self.diffPath)
return
def walkSpeed(self):
return ToontownGlobals.GoofySpeed
def start(self):
self.fsm.request('Lonely')
def <|fim_middle|>(self, doneStatus):
if self.transitionToCostume == 1:
curWalkNode = self.walk.getDestNode()
if simbase.air.holidayManager:
if ToontownGlobals.HALLOWEEN_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
elif ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
else:
self.notify.warning('transitionToCostume == 1 but no costume holiday')
else:
self.notify.warning('transitionToCostume == 1 but no holiday Manager')
if doneStatus['state'] == 'lonely' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'chatty' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'walk' and doneStatus['status'] == 'done':
if len(self.nearbyAvatars) > 0:
self.fsm.request('Chatty')
else:
self.fsm.request('Lonely')
def enterOff(self):
pass
def exitOff(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.exitOff(self)
def enterLonely(self):
self.lonely.enter()
self.acceptOnce(self.lonelyDoneEvent, self.__decideNextState)
def exitLonely(self):
self.ignore(self.lonelyDoneEvent)
self.lonely.exit()
def __goForAWalk(self, task):
self.notify.debug('going for a walk')
self.fsm.request('Walk')
return Task.done
def enterChatty(self):
self.chatty.enter()
self.acceptOnce(self.chattyDoneEvent, self.__decideNextState)
def exitChatty(self):
self.ignore(self.chattyDoneEvent)
self.chatty.exit()
def enterWalk(self):
self.notify.debug('going for a walk')
self.walk.enter()
self.acceptOnce(self.walkDoneEvent, self.__decideNextState)
def exitWalk(self):
self.ignore(self.walkDoneEvent)
self.walk.exit()
def avatarEnterNextState(self):
if len(self.nearbyAvatars) == 1:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Chatty')
else:
self.notify.debug('avatarEnterNextState: in walk state')
else:
self.notify.debug('avatarEnterNextState: num avatars: ' + str(len(self.nearbyAvatars)))
def avatarExitNextState(self):
if len(self.nearbyAvatars) == 0:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Lonely')
def handleHolidays(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.handleHolidays(self)
if hasattr(simbase.air, 'holidayManager'):
if ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays:
if simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES] != None and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].getRunningState():
self.diffPath = TTLocalizer.Donald
return
def getCCLocation(self):
if self.diffPath == None:
return 1
else:
return 0
return
def enterTransitionToCostume(self):
pass
def exitTransitionToCostume(self):
pass
<|fim▁end|> | __decideNextState |
<|file_name|>DistributedGoofySpeedwayAI.py<|end_file_name|><|fim▁begin|>from otp.ai.AIBaseGlobal import *
import DistributedCCharBaseAI
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from direct.task import Task
import random
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
import CharStateDatasAI
class DistributedGoofySpeedwayAI(DistributedCCharBaseAI.DistributedCCharBaseAI):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedGoofySpeedwayAI')
def __init__(self, air):
DistributedCCharBaseAI.DistributedCCharBaseAI.__init__(self, air, TTLocalizer.Goofy)
self.fsm = ClassicFSM.ClassicFSM('DistributedGoofySpeedwayAI', [State.State('Off', self.enterOff, self.exitOff, ['Lonely', 'TransitionToCostume', 'Walk']),
State.State('Lonely', self.enterLonely, self.exitLonely, ['Chatty', 'Walk', 'TransitionToCostume']),
State.State('Chatty', self.enterChatty, self.exitChatty, ['Lonely', 'Walk', 'TransitionToCostume']),
State.State('Walk', self.enterWalk, self.exitWalk, ['Lonely', 'Chatty', 'TransitionToCostume']),
State.State('TransitionToCostume', self.enterTransitionToCostume, self.exitTransitionToCostume, ['Off'])], 'Off', 'Off')
self.fsm.enterInitialState()
self.handleHolidays()
def delete(self):
self.fsm.requestFinalState()
DistributedCCharBaseAI.DistributedCCharBaseAI.delete(self)
self.lonelyDoneEvent = None
self.lonely = None
self.chattyDoneEvent = None
self.chatty = None
self.walkDoneEvent = None
self.walk = None
return
def generate(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.generate(self)
name = self.getName()
self.lonelyDoneEvent = self.taskName(name + '-lonely-done')
self.lonely = CharStateDatasAI.CharLonelyStateAI(self.lonelyDoneEvent, self)
self.chattyDoneEvent = self.taskName(name + '-chatty-done')
self.chatty = CharStateDatasAI.CharChattyStateAI(self.chattyDoneEvent, self)
self.walkDoneEvent = self.taskName(name + '-walk-done')
if self.diffPath == None:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self)
else:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self, self.diffPath)
return
def walkSpeed(self):
return ToontownGlobals.GoofySpeed
def start(self):
self.fsm.request('Lonely')
def __decideNextState(self, doneStatus):
if self.transitionToCostume == 1:
curWalkNode = self.walk.getDestNode()
if simbase.air.holidayManager:
if ToontownGlobals.HALLOWEEN_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
elif ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
else:
self.notify.warning('transitionToCostume == 1 but no costume holiday')
else:
self.notify.warning('transitionToCostume == 1 but no holiday Manager')
if doneStatus['state'] == 'lonely' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'chatty' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'walk' and doneStatus['status'] == 'done':
if len(self.nearbyAvatars) > 0:
self.fsm.request('Chatty')
else:
self.fsm.request('Lonely')
def <|fim_middle|>(self):
pass
def exitOff(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.exitOff(self)
def enterLonely(self):
self.lonely.enter()
self.acceptOnce(self.lonelyDoneEvent, self.__decideNextState)
def exitLonely(self):
self.ignore(self.lonelyDoneEvent)
self.lonely.exit()
def __goForAWalk(self, task):
self.notify.debug('going for a walk')
self.fsm.request('Walk')
return Task.done
def enterChatty(self):
self.chatty.enter()
self.acceptOnce(self.chattyDoneEvent, self.__decideNextState)
def exitChatty(self):
self.ignore(self.chattyDoneEvent)
self.chatty.exit()
def enterWalk(self):
self.notify.debug('going for a walk')
self.walk.enter()
self.acceptOnce(self.walkDoneEvent, self.__decideNextState)
def exitWalk(self):
self.ignore(self.walkDoneEvent)
self.walk.exit()
def avatarEnterNextState(self):
if len(self.nearbyAvatars) == 1:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Chatty')
else:
self.notify.debug('avatarEnterNextState: in walk state')
else:
self.notify.debug('avatarEnterNextState: num avatars: ' + str(len(self.nearbyAvatars)))
def avatarExitNextState(self):
if len(self.nearbyAvatars) == 0:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Lonely')
def handleHolidays(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.handleHolidays(self)
if hasattr(simbase.air, 'holidayManager'):
if ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays:
if simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES] != None and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].getRunningState():
self.diffPath = TTLocalizer.Donald
return
def getCCLocation(self):
if self.diffPath == None:
return 1
else:
return 0
return
def enterTransitionToCostume(self):
pass
def exitTransitionToCostume(self):
pass
<|fim▁end|> | enterOff |
<|file_name|>DistributedGoofySpeedwayAI.py<|end_file_name|><|fim▁begin|>from otp.ai.AIBaseGlobal import *
import DistributedCCharBaseAI
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from direct.task import Task
import random
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
import CharStateDatasAI
class DistributedGoofySpeedwayAI(DistributedCCharBaseAI.DistributedCCharBaseAI):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedGoofySpeedwayAI')
def __init__(self, air):
DistributedCCharBaseAI.DistributedCCharBaseAI.__init__(self, air, TTLocalizer.Goofy)
self.fsm = ClassicFSM.ClassicFSM('DistributedGoofySpeedwayAI', [State.State('Off', self.enterOff, self.exitOff, ['Lonely', 'TransitionToCostume', 'Walk']),
State.State('Lonely', self.enterLonely, self.exitLonely, ['Chatty', 'Walk', 'TransitionToCostume']),
State.State('Chatty', self.enterChatty, self.exitChatty, ['Lonely', 'Walk', 'TransitionToCostume']),
State.State('Walk', self.enterWalk, self.exitWalk, ['Lonely', 'Chatty', 'TransitionToCostume']),
State.State('TransitionToCostume', self.enterTransitionToCostume, self.exitTransitionToCostume, ['Off'])], 'Off', 'Off')
self.fsm.enterInitialState()
self.handleHolidays()
def delete(self):
self.fsm.requestFinalState()
DistributedCCharBaseAI.DistributedCCharBaseAI.delete(self)
self.lonelyDoneEvent = None
self.lonely = None
self.chattyDoneEvent = None
self.chatty = None
self.walkDoneEvent = None
self.walk = None
return
def generate(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.generate(self)
name = self.getName()
self.lonelyDoneEvent = self.taskName(name + '-lonely-done')
self.lonely = CharStateDatasAI.CharLonelyStateAI(self.lonelyDoneEvent, self)
self.chattyDoneEvent = self.taskName(name + '-chatty-done')
self.chatty = CharStateDatasAI.CharChattyStateAI(self.chattyDoneEvent, self)
self.walkDoneEvent = self.taskName(name + '-walk-done')
if self.diffPath == None:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self)
else:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self, self.diffPath)
return
def walkSpeed(self):
return ToontownGlobals.GoofySpeed
def start(self):
self.fsm.request('Lonely')
def __decideNextState(self, doneStatus):
if self.transitionToCostume == 1:
curWalkNode = self.walk.getDestNode()
if simbase.air.holidayManager:
if ToontownGlobals.HALLOWEEN_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
elif ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
else:
self.notify.warning('transitionToCostume == 1 but no costume holiday')
else:
self.notify.warning('transitionToCostume == 1 but no holiday Manager')
if doneStatus['state'] == 'lonely' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'chatty' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'walk' and doneStatus['status'] == 'done':
if len(self.nearbyAvatars) > 0:
self.fsm.request('Chatty')
else:
self.fsm.request('Lonely')
def enterOff(self):
pass
def <|fim_middle|>(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.exitOff(self)
def enterLonely(self):
self.lonely.enter()
self.acceptOnce(self.lonelyDoneEvent, self.__decideNextState)
def exitLonely(self):
self.ignore(self.lonelyDoneEvent)
self.lonely.exit()
def __goForAWalk(self, task):
self.notify.debug('going for a walk')
self.fsm.request('Walk')
return Task.done
def enterChatty(self):
self.chatty.enter()
self.acceptOnce(self.chattyDoneEvent, self.__decideNextState)
def exitChatty(self):
self.ignore(self.chattyDoneEvent)
self.chatty.exit()
def enterWalk(self):
self.notify.debug('going for a walk')
self.walk.enter()
self.acceptOnce(self.walkDoneEvent, self.__decideNextState)
def exitWalk(self):
self.ignore(self.walkDoneEvent)
self.walk.exit()
def avatarEnterNextState(self):
if len(self.nearbyAvatars) == 1:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Chatty')
else:
self.notify.debug('avatarEnterNextState: in walk state')
else:
self.notify.debug('avatarEnterNextState: num avatars: ' + str(len(self.nearbyAvatars)))
def avatarExitNextState(self):
if len(self.nearbyAvatars) == 0:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Lonely')
def handleHolidays(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.handleHolidays(self)
if hasattr(simbase.air, 'holidayManager'):
if ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays:
if simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES] != None and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].getRunningState():
self.diffPath = TTLocalizer.Donald
return
def getCCLocation(self):
if self.diffPath == None:
return 1
else:
return 0
return
def enterTransitionToCostume(self):
pass
def exitTransitionToCostume(self):
pass
<|fim▁end|> | exitOff |
<|file_name|>DistributedGoofySpeedwayAI.py<|end_file_name|><|fim▁begin|>from otp.ai.AIBaseGlobal import *
import DistributedCCharBaseAI
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from direct.task import Task
import random
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
import CharStateDatasAI
class DistributedGoofySpeedwayAI(DistributedCCharBaseAI.DistributedCCharBaseAI):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedGoofySpeedwayAI')
def __init__(self, air):
DistributedCCharBaseAI.DistributedCCharBaseAI.__init__(self, air, TTLocalizer.Goofy)
self.fsm = ClassicFSM.ClassicFSM('DistributedGoofySpeedwayAI', [State.State('Off', self.enterOff, self.exitOff, ['Lonely', 'TransitionToCostume', 'Walk']),
State.State('Lonely', self.enterLonely, self.exitLonely, ['Chatty', 'Walk', 'TransitionToCostume']),
State.State('Chatty', self.enterChatty, self.exitChatty, ['Lonely', 'Walk', 'TransitionToCostume']),
State.State('Walk', self.enterWalk, self.exitWalk, ['Lonely', 'Chatty', 'TransitionToCostume']),
State.State('TransitionToCostume', self.enterTransitionToCostume, self.exitTransitionToCostume, ['Off'])], 'Off', 'Off')
self.fsm.enterInitialState()
self.handleHolidays()
def delete(self):
self.fsm.requestFinalState()
DistributedCCharBaseAI.DistributedCCharBaseAI.delete(self)
self.lonelyDoneEvent = None
self.lonely = None
self.chattyDoneEvent = None
self.chatty = None
self.walkDoneEvent = None
self.walk = None
return
def generate(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.generate(self)
name = self.getName()
self.lonelyDoneEvent = self.taskName(name + '-lonely-done')
self.lonely = CharStateDatasAI.CharLonelyStateAI(self.lonelyDoneEvent, self)
self.chattyDoneEvent = self.taskName(name + '-chatty-done')
self.chatty = CharStateDatasAI.CharChattyStateAI(self.chattyDoneEvent, self)
self.walkDoneEvent = self.taskName(name + '-walk-done')
if self.diffPath == None:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self)
else:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self, self.diffPath)
return
def walkSpeed(self):
return ToontownGlobals.GoofySpeed
def start(self):
self.fsm.request('Lonely')
def __decideNextState(self, doneStatus):
if self.transitionToCostume == 1:
curWalkNode = self.walk.getDestNode()
if simbase.air.holidayManager:
if ToontownGlobals.HALLOWEEN_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
elif ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
else:
self.notify.warning('transitionToCostume == 1 but no costume holiday')
else:
self.notify.warning('transitionToCostume == 1 but no holiday Manager')
if doneStatus['state'] == 'lonely' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'chatty' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'walk' and doneStatus['status'] == 'done':
if len(self.nearbyAvatars) > 0:
self.fsm.request('Chatty')
else:
self.fsm.request('Lonely')
def enterOff(self):
pass
def exitOff(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.exitOff(self)
def <|fim_middle|>(self):
self.lonely.enter()
self.acceptOnce(self.lonelyDoneEvent, self.__decideNextState)
def exitLonely(self):
self.ignore(self.lonelyDoneEvent)
self.lonely.exit()
def __goForAWalk(self, task):
self.notify.debug('going for a walk')
self.fsm.request('Walk')
return Task.done
def enterChatty(self):
self.chatty.enter()
self.acceptOnce(self.chattyDoneEvent, self.__decideNextState)
def exitChatty(self):
self.ignore(self.chattyDoneEvent)
self.chatty.exit()
def enterWalk(self):
self.notify.debug('going for a walk')
self.walk.enter()
self.acceptOnce(self.walkDoneEvent, self.__decideNextState)
def exitWalk(self):
self.ignore(self.walkDoneEvent)
self.walk.exit()
def avatarEnterNextState(self):
if len(self.nearbyAvatars) == 1:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Chatty')
else:
self.notify.debug('avatarEnterNextState: in walk state')
else:
self.notify.debug('avatarEnterNextState: num avatars: ' + str(len(self.nearbyAvatars)))
def avatarExitNextState(self):
if len(self.nearbyAvatars) == 0:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Lonely')
def handleHolidays(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.handleHolidays(self)
if hasattr(simbase.air, 'holidayManager'):
if ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays:
if simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES] != None and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].getRunningState():
self.diffPath = TTLocalizer.Donald
return
def getCCLocation(self):
if self.diffPath == None:
return 1
else:
return 0
return
def enterTransitionToCostume(self):
pass
def exitTransitionToCostume(self):
pass
<|fim▁end|> | enterLonely |
<|file_name|>DistributedGoofySpeedwayAI.py<|end_file_name|><|fim▁begin|>from otp.ai.AIBaseGlobal import *
import DistributedCCharBaseAI
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from direct.task import Task
import random
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
import CharStateDatasAI
class DistributedGoofySpeedwayAI(DistributedCCharBaseAI.DistributedCCharBaseAI):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedGoofySpeedwayAI')
def __init__(self, air):
DistributedCCharBaseAI.DistributedCCharBaseAI.__init__(self, air, TTLocalizer.Goofy)
self.fsm = ClassicFSM.ClassicFSM('DistributedGoofySpeedwayAI', [State.State('Off', self.enterOff, self.exitOff, ['Lonely', 'TransitionToCostume', 'Walk']),
State.State('Lonely', self.enterLonely, self.exitLonely, ['Chatty', 'Walk', 'TransitionToCostume']),
State.State('Chatty', self.enterChatty, self.exitChatty, ['Lonely', 'Walk', 'TransitionToCostume']),
State.State('Walk', self.enterWalk, self.exitWalk, ['Lonely', 'Chatty', 'TransitionToCostume']),
State.State('TransitionToCostume', self.enterTransitionToCostume, self.exitTransitionToCostume, ['Off'])], 'Off', 'Off')
self.fsm.enterInitialState()
self.handleHolidays()
def delete(self):
self.fsm.requestFinalState()
DistributedCCharBaseAI.DistributedCCharBaseAI.delete(self)
self.lonelyDoneEvent = None
self.lonely = None
self.chattyDoneEvent = None
self.chatty = None
self.walkDoneEvent = None
self.walk = None
return
def generate(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.generate(self)
name = self.getName()
self.lonelyDoneEvent = self.taskName(name + '-lonely-done')
self.lonely = CharStateDatasAI.CharLonelyStateAI(self.lonelyDoneEvent, self)
self.chattyDoneEvent = self.taskName(name + '-chatty-done')
self.chatty = CharStateDatasAI.CharChattyStateAI(self.chattyDoneEvent, self)
self.walkDoneEvent = self.taskName(name + '-walk-done')
if self.diffPath == None:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self)
else:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self, self.diffPath)
return
def walkSpeed(self):
return ToontownGlobals.GoofySpeed
def start(self):
self.fsm.request('Lonely')
def __decideNextState(self, doneStatus):
if self.transitionToCostume == 1:
curWalkNode = self.walk.getDestNode()
if simbase.air.holidayManager:
if ToontownGlobals.HALLOWEEN_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
elif ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
else:
self.notify.warning('transitionToCostume == 1 but no costume holiday')
else:
self.notify.warning('transitionToCostume == 1 but no holiday Manager')
if doneStatus['state'] == 'lonely' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'chatty' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'walk' and doneStatus['status'] == 'done':
if len(self.nearbyAvatars) > 0:
self.fsm.request('Chatty')
else:
self.fsm.request('Lonely')
def enterOff(self):
pass
def exitOff(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.exitOff(self)
def enterLonely(self):
self.lonely.enter()
self.acceptOnce(self.lonelyDoneEvent, self.__decideNextState)
def <|fim_middle|>(self):
self.ignore(self.lonelyDoneEvent)
self.lonely.exit()
def __goForAWalk(self, task):
self.notify.debug('going for a walk')
self.fsm.request('Walk')
return Task.done
def enterChatty(self):
self.chatty.enter()
self.acceptOnce(self.chattyDoneEvent, self.__decideNextState)
def exitChatty(self):
self.ignore(self.chattyDoneEvent)
self.chatty.exit()
def enterWalk(self):
self.notify.debug('going for a walk')
self.walk.enter()
self.acceptOnce(self.walkDoneEvent, self.__decideNextState)
def exitWalk(self):
self.ignore(self.walkDoneEvent)
self.walk.exit()
def avatarEnterNextState(self):
if len(self.nearbyAvatars) == 1:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Chatty')
else:
self.notify.debug('avatarEnterNextState: in walk state')
else:
self.notify.debug('avatarEnterNextState: num avatars: ' + str(len(self.nearbyAvatars)))
def avatarExitNextState(self):
if len(self.nearbyAvatars) == 0:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Lonely')
def handleHolidays(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.handleHolidays(self)
if hasattr(simbase.air, 'holidayManager'):
if ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays:
if simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES] != None and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].getRunningState():
self.diffPath = TTLocalizer.Donald
return
def getCCLocation(self):
if self.diffPath == None:
return 1
else:
return 0
return
def enterTransitionToCostume(self):
pass
def exitTransitionToCostume(self):
pass
<|fim▁end|> | exitLonely |
<|file_name|>DistributedGoofySpeedwayAI.py<|end_file_name|><|fim▁begin|>from otp.ai.AIBaseGlobal import *
import DistributedCCharBaseAI
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from direct.task import Task
import random
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
import CharStateDatasAI
class DistributedGoofySpeedwayAI(DistributedCCharBaseAI.DistributedCCharBaseAI):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedGoofySpeedwayAI')
def __init__(self, air):
DistributedCCharBaseAI.DistributedCCharBaseAI.__init__(self, air, TTLocalizer.Goofy)
self.fsm = ClassicFSM.ClassicFSM('DistributedGoofySpeedwayAI', [State.State('Off', self.enterOff, self.exitOff, ['Lonely', 'TransitionToCostume', 'Walk']),
State.State('Lonely', self.enterLonely, self.exitLonely, ['Chatty', 'Walk', 'TransitionToCostume']),
State.State('Chatty', self.enterChatty, self.exitChatty, ['Lonely', 'Walk', 'TransitionToCostume']),
State.State('Walk', self.enterWalk, self.exitWalk, ['Lonely', 'Chatty', 'TransitionToCostume']),
State.State('TransitionToCostume', self.enterTransitionToCostume, self.exitTransitionToCostume, ['Off'])], 'Off', 'Off')
self.fsm.enterInitialState()
self.handleHolidays()
def delete(self):
self.fsm.requestFinalState()
DistributedCCharBaseAI.DistributedCCharBaseAI.delete(self)
self.lonelyDoneEvent = None
self.lonely = None
self.chattyDoneEvent = None
self.chatty = None
self.walkDoneEvent = None
self.walk = None
return
def generate(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.generate(self)
name = self.getName()
self.lonelyDoneEvent = self.taskName(name + '-lonely-done')
self.lonely = CharStateDatasAI.CharLonelyStateAI(self.lonelyDoneEvent, self)
self.chattyDoneEvent = self.taskName(name + '-chatty-done')
self.chatty = CharStateDatasAI.CharChattyStateAI(self.chattyDoneEvent, self)
self.walkDoneEvent = self.taskName(name + '-walk-done')
if self.diffPath == None:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self)
else:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self, self.diffPath)
return
def walkSpeed(self):
return ToontownGlobals.GoofySpeed
def start(self):
self.fsm.request('Lonely')
def __decideNextState(self, doneStatus):
if self.transitionToCostume == 1:
curWalkNode = self.walk.getDestNode()
if simbase.air.holidayManager:
if ToontownGlobals.HALLOWEEN_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
elif ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
else:
self.notify.warning('transitionToCostume == 1 but no costume holiday')
else:
self.notify.warning('transitionToCostume == 1 but no holiday Manager')
if doneStatus['state'] == 'lonely' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'chatty' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'walk' and doneStatus['status'] == 'done':
if len(self.nearbyAvatars) > 0:
self.fsm.request('Chatty')
else:
self.fsm.request('Lonely')
def enterOff(self):
pass
def exitOff(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.exitOff(self)
def enterLonely(self):
self.lonely.enter()
self.acceptOnce(self.lonelyDoneEvent, self.__decideNextState)
def exitLonely(self):
self.ignore(self.lonelyDoneEvent)
self.lonely.exit()
def <|fim_middle|>(self, task):
self.notify.debug('going for a walk')
self.fsm.request('Walk')
return Task.done
def enterChatty(self):
self.chatty.enter()
self.acceptOnce(self.chattyDoneEvent, self.__decideNextState)
def exitChatty(self):
self.ignore(self.chattyDoneEvent)
self.chatty.exit()
def enterWalk(self):
self.notify.debug('going for a walk')
self.walk.enter()
self.acceptOnce(self.walkDoneEvent, self.__decideNextState)
def exitWalk(self):
self.ignore(self.walkDoneEvent)
self.walk.exit()
def avatarEnterNextState(self):
if len(self.nearbyAvatars) == 1:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Chatty')
else:
self.notify.debug('avatarEnterNextState: in walk state')
else:
self.notify.debug('avatarEnterNextState: num avatars: ' + str(len(self.nearbyAvatars)))
def avatarExitNextState(self):
if len(self.nearbyAvatars) == 0:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Lonely')
def handleHolidays(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.handleHolidays(self)
if hasattr(simbase.air, 'holidayManager'):
if ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays:
if simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES] != None and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].getRunningState():
self.diffPath = TTLocalizer.Donald
return
def getCCLocation(self):
if self.diffPath == None:
return 1
else:
return 0
return
def enterTransitionToCostume(self):
pass
def exitTransitionToCostume(self):
pass
<|fim▁end|> | __goForAWalk |
<|file_name|>DistributedGoofySpeedwayAI.py<|end_file_name|><|fim▁begin|>from otp.ai.AIBaseGlobal import *
import DistributedCCharBaseAI
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from direct.task import Task
import random
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
import CharStateDatasAI
class DistributedGoofySpeedwayAI(DistributedCCharBaseAI.DistributedCCharBaseAI):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedGoofySpeedwayAI')
def __init__(self, air):
DistributedCCharBaseAI.DistributedCCharBaseAI.__init__(self, air, TTLocalizer.Goofy)
self.fsm = ClassicFSM.ClassicFSM('DistributedGoofySpeedwayAI', [State.State('Off', self.enterOff, self.exitOff, ['Lonely', 'TransitionToCostume', 'Walk']),
State.State('Lonely', self.enterLonely, self.exitLonely, ['Chatty', 'Walk', 'TransitionToCostume']),
State.State('Chatty', self.enterChatty, self.exitChatty, ['Lonely', 'Walk', 'TransitionToCostume']),
State.State('Walk', self.enterWalk, self.exitWalk, ['Lonely', 'Chatty', 'TransitionToCostume']),
State.State('TransitionToCostume', self.enterTransitionToCostume, self.exitTransitionToCostume, ['Off'])], 'Off', 'Off')
self.fsm.enterInitialState()
self.handleHolidays()
def delete(self):
self.fsm.requestFinalState()
DistributedCCharBaseAI.DistributedCCharBaseAI.delete(self)
self.lonelyDoneEvent = None
self.lonely = None
self.chattyDoneEvent = None
self.chatty = None
self.walkDoneEvent = None
self.walk = None
return
def generate(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.generate(self)
name = self.getName()
self.lonelyDoneEvent = self.taskName(name + '-lonely-done')
self.lonely = CharStateDatasAI.CharLonelyStateAI(self.lonelyDoneEvent, self)
self.chattyDoneEvent = self.taskName(name + '-chatty-done')
self.chatty = CharStateDatasAI.CharChattyStateAI(self.chattyDoneEvent, self)
self.walkDoneEvent = self.taskName(name + '-walk-done')
if self.diffPath == None:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self)
else:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self, self.diffPath)
return
def walkSpeed(self):
return ToontownGlobals.GoofySpeed
def start(self):
self.fsm.request('Lonely')
def __decideNextState(self, doneStatus):
if self.transitionToCostume == 1:
curWalkNode = self.walk.getDestNode()
if simbase.air.holidayManager:
if ToontownGlobals.HALLOWEEN_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
elif ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
else:
self.notify.warning('transitionToCostume == 1 but no costume holiday')
else:
self.notify.warning('transitionToCostume == 1 but no holiday Manager')
if doneStatus['state'] == 'lonely' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'chatty' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'walk' and doneStatus['status'] == 'done':
if len(self.nearbyAvatars) > 0:
self.fsm.request('Chatty')
else:
self.fsm.request('Lonely')
def enterOff(self):
pass
def exitOff(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.exitOff(self)
def enterLonely(self):
self.lonely.enter()
self.acceptOnce(self.lonelyDoneEvent, self.__decideNextState)
def exitLonely(self):
self.ignore(self.lonelyDoneEvent)
self.lonely.exit()
def __goForAWalk(self, task):
self.notify.debug('going for a walk')
self.fsm.request('Walk')
return Task.done
def <|fim_middle|>(self):
self.chatty.enter()
self.acceptOnce(self.chattyDoneEvent, self.__decideNextState)
def exitChatty(self):
self.ignore(self.chattyDoneEvent)
self.chatty.exit()
def enterWalk(self):
self.notify.debug('going for a walk')
self.walk.enter()
self.acceptOnce(self.walkDoneEvent, self.__decideNextState)
def exitWalk(self):
self.ignore(self.walkDoneEvent)
self.walk.exit()
def avatarEnterNextState(self):
if len(self.nearbyAvatars) == 1:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Chatty')
else:
self.notify.debug('avatarEnterNextState: in walk state')
else:
self.notify.debug('avatarEnterNextState: num avatars: ' + str(len(self.nearbyAvatars)))
def avatarExitNextState(self):
if len(self.nearbyAvatars) == 0:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Lonely')
def handleHolidays(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.handleHolidays(self)
if hasattr(simbase.air, 'holidayManager'):
if ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays:
if simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES] != None and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].getRunningState():
self.diffPath = TTLocalizer.Donald
return
def getCCLocation(self):
if self.diffPath == None:
return 1
else:
return 0
return
def enterTransitionToCostume(self):
pass
def exitTransitionToCostume(self):
pass
<|fim▁end|> | enterChatty |
<|file_name|>DistributedGoofySpeedwayAI.py<|end_file_name|><|fim▁begin|>from otp.ai.AIBaseGlobal import *
import DistributedCCharBaseAI
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from direct.task import Task
import random
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
import CharStateDatasAI
class DistributedGoofySpeedwayAI(DistributedCCharBaseAI.DistributedCCharBaseAI):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedGoofySpeedwayAI')
def __init__(self, air):
DistributedCCharBaseAI.DistributedCCharBaseAI.__init__(self, air, TTLocalizer.Goofy)
self.fsm = ClassicFSM.ClassicFSM('DistributedGoofySpeedwayAI', [State.State('Off', self.enterOff, self.exitOff, ['Lonely', 'TransitionToCostume', 'Walk']),
State.State('Lonely', self.enterLonely, self.exitLonely, ['Chatty', 'Walk', 'TransitionToCostume']),
State.State('Chatty', self.enterChatty, self.exitChatty, ['Lonely', 'Walk', 'TransitionToCostume']),
State.State('Walk', self.enterWalk, self.exitWalk, ['Lonely', 'Chatty', 'TransitionToCostume']),
State.State('TransitionToCostume', self.enterTransitionToCostume, self.exitTransitionToCostume, ['Off'])], 'Off', 'Off')
self.fsm.enterInitialState()
self.handleHolidays()
def delete(self):
self.fsm.requestFinalState()
DistributedCCharBaseAI.DistributedCCharBaseAI.delete(self)
self.lonelyDoneEvent = None
self.lonely = None
self.chattyDoneEvent = None
self.chatty = None
self.walkDoneEvent = None
self.walk = None
return
def generate(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.generate(self)
name = self.getName()
self.lonelyDoneEvent = self.taskName(name + '-lonely-done')
self.lonely = CharStateDatasAI.CharLonelyStateAI(self.lonelyDoneEvent, self)
self.chattyDoneEvent = self.taskName(name + '-chatty-done')
self.chatty = CharStateDatasAI.CharChattyStateAI(self.chattyDoneEvent, self)
self.walkDoneEvent = self.taskName(name + '-walk-done')
if self.diffPath == None:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self)
else:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self, self.diffPath)
return
def walkSpeed(self):
return ToontownGlobals.GoofySpeed
def start(self):
self.fsm.request('Lonely')
def __decideNextState(self, doneStatus):
if self.transitionToCostume == 1:
curWalkNode = self.walk.getDestNode()
if simbase.air.holidayManager:
if ToontownGlobals.HALLOWEEN_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
elif ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
else:
self.notify.warning('transitionToCostume == 1 but no costume holiday')
else:
self.notify.warning('transitionToCostume == 1 but no holiday Manager')
if doneStatus['state'] == 'lonely' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'chatty' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'walk' and doneStatus['status'] == 'done':
if len(self.nearbyAvatars) > 0:
self.fsm.request('Chatty')
else:
self.fsm.request('Lonely')
def enterOff(self):
pass
def exitOff(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.exitOff(self)
def enterLonely(self):
self.lonely.enter()
self.acceptOnce(self.lonelyDoneEvent, self.__decideNextState)
def exitLonely(self):
self.ignore(self.lonelyDoneEvent)
self.lonely.exit()
def __goForAWalk(self, task):
self.notify.debug('going for a walk')
self.fsm.request('Walk')
return Task.done
def enterChatty(self):
self.chatty.enter()
self.acceptOnce(self.chattyDoneEvent, self.__decideNextState)
def <|fim_middle|>(self):
self.ignore(self.chattyDoneEvent)
self.chatty.exit()
def enterWalk(self):
self.notify.debug('going for a walk')
self.walk.enter()
self.acceptOnce(self.walkDoneEvent, self.__decideNextState)
def exitWalk(self):
self.ignore(self.walkDoneEvent)
self.walk.exit()
def avatarEnterNextState(self):
if len(self.nearbyAvatars) == 1:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Chatty')
else:
self.notify.debug('avatarEnterNextState: in walk state')
else:
self.notify.debug('avatarEnterNextState: num avatars: ' + str(len(self.nearbyAvatars)))
def avatarExitNextState(self):
if len(self.nearbyAvatars) == 0:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Lonely')
def handleHolidays(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.handleHolidays(self)
if hasattr(simbase.air, 'holidayManager'):
if ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays:
if simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES] != None and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].getRunningState():
self.diffPath = TTLocalizer.Donald
return
def getCCLocation(self):
if self.diffPath == None:
return 1
else:
return 0
return
def enterTransitionToCostume(self):
pass
def exitTransitionToCostume(self):
pass
<|fim▁end|> | exitChatty |
<|file_name|>DistributedGoofySpeedwayAI.py<|end_file_name|><|fim▁begin|>from otp.ai.AIBaseGlobal import *
import DistributedCCharBaseAI
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from direct.task import Task
import random
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
import CharStateDatasAI
class DistributedGoofySpeedwayAI(DistributedCCharBaseAI.DistributedCCharBaseAI):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedGoofySpeedwayAI')
def __init__(self, air):
DistributedCCharBaseAI.DistributedCCharBaseAI.__init__(self, air, TTLocalizer.Goofy)
self.fsm = ClassicFSM.ClassicFSM('DistributedGoofySpeedwayAI', [State.State('Off', self.enterOff, self.exitOff, ['Lonely', 'TransitionToCostume', 'Walk']),
State.State('Lonely', self.enterLonely, self.exitLonely, ['Chatty', 'Walk', 'TransitionToCostume']),
State.State('Chatty', self.enterChatty, self.exitChatty, ['Lonely', 'Walk', 'TransitionToCostume']),
State.State('Walk', self.enterWalk, self.exitWalk, ['Lonely', 'Chatty', 'TransitionToCostume']),
State.State('TransitionToCostume', self.enterTransitionToCostume, self.exitTransitionToCostume, ['Off'])], 'Off', 'Off')
self.fsm.enterInitialState()
self.handleHolidays()
def delete(self):
self.fsm.requestFinalState()
DistributedCCharBaseAI.DistributedCCharBaseAI.delete(self)
self.lonelyDoneEvent = None
self.lonely = None
self.chattyDoneEvent = None
self.chatty = None
self.walkDoneEvent = None
self.walk = None
return
def generate(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.generate(self)
name = self.getName()
self.lonelyDoneEvent = self.taskName(name + '-lonely-done')
self.lonely = CharStateDatasAI.CharLonelyStateAI(self.lonelyDoneEvent, self)
self.chattyDoneEvent = self.taskName(name + '-chatty-done')
self.chatty = CharStateDatasAI.CharChattyStateAI(self.chattyDoneEvent, self)
self.walkDoneEvent = self.taskName(name + '-walk-done')
if self.diffPath == None:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self)
else:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self, self.diffPath)
return
def walkSpeed(self):
return ToontownGlobals.GoofySpeed
def start(self):
self.fsm.request('Lonely')
def __decideNextState(self, doneStatus):
if self.transitionToCostume == 1:
curWalkNode = self.walk.getDestNode()
if simbase.air.holidayManager:
if ToontownGlobals.HALLOWEEN_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
elif ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
else:
self.notify.warning('transitionToCostume == 1 but no costume holiday')
else:
self.notify.warning('transitionToCostume == 1 but no holiday Manager')
if doneStatus['state'] == 'lonely' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'chatty' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'walk' and doneStatus['status'] == 'done':
if len(self.nearbyAvatars) > 0:
self.fsm.request('Chatty')
else:
self.fsm.request('Lonely')
def enterOff(self):
pass
def exitOff(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.exitOff(self)
def enterLonely(self):
self.lonely.enter()
self.acceptOnce(self.lonelyDoneEvent, self.__decideNextState)
def exitLonely(self):
self.ignore(self.lonelyDoneEvent)
self.lonely.exit()
def __goForAWalk(self, task):
self.notify.debug('going for a walk')
self.fsm.request('Walk')
return Task.done
def enterChatty(self):
self.chatty.enter()
self.acceptOnce(self.chattyDoneEvent, self.__decideNextState)
def exitChatty(self):
self.ignore(self.chattyDoneEvent)
self.chatty.exit()
def <|fim_middle|>(self):
self.notify.debug('going for a walk')
self.walk.enter()
self.acceptOnce(self.walkDoneEvent, self.__decideNextState)
def exitWalk(self):
self.ignore(self.walkDoneEvent)
self.walk.exit()
def avatarEnterNextState(self):
if len(self.nearbyAvatars) == 1:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Chatty')
else:
self.notify.debug('avatarEnterNextState: in walk state')
else:
self.notify.debug('avatarEnterNextState: num avatars: ' + str(len(self.nearbyAvatars)))
def avatarExitNextState(self):
if len(self.nearbyAvatars) == 0:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Lonely')
def handleHolidays(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.handleHolidays(self)
if hasattr(simbase.air, 'holidayManager'):
if ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays:
if simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES] != None and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].getRunningState():
self.diffPath = TTLocalizer.Donald
return
def getCCLocation(self):
if self.diffPath == None:
return 1
else:
return 0
return
def enterTransitionToCostume(self):
pass
def exitTransitionToCostume(self):
pass
<|fim▁end|> | enterWalk |
<|file_name|>DistributedGoofySpeedwayAI.py<|end_file_name|><|fim▁begin|>from otp.ai.AIBaseGlobal import *
import DistributedCCharBaseAI
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from direct.task import Task
import random
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
import CharStateDatasAI
class DistributedGoofySpeedwayAI(DistributedCCharBaseAI.DistributedCCharBaseAI):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedGoofySpeedwayAI')
def __init__(self, air):
DistributedCCharBaseAI.DistributedCCharBaseAI.__init__(self, air, TTLocalizer.Goofy)
self.fsm = ClassicFSM.ClassicFSM('DistributedGoofySpeedwayAI', [State.State('Off', self.enterOff, self.exitOff, ['Lonely', 'TransitionToCostume', 'Walk']),
State.State('Lonely', self.enterLonely, self.exitLonely, ['Chatty', 'Walk', 'TransitionToCostume']),
State.State('Chatty', self.enterChatty, self.exitChatty, ['Lonely', 'Walk', 'TransitionToCostume']),
State.State('Walk', self.enterWalk, self.exitWalk, ['Lonely', 'Chatty', 'TransitionToCostume']),
State.State('TransitionToCostume', self.enterTransitionToCostume, self.exitTransitionToCostume, ['Off'])], 'Off', 'Off')
self.fsm.enterInitialState()
self.handleHolidays()
def delete(self):
self.fsm.requestFinalState()
DistributedCCharBaseAI.DistributedCCharBaseAI.delete(self)
self.lonelyDoneEvent = None
self.lonely = None
self.chattyDoneEvent = None
self.chatty = None
self.walkDoneEvent = None
self.walk = None
return
def generate(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.generate(self)
name = self.getName()
self.lonelyDoneEvent = self.taskName(name + '-lonely-done')
self.lonely = CharStateDatasAI.CharLonelyStateAI(self.lonelyDoneEvent, self)
self.chattyDoneEvent = self.taskName(name + '-chatty-done')
self.chatty = CharStateDatasAI.CharChattyStateAI(self.chattyDoneEvent, self)
self.walkDoneEvent = self.taskName(name + '-walk-done')
if self.diffPath == None:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self)
else:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self, self.diffPath)
return
def walkSpeed(self):
return ToontownGlobals.GoofySpeed
def start(self):
self.fsm.request('Lonely')
def __decideNextState(self, doneStatus):
if self.transitionToCostume == 1:
curWalkNode = self.walk.getDestNode()
if simbase.air.holidayManager:
if ToontownGlobals.HALLOWEEN_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
elif ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
else:
self.notify.warning('transitionToCostume == 1 but no costume holiday')
else:
self.notify.warning('transitionToCostume == 1 but no holiday Manager')
if doneStatus['state'] == 'lonely' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'chatty' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'walk' and doneStatus['status'] == 'done':
if len(self.nearbyAvatars) > 0:
self.fsm.request('Chatty')
else:
self.fsm.request('Lonely')
def enterOff(self):
pass
def exitOff(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.exitOff(self)
def enterLonely(self):
self.lonely.enter()
self.acceptOnce(self.lonelyDoneEvent, self.__decideNextState)
def exitLonely(self):
self.ignore(self.lonelyDoneEvent)
self.lonely.exit()
def __goForAWalk(self, task):
self.notify.debug('going for a walk')
self.fsm.request('Walk')
return Task.done
def enterChatty(self):
self.chatty.enter()
self.acceptOnce(self.chattyDoneEvent, self.__decideNextState)
def exitChatty(self):
self.ignore(self.chattyDoneEvent)
self.chatty.exit()
def enterWalk(self):
self.notify.debug('going for a walk')
self.walk.enter()
self.acceptOnce(self.walkDoneEvent, self.__decideNextState)
def <|fim_middle|>(self):
self.ignore(self.walkDoneEvent)
self.walk.exit()
def avatarEnterNextState(self):
if len(self.nearbyAvatars) == 1:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Chatty')
else:
self.notify.debug('avatarEnterNextState: in walk state')
else:
self.notify.debug('avatarEnterNextState: num avatars: ' + str(len(self.nearbyAvatars)))
def avatarExitNextState(self):
if len(self.nearbyAvatars) == 0:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Lonely')
def handleHolidays(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.handleHolidays(self)
if hasattr(simbase.air, 'holidayManager'):
if ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays:
if simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES] != None and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].getRunningState():
self.diffPath = TTLocalizer.Donald
return
def getCCLocation(self):
if self.diffPath == None:
return 1
else:
return 0
return
def enterTransitionToCostume(self):
pass
def exitTransitionToCostume(self):
pass
<|fim▁end|> | exitWalk |
<|file_name|>DistributedGoofySpeedwayAI.py<|end_file_name|><|fim▁begin|>from otp.ai.AIBaseGlobal import *
import DistributedCCharBaseAI
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from direct.task import Task
import random
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
import CharStateDatasAI
class DistributedGoofySpeedwayAI(DistributedCCharBaseAI.DistributedCCharBaseAI):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedGoofySpeedwayAI')
def __init__(self, air):
DistributedCCharBaseAI.DistributedCCharBaseAI.__init__(self, air, TTLocalizer.Goofy)
self.fsm = ClassicFSM.ClassicFSM('DistributedGoofySpeedwayAI', [State.State('Off', self.enterOff, self.exitOff, ['Lonely', 'TransitionToCostume', 'Walk']),
State.State('Lonely', self.enterLonely, self.exitLonely, ['Chatty', 'Walk', 'TransitionToCostume']),
State.State('Chatty', self.enterChatty, self.exitChatty, ['Lonely', 'Walk', 'TransitionToCostume']),
State.State('Walk', self.enterWalk, self.exitWalk, ['Lonely', 'Chatty', 'TransitionToCostume']),
State.State('TransitionToCostume', self.enterTransitionToCostume, self.exitTransitionToCostume, ['Off'])], 'Off', 'Off')
self.fsm.enterInitialState()
self.handleHolidays()
def delete(self):
self.fsm.requestFinalState()
DistributedCCharBaseAI.DistributedCCharBaseAI.delete(self)
self.lonelyDoneEvent = None
self.lonely = None
self.chattyDoneEvent = None
self.chatty = None
self.walkDoneEvent = None
self.walk = None
return
def generate(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.generate(self)
name = self.getName()
self.lonelyDoneEvent = self.taskName(name + '-lonely-done')
self.lonely = CharStateDatasAI.CharLonelyStateAI(self.lonelyDoneEvent, self)
self.chattyDoneEvent = self.taskName(name + '-chatty-done')
self.chatty = CharStateDatasAI.CharChattyStateAI(self.chattyDoneEvent, self)
self.walkDoneEvent = self.taskName(name + '-walk-done')
if self.diffPath == None:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self)
else:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self, self.diffPath)
return
def walkSpeed(self):
return ToontownGlobals.GoofySpeed
def start(self):
self.fsm.request('Lonely')
def __decideNextState(self, doneStatus):
if self.transitionToCostume == 1:
curWalkNode = self.walk.getDestNode()
if simbase.air.holidayManager:
if ToontownGlobals.HALLOWEEN_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
elif ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
else:
self.notify.warning('transitionToCostume == 1 but no costume holiday')
else:
self.notify.warning('transitionToCostume == 1 but no holiday Manager')
if doneStatus['state'] == 'lonely' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'chatty' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'walk' and doneStatus['status'] == 'done':
if len(self.nearbyAvatars) > 0:
self.fsm.request('Chatty')
else:
self.fsm.request('Lonely')
def enterOff(self):
pass
def exitOff(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.exitOff(self)
def enterLonely(self):
self.lonely.enter()
self.acceptOnce(self.lonelyDoneEvent, self.__decideNextState)
def exitLonely(self):
self.ignore(self.lonelyDoneEvent)
self.lonely.exit()
def __goForAWalk(self, task):
self.notify.debug('going for a walk')
self.fsm.request('Walk')
return Task.done
def enterChatty(self):
self.chatty.enter()
self.acceptOnce(self.chattyDoneEvent, self.__decideNextState)
def exitChatty(self):
self.ignore(self.chattyDoneEvent)
self.chatty.exit()
def enterWalk(self):
self.notify.debug('going for a walk')
self.walk.enter()
self.acceptOnce(self.walkDoneEvent, self.__decideNextState)
def exitWalk(self):
self.ignore(self.walkDoneEvent)
self.walk.exit()
def <|fim_middle|>(self):
if len(self.nearbyAvatars) == 1:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Chatty')
else:
self.notify.debug('avatarEnterNextState: in walk state')
else:
self.notify.debug('avatarEnterNextState: num avatars: ' + str(len(self.nearbyAvatars)))
def avatarExitNextState(self):
if len(self.nearbyAvatars) == 0:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Lonely')
def handleHolidays(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.handleHolidays(self)
if hasattr(simbase.air, 'holidayManager'):
if ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays:
if simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES] != None and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].getRunningState():
self.diffPath = TTLocalizer.Donald
return
def getCCLocation(self):
if self.diffPath == None:
return 1
else:
return 0
return
def enterTransitionToCostume(self):
pass
def exitTransitionToCostume(self):
pass
<|fim▁end|> | avatarEnterNextState |
<|file_name|>DistributedGoofySpeedwayAI.py<|end_file_name|><|fim▁begin|>from otp.ai.AIBaseGlobal import *
import DistributedCCharBaseAI
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from direct.task import Task
import random
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
import CharStateDatasAI
class DistributedGoofySpeedwayAI(DistributedCCharBaseAI.DistributedCCharBaseAI):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedGoofySpeedwayAI')
def __init__(self, air):
DistributedCCharBaseAI.DistributedCCharBaseAI.__init__(self, air, TTLocalizer.Goofy)
self.fsm = ClassicFSM.ClassicFSM('DistributedGoofySpeedwayAI', [State.State('Off', self.enterOff, self.exitOff, ['Lonely', 'TransitionToCostume', 'Walk']),
State.State('Lonely', self.enterLonely, self.exitLonely, ['Chatty', 'Walk', 'TransitionToCostume']),
State.State('Chatty', self.enterChatty, self.exitChatty, ['Lonely', 'Walk', 'TransitionToCostume']),
State.State('Walk', self.enterWalk, self.exitWalk, ['Lonely', 'Chatty', 'TransitionToCostume']),
State.State('TransitionToCostume', self.enterTransitionToCostume, self.exitTransitionToCostume, ['Off'])], 'Off', 'Off')
self.fsm.enterInitialState()
self.handleHolidays()
def delete(self):
self.fsm.requestFinalState()
DistributedCCharBaseAI.DistributedCCharBaseAI.delete(self)
self.lonelyDoneEvent = None
self.lonely = None
self.chattyDoneEvent = None
self.chatty = None
self.walkDoneEvent = None
self.walk = None
return
def generate(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.generate(self)
name = self.getName()
self.lonelyDoneEvent = self.taskName(name + '-lonely-done')
self.lonely = CharStateDatasAI.CharLonelyStateAI(self.lonelyDoneEvent, self)
self.chattyDoneEvent = self.taskName(name + '-chatty-done')
self.chatty = CharStateDatasAI.CharChattyStateAI(self.chattyDoneEvent, self)
self.walkDoneEvent = self.taskName(name + '-walk-done')
if self.diffPath == None:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self)
else:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self, self.diffPath)
return
def walkSpeed(self):
return ToontownGlobals.GoofySpeed
def start(self):
self.fsm.request('Lonely')
def __decideNextState(self, doneStatus):
if self.transitionToCostume == 1:
curWalkNode = self.walk.getDestNode()
if simbase.air.holidayManager:
if ToontownGlobals.HALLOWEEN_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
elif ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
else:
self.notify.warning('transitionToCostume == 1 but no costume holiday')
else:
self.notify.warning('transitionToCostume == 1 but no holiday Manager')
if doneStatus['state'] == 'lonely' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'chatty' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'walk' and doneStatus['status'] == 'done':
if len(self.nearbyAvatars) > 0:
self.fsm.request('Chatty')
else:
self.fsm.request('Lonely')
def enterOff(self):
pass
def exitOff(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.exitOff(self)
def enterLonely(self):
self.lonely.enter()
self.acceptOnce(self.lonelyDoneEvent, self.__decideNextState)
def exitLonely(self):
self.ignore(self.lonelyDoneEvent)
self.lonely.exit()
def __goForAWalk(self, task):
self.notify.debug('going for a walk')
self.fsm.request('Walk')
return Task.done
def enterChatty(self):
self.chatty.enter()
self.acceptOnce(self.chattyDoneEvent, self.__decideNextState)
def exitChatty(self):
self.ignore(self.chattyDoneEvent)
self.chatty.exit()
def enterWalk(self):
self.notify.debug('going for a walk')
self.walk.enter()
self.acceptOnce(self.walkDoneEvent, self.__decideNextState)
def exitWalk(self):
self.ignore(self.walkDoneEvent)
self.walk.exit()
def avatarEnterNextState(self):
if len(self.nearbyAvatars) == 1:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Chatty')
else:
self.notify.debug('avatarEnterNextState: in walk state')
else:
self.notify.debug('avatarEnterNextState: num avatars: ' + str(len(self.nearbyAvatars)))
def <|fim_middle|>(self):
if len(self.nearbyAvatars) == 0:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Lonely')
def handleHolidays(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.handleHolidays(self)
if hasattr(simbase.air, 'holidayManager'):
if ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays:
if simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES] != None and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].getRunningState():
self.diffPath = TTLocalizer.Donald
return
def getCCLocation(self):
if self.diffPath == None:
return 1
else:
return 0
return
def enterTransitionToCostume(self):
pass
def exitTransitionToCostume(self):
pass
<|fim▁end|> | avatarExitNextState |
<|file_name|>DistributedGoofySpeedwayAI.py<|end_file_name|><|fim▁begin|>from otp.ai.AIBaseGlobal import *
import DistributedCCharBaseAI
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from direct.task import Task
import random
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
import CharStateDatasAI
class DistributedGoofySpeedwayAI(DistributedCCharBaseAI.DistributedCCharBaseAI):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedGoofySpeedwayAI')
def __init__(self, air):
DistributedCCharBaseAI.DistributedCCharBaseAI.__init__(self, air, TTLocalizer.Goofy)
self.fsm = ClassicFSM.ClassicFSM('DistributedGoofySpeedwayAI', [State.State('Off', self.enterOff, self.exitOff, ['Lonely', 'TransitionToCostume', 'Walk']),
State.State('Lonely', self.enterLonely, self.exitLonely, ['Chatty', 'Walk', 'TransitionToCostume']),
State.State('Chatty', self.enterChatty, self.exitChatty, ['Lonely', 'Walk', 'TransitionToCostume']),
State.State('Walk', self.enterWalk, self.exitWalk, ['Lonely', 'Chatty', 'TransitionToCostume']),
State.State('TransitionToCostume', self.enterTransitionToCostume, self.exitTransitionToCostume, ['Off'])], 'Off', 'Off')
self.fsm.enterInitialState()
self.handleHolidays()
def delete(self):
self.fsm.requestFinalState()
DistributedCCharBaseAI.DistributedCCharBaseAI.delete(self)
self.lonelyDoneEvent = None
self.lonely = None
self.chattyDoneEvent = None
self.chatty = None
self.walkDoneEvent = None
self.walk = None
return
def generate(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.generate(self)
name = self.getName()
self.lonelyDoneEvent = self.taskName(name + '-lonely-done')
self.lonely = CharStateDatasAI.CharLonelyStateAI(self.lonelyDoneEvent, self)
self.chattyDoneEvent = self.taskName(name + '-chatty-done')
self.chatty = CharStateDatasAI.CharChattyStateAI(self.chattyDoneEvent, self)
self.walkDoneEvent = self.taskName(name + '-walk-done')
if self.diffPath == None:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self)
else:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self, self.diffPath)
return
def walkSpeed(self):
return ToontownGlobals.GoofySpeed
def start(self):
self.fsm.request('Lonely')
def __decideNextState(self, doneStatus):
if self.transitionToCostume == 1:
curWalkNode = self.walk.getDestNode()
if simbase.air.holidayManager:
if ToontownGlobals.HALLOWEEN_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
elif ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
else:
self.notify.warning('transitionToCostume == 1 but no costume holiday')
else:
self.notify.warning('transitionToCostume == 1 but no holiday Manager')
if doneStatus['state'] == 'lonely' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'chatty' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'walk' and doneStatus['status'] == 'done':
if len(self.nearbyAvatars) > 0:
self.fsm.request('Chatty')
else:
self.fsm.request('Lonely')
def enterOff(self):
pass
def exitOff(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.exitOff(self)
def enterLonely(self):
self.lonely.enter()
self.acceptOnce(self.lonelyDoneEvent, self.__decideNextState)
def exitLonely(self):
self.ignore(self.lonelyDoneEvent)
self.lonely.exit()
def __goForAWalk(self, task):
self.notify.debug('going for a walk')
self.fsm.request('Walk')
return Task.done
def enterChatty(self):
self.chatty.enter()
self.acceptOnce(self.chattyDoneEvent, self.__decideNextState)
def exitChatty(self):
self.ignore(self.chattyDoneEvent)
self.chatty.exit()
def enterWalk(self):
self.notify.debug('going for a walk')
self.walk.enter()
self.acceptOnce(self.walkDoneEvent, self.__decideNextState)
def exitWalk(self):
self.ignore(self.walkDoneEvent)
self.walk.exit()
def avatarEnterNextState(self):
if len(self.nearbyAvatars) == 1:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Chatty')
else:
self.notify.debug('avatarEnterNextState: in walk state')
else:
self.notify.debug('avatarEnterNextState: num avatars: ' + str(len(self.nearbyAvatars)))
def avatarExitNextState(self):
if len(self.nearbyAvatars) == 0:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Lonely')
def <|fim_middle|>(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.handleHolidays(self)
if hasattr(simbase.air, 'holidayManager'):
if ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays:
if simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES] != None and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].getRunningState():
self.diffPath = TTLocalizer.Donald
return
def getCCLocation(self):
if self.diffPath == None:
return 1
else:
return 0
return
def enterTransitionToCostume(self):
pass
def exitTransitionToCostume(self):
pass
<|fim▁end|> | handleHolidays |
<|file_name|>DistributedGoofySpeedwayAI.py<|end_file_name|><|fim▁begin|>from otp.ai.AIBaseGlobal import *
import DistributedCCharBaseAI
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from direct.task import Task
import random
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
import CharStateDatasAI
class DistributedGoofySpeedwayAI(DistributedCCharBaseAI.DistributedCCharBaseAI):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedGoofySpeedwayAI')
def __init__(self, air):
DistributedCCharBaseAI.DistributedCCharBaseAI.__init__(self, air, TTLocalizer.Goofy)
self.fsm = ClassicFSM.ClassicFSM('DistributedGoofySpeedwayAI', [State.State('Off', self.enterOff, self.exitOff, ['Lonely', 'TransitionToCostume', 'Walk']),
State.State('Lonely', self.enterLonely, self.exitLonely, ['Chatty', 'Walk', 'TransitionToCostume']),
State.State('Chatty', self.enterChatty, self.exitChatty, ['Lonely', 'Walk', 'TransitionToCostume']),
State.State('Walk', self.enterWalk, self.exitWalk, ['Lonely', 'Chatty', 'TransitionToCostume']),
State.State('TransitionToCostume', self.enterTransitionToCostume, self.exitTransitionToCostume, ['Off'])], 'Off', 'Off')
self.fsm.enterInitialState()
self.handleHolidays()
def delete(self):
self.fsm.requestFinalState()
DistributedCCharBaseAI.DistributedCCharBaseAI.delete(self)
self.lonelyDoneEvent = None
self.lonely = None
self.chattyDoneEvent = None
self.chatty = None
self.walkDoneEvent = None
self.walk = None
return
def generate(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.generate(self)
name = self.getName()
self.lonelyDoneEvent = self.taskName(name + '-lonely-done')
self.lonely = CharStateDatasAI.CharLonelyStateAI(self.lonelyDoneEvent, self)
self.chattyDoneEvent = self.taskName(name + '-chatty-done')
self.chatty = CharStateDatasAI.CharChattyStateAI(self.chattyDoneEvent, self)
self.walkDoneEvent = self.taskName(name + '-walk-done')
if self.diffPath == None:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self)
else:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self, self.diffPath)
return
def walkSpeed(self):
return ToontownGlobals.GoofySpeed
def start(self):
self.fsm.request('Lonely')
def __decideNextState(self, doneStatus):
if self.transitionToCostume == 1:
curWalkNode = self.walk.getDestNode()
if simbase.air.holidayManager:
if ToontownGlobals.HALLOWEEN_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
elif ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
else:
self.notify.warning('transitionToCostume == 1 but no costume holiday')
else:
self.notify.warning('transitionToCostume == 1 but no holiday Manager')
if doneStatus['state'] == 'lonely' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'chatty' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'walk' and doneStatus['status'] == 'done':
if len(self.nearbyAvatars) > 0:
self.fsm.request('Chatty')
else:
self.fsm.request('Lonely')
def enterOff(self):
pass
def exitOff(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.exitOff(self)
def enterLonely(self):
self.lonely.enter()
self.acceptOnce(self.lonelyDoneEvent, self.__decideNextState)
def exitLonely(self):
self.ignore(self.lonelyDoneEvent)
self.lonely.exit()
def __goForAWalk(self, task):
self.notify.debug('going for a walk')
self.fsm.request('Walk')
return Task.done
def enterChatty(self):
self.chatty.enter()
self.acceptOnce(self.chattyDoneEvent, self.__decideNextState)
def exitChatty(self):
self.ignore(self.chattyDoneEvent)
self.chatty.exit()
def enterWalk(self):
self.notify.debug('going for a walk')
self.walk.enter()
self.acceptOnce(self.walkDoneEvent, self.__decideNextState)
def exitWalk(self):
self.ignore(self.walkDoneEvent)
self.walk.exit()
def avatarEnterNextState(self):
if len(self.nearbyAvatars) == 1:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Chatty')
else:
self.notify.debug('avatarEnterNextState: in walk state')
else:
self.notify.debug('avatarEnterNextState: num avatars: ' + str(len(self.nearbyAvatars)))
def avatarExitNextState(self):
if len(self.nearbyAvatars) == 0:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Lonely')
def handleHolidays(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.handleHolidays(self)
if hasattr(simbase.air, 'holidayManager'):
if ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays:
if simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES] != None and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].getRunningState():
self.diffPath = TTLocalizer.Donald
return
def <|fim_middle|>(self):
if self.diffPath == None:
return 1
else:
return 0
return
def enterTransitionToCostume(self):
pass
def exitTransitionToCostume(self):
pass
<|fim▁end|> | getCCLocation |
<|file_name|>DistributedGoofySpeedwayAI.py<|end_file_name|><|fim▁begin|>from otp.ai.AIBaseGlobal import *
import DistributedCCharBaseAI
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from direct.task import Task
import random
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
import CharStateDatasAI
class DistributedGoofySpeedwayAI(DistributedCCharBaseAI.DistributedCCharBaseAI):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedGoofySpeedwayAI')
def __init__(self, air):
DistributedCCharBaseAI.DistributedCCharBaseAI.__init__(self, air, TTLocalizer.Goofy)
self.fsm = ClassicFSM.ClassicFSM('DistributedGoofySpeedwayAI', [State.State('Off', self.enterOff, self.exitOff, ['Lonely', 'TransitionToCostume', 'Walk']),
State.State('Lonely', self.enterLonely, self.exitLonely, ['Chatty', 'Walk', 'TransitionToCostume']),
State.State('Chatty', self.enterChatty, self.exitChatty, ['Lonely', 'Walk', 'TransitionToCostume']),
State.State('Walk', self.enterWalk, self.exitWalk, ['Lonely', 'Chatty', 'TransitionToCostume']),
State.State('TransitionToCostume', self.enterTransitionToCostume, self.exitTransitionToCostume, ['Off'])], 'Off', 'Off')
self.fsm.enterInitialState()
self.handleHolidays()
def delete(self):
self.fsm.requestFinalState()
DistributedCCharBaseAI.DistributedCCharBaseAI.delete(self)
self.lonelyDoneEvent = None
self.lonely = None
self.chattyDoneEvent = None
self.chatty = None
self.walkDoneEvent = None
self.walk = None
return
def generate(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.generate(self)
name = self.getName()
self.lonelyDoneEvent = self.taskName(name + '-lonely-done')
self.lonely = CharStateDatasAI.CharLonelyStateAI(self.lonelyDoneEvent, self)
self.chattyDoneEvent = self.taskName(name + '-chatty-done')
self.chatty = CharStateDatasAI.CharChattyStateAI(self.chattyDoneEvent, self)
self.walkDoneEvent = self.taskName(name + '-walk-done')
if self.diffPath == None:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self)
else:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self, self.diffPath)
return
def walkSpeed(self):
return ToontownGlobals.GoofySpeed
def start(self):
self.fsm.request('Lonely')
def __decideNextState(self, doneStatus):
if self.transitionToCostume == 1:
curWalkNode = self.walk.getDestNode()
if simbase.air.holidayManager:
if ToontownGlobals.HALLOWEEN_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
elif ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
else:
self.notify.warning('transitionToCostume == 1 but no costume holiday')
else:
self.notify.warning('transitionToCostume == 1 but no holiday Manager')
if doneStatus['state'] == 'lonely' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'chatty' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'walk' and doneStatus['status'] == 'done':
if len(self.nearbyAvatars) > 0:
self.fsm.request('Chatty')
else:
self.fsm.request('Lonely')
def enterOff(self):
pass
def exitOff(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.exitOff(self)
def enterLonely(self):
self.lonely.enter()
self.acceptOnce(self.lonelyDoneEvent, self.__decideNextState)
def exitLonely(self):
self.ignore(self.lonelyDoneEvent)
self.lonely.exit()
def __goForAWalk(self, task):
self.notify.debug('going for a walk')
self.fsm.request('Walk')
return Task.done
def enterChatty(self):
self.chatty.enter()
self.acceptOnce(self.chattyDoneEvent, self.__decideNextState)
def exitChatty(self):
self.ignore(self.chattyDoneEvent)
self.chatty.exit()
def enterWalk(self):
self.notify.debug('going for a walk')
self.walk.enter()
self.acceptOnce(self.walkDoneEvent, self.__decideNextState)
def exitWalk(self):
self.ignore(self.walkDoneEvent)
self.walk.exit()
def avatarEnterNextState(self):
if len(self.nearbyAvatars) == 1:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Chatty')
else:
self.notify.debug('avatarEnterNextState: in walk state')
else:
self.notify.debug('avatarEnterNextState: num avatars: ' + str(len(self.nearbyAvatars)))
def avatarExitNextState(self):
if len(self.nearbyAvatars) == 0:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Lonely')
def handleHolidays(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.handleHolidays(self)
if hasattr(simbase.air, 'holidayManager'):
if ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays:
if simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES] != None and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].getRunningState():
self.diffPath = TTLocalizer.Donald
return
def getCCLocation(self):
if self.diffPath == None:
return 1
else:
return 0
return
def <|fim_middle|>(self):
pass
def exitTransitionToCostume(self):
pass
<|fim▁end|> | enterTransitionToCostume |
<|file_name|>DistributedGoofySpeedwayAI.py<|end_file_name|><|fim▁begin|>from otp.ai.AIBaseGlobal import *
import DistributedCCharBaseAI
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from direct.task import Task
import random
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
import CharStateDatasAI
class DistributedGoofySpeedwayAI(DistributedCCharBaseAI.DistributedCCharBaseAI):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedGoofySpeedwayAI')
def __init__(self, air):
DistributedCCharBaseAI.DistributedCCharBaseAI.__init__(self, air, TTLocalizer.Goofy)
self.fsm = ClassicFSM.ClassicFSM('DistributedGoofySpeedwayAI', [State.State('Off', self.enterOff, self.exitOff, ['Lonely', 'TransitionToCostume', 'Walk']),
State.State('Lonely', self.enterLonely, self.exitLonely, ['Chatty', 'Walk', 'TransitionToCostume']),
State.State('Chatty', self.enterChatty, self.exitChatty, ['Lonely', 'Walk', 'TransitionToCostume']),
State.State('Walk', self.enterWalk, self.exitWalk, ['Lonely', 'Chatty', 'TransitionToCostume']),
State.State('TransitionToCostume', self.enterTransitionToCostume, self.exitTransitionToCostume, ['Off'])], 'Off', 'Off')
self.fsm.enterInitialState()
self.handleHolidays()
def delete(self):
self.fsm.requestFinalState()
DistributedCCharBaseAI.DistributedCCharBaseAI.delete(self)
self.lonelyDoneEvent = None
self.lonely = None
self.chattyDoneEvent = None
self.chatty = None
self.walkDoneEvent = None
self.walk = None
return
def generate(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.generate(self)
name = self.getName()
self.lonelyDoneEvent = self.taskName(name + '-lonely-done')
self.lonely = CharStateDatasAI.CharLonelyStateAI(self.lonelyDoneEvent, self)
self.chattyDoneEvent = self.taskName(name + '-chatty-done')
self.chatty = CharStateDatasAI.CharChattyStateAI(self.chattyDoneEvent, self)
self.walkDoneEvent = self.taskName(name + '-walk-done')
if self.diffPath == None:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self)
else:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self, self.diffPath)
return
def walkSpeed(self):
return ToontownGlobals.GoofySpeed
def start(self):
self.fsm.request('Lonely')
def __decideNextState(self, doneStatus):
if self.transitionToCostume == 1:
curWalkNode = self.walk.getDestNode()
if simbase.air.holidayManager:
if ToontownGlobals.HALLOWEEN_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
elif ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
else:
self.notify.warning('transitionToCostume == 1 but no costume holiday')
else:
self.notify.warning('transitionToCostume == 1 but no holiday Manager')
if doneStatus['state'] == 'lonely' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'chatty' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'walk' and doneStatus['status'] == 'done':
if len(self.nearbyAvatars) > 0:
self.fsm.request('Chatty')
else:
self.fsm.request('Lonely')
def enterOff(self):
pass
def exitOff(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.exitOff(self)
def enterLonely(self):
self.lonely.enter()
self.acceptOnce(self.lonelyDoneEvent, self.__decideNextState)
def exitLonely(self):
self.ignore(self.lonelyDoneEvent)
self.lonely.exit()
def __goForAWalk(self, task):
self.notify.debug('going for a walk')
self.fsm.request('Walk')
return Task.done
def enterChatty(self):
self.chatty.enter()
self.acceptOnce(self.chattyDoneEvent, self.__decideNextState)
def exitChatty(self):
self.ignore(self.chattyDoneEvent)
self.chatty.exit()
def enterWalk(self):
self.notify.debug('going for a walk')
self.walk.enter()
self.acceptOnce(self.walkDoneEvent, self.__decideNextState)
def exitWalk(self):
self.ignore(self.walkDoneEvent)
self.walk.exit()
def avatarEnterNextState(self):
if len(self.nearbyAvatars) == 1:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Chatty')
else:
self.notify.debug('avatarEnterNextState: in walk state')
else:
self.notify.debug('avatarEnterNextState: num avatars: ' + str(len(self.nearbyAvatars)))
def avatarExitNextState(self):
if len(self.nearbyAvatars) == 0:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Lonely')
def handleHolidays(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.handleHolidays(self)
if hasattr(simbase.air, 'holidayManager'):
if ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays:
if simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES] != None and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].getRunningState():
self.diffPath = TTLocalizer.Donald
return
def getCCLocation(self):
if self.diffPath == None:
return 1
else:
return 0
return
def enterTransitionToCostume(self):
pass
def <|fim_middle|>(self):
pass
<|fim▁end|> | exitTransitionToCostume |
<|file_name|>missing_record_ids.py<|end_file_name|><|fim▁begin|>from datetime import datetime
<|fim▁hole|>from flask import current_app
from flask.cli import with_appcontext
from invenio_db import db
from hepdata.cli import fix
from hepdata.ext.elasticsearch.api import index_record_ids, push_data_keywords
from hepdata.modules.submission.models import HEPSubmission, DataSubmission
from hepdata.modules.records.utils.common import get_record_by_id
from hepdata.modules.records.utils.doi_minter import generate_doi_for_table
from hepdata.modules.records.utils.submission import finalise_datasubmission
@fix.command()
@with_appcontext
def create_missing_datasubmission_records():
# Get submissions with missing IDs
missing_submissions = DataSubmission.query \
.join(HEPSubmission, HEPSubmission.publication_recid == DataSubmission.publication_recid) \
.filter(
DataSubmission.associated_recid == None,
DataSubmission.publication_inspire_id == None,
DataSubmission.version == HEPSubmission.version,
HEPSubmission.overall_status == 'finished')
missing_submissions = missing_submissions.all()
if not missing_submissions:
print("No datasubmissions found with missing record or inspire ids.")
return
# Organise missing submissions by publication
submissions_by_publication = {}
for submission in missing_submissions:
if submission.publication_recid in submissions_by_publication:
submissions_by_publication[submission.publication_recid].append(submission)
else:
submissions_by_publication[submission.publication_recid] = [submission]
# Loop through each publication
for publication_recid, submissions in submissions_by_publication.items():
publication_record = get_record_by_id(publication_recid)
current_time = "{:%Y-%m-%d %H:%M:%S}".format(datetime.utcnow())
generated_record_ids = []
for submission in submissions:
# Finalise each data submission that does not have a record
finalise_datasubmission(current_time, {},
generated_record_ids,
publication_record, publication_recid,
submission,
submission.version)
# Register the datasubmission's DOI
if not current_app.config.get('TESTING', False):
generate_doi_for_table.delay(submission.doi)
print(f"Generated DOI {submission.doi}")
else:
print(f"Would generate DOI {submission.doi}")
# finalise_datasubmission does not commit, so commit once for each publication
db.session.commit()
# Reindex the publication and its updated datasubmissions
index_record_ids([publication_recid] + generated_record_ids)
push_data_keywords(pub_ids=[publication_recid])<|fim▁end|> | |
<|file_name|>missing_record_ids.py<|end_file_name|><|fim▁begin|>from datetime import datetime
from flask import current_app
from flask.cli import with_appcontext
from invenio_db import db
from hepdata.cli import fix
from hepdata.ext.elasticsearch.api import index_record_ids, push_data_keywords
from hepdata.modules.submission.models import HEPSubmission, DataSubmission
from hepdata.modules.records.utils.common import get_record_by_id
from hepdata.modules.records.utils.doi_minter import generate_doi_for_table
from hepdata.modules.records.utils.submission import finalise_datasubmission
@fix.command()
@with_appcontext
def create_missing_datasubmission_records():
# Get submissions with missing IDs
<|fim_middle|>
<|fim▁end|> | missing_submissions = DataSubmission.query \
.join(HEPSubmission, HEPSubmission.publication_recid == DataSubmission.publication_recid) \
.filter(
DataSubmission.associated_recid == None,
DataSubmission.publication_inspire_id == None,
DataSubmission.version == HEPSubmission.version,
HEPSubmission.overall_status == 'finished')
missing_submissions = missing_submissions.all()
if not missing_submissions:
print("No datasubmissions found with missing record or inspire ids.")
return
# Organise missing submissions by publication
submissions_by_publication = {}
for submission in missing_submissions:
if submission.publication_recid in submissions_by_publication:
submissions_by_publication[submission.publication_recid].append(submission)
else:
submissions_by_publication[submission.publication_recid] = [submission]
# Loop through each publication
for publication_recid, submissions in submissions_by_publication.items():
publication_record = get_record_by_id(publication_recid)
current_time = "{:%Y-%m-%d %H:%M:%S}".format(datetime.utcnow())
generated_record_ids = []
for submission in submissions:
# Finalise each data submission that does not have a record
finalise_datasubmission(current_time, {},
generated_record_ids,
publication_record, publication_recid,
submission,
submission.version)
# Register the datasubmission's DOI
if not current_app.config.get('TESTING', False):
generate_doi_for_table.delay(submission.doi)
print(f"Generated DOI {submission.doi}")
else:
print(f"Would generate DOI {submission.doi}")
# finalise_datasubmission does not commit, so commit once for each publication
db.session.commit()
# Reindex the publication and its updated datasubmissions
index_record_ids([publication_recid] + generated_record_ids)
push_data_keywords(pub_ids=[publication_recid]) |
<|file_name|>missing_record_ids.py<|end_file_name|><|fim▁begin|>from datetime import datetime
from flask import current_app
from flask.cli import with_appcontext
from invenio_db import db
from hepdata.cli import fix
from hepdata.ext.elasticsearch.api import index_record_ids, push_data_keywords
from hepdata.modules.submission.models import HEPSubmission, DataSubmission
from hepdata.modules.records.utils.common import get_record_by_id
from hepdata.modules.records.utils.doi_minter import generate_doi_for_table
from hepdata.modules.records.utils.submission import finalise_datasubmission
@fix.command()
@with_appcontext
def create_missing_datasubmission_records():
# Get submissions with missing IDs
missing_submissions = DataSubmission.query \
.join(HEPSubmission, HEPSubmission.publication_recid == DataSubmission.publication_recid) \
.filter(
DataSubmission.associated_recid == None,
DataSubmission.publication_inspire_id == None,
DataSubmission.version == HEPSubmission.version,
HEPSubmission.overall_status == 'finished')
missing_submissions = missing_submissions.all()
if not missing_submissions:
<|fim_middle|>
# Organise missing submissions by publication
submissions_by_publication = {}
for submission in missing_submissions:
if submission.publication_recid in submissions_by_publication:
submissions_by_publication[submission.publication_recid].append(submission)
else:
submissions_by_publication[submission.publication_recid] = [submission]
# Loop through each publication
for publication_recid, submissions in submissions_by_publication.items():
publication_record = get_record_by_id(publication_recid)
current_time = "{:%Y-%m-%d %H:%M:%S}".format(datetime.utcnow())
generated_record_ids = []
for submission in submissions:
# Finalise each data submission that does not have a record
finalise_datasubmission(current_time, {},
generated_record_ids,
publication_record, publication_recid,
submission,
submission.version)
# Register the datasubmission's DOI
if not current_app.config.get('TESTING', False):
generate_doi_for_table.delay(submission.doi)
print(f"Generated DOI {submission.doi}")
else:
print(f"Would generate DOI {submission.doi}")
# finalise_datasubmission does not commit, so commit once for each publication
db.session.commit()
# Reindex the publication and its updated datasubmissions
index_record_ids([publication_recid] + generated_record_ids)
push_data_keywords(pub_ids=[publication_recid])
<|fim▁end|> | print("No datasubmissions found with missing record or inspire ids.")
return |
<|file_name|>missing_record_ids.py<|end_file_name|><|fim▁begin|>from datetime import datetime
from flask import current_app
from flask.cli import with_appcontext
from invenio_db import db
from hepdata.cli import fix
from hepdata.ext.elasticsearch.api import index_record_ids, push_data_keywords
from hepdata.modules.submission.models import HEPSubmission, DataSubmission
from hepdata.modules.records.utils.common import get_record_by_id
from hepdata.modules.records.utils.doi_minter import generate_doi_for_table
from hepdata.modules.records.utils.submission import finalise_datasubmission
@fix.command()
@with_appcontext
def create_missing_datasubmission_records():
# Get submissions with missing IDs
missing_submissions = DataSubmission.query \
.join(HEPSubmission, HEPSubmission.publication_recid == DataSubmission.publication_recid) \
.filter(
DataSubmission.associated_recid == None,
DataSubmission.publication_inspire_id == None,
DataSubmission.version == HEPSubmission.version,
HEPSubmission.overall_status == 'finished')
missing_submissions = missing_submissions.all()
if not missing_submissions:
print("No datasubmissions found with missing record or inspire ids.")
return
# Organise missing submissions by publication
submissions_by_publication = {}
for submission in missing_submissions:
if submission.publication_recid in submissions_by_publication:
<|fim_middle|>
else:
submissions_by_publication[submission.publication_recid] = [submission]
# Loop through each publication
for publication_recid, submissions in submissions_by_publication.items():
publication_record = get_record_by_id(publication_recid)
current_time = "{:%Y-%m-%d %H:%M:%S}".format(datetime.utcnow())
generated_record_ids = []
for submission in submissions:
# Finalise each data submission that does not have a record
finalise_datasubmission(current_time, {},
generated_record_ids,
publication_record, publication_recid,
submission,
submission.version)
# Register the datasubmission's DOI
if not current_app.config.get('TESTING', False):
generate_doi_for_table.delay(submission.doi)
print(f"Generated DOI {submission.doi}")
else:
print(f"Would generate DOI {submission.doi}")
# finalise_datasubmission does not commit, so commit once for each publication
db.session.commit()
# Reindex the publication and its updated datasubmissions
index_record_ids([publication_recid] + generated_record_ids)
push_data_keywords(pub_ids=[publication_recid])
<|fim▁end|> | submissions_by_publication[submission.publication_recid].append(submission) |
<|file_name|>missing_record_ids.py<|end_file_name|><|fim▁begin|>from datetime import datetime
from flask import current_app
from flask.cli import with_appcontext
from invenio_db import db
from hepdata.cli import fix
from hepdata.ext.elasticsearch.api import index_record_ids, push_data_keywords
from hepdata.modules.submission.models import HEPSubmission, DataSubmission
from hepdata.modules.records.utils.common import get_record_by_id
from hepdata.modules.records.utils.doi_minter import generate_doi_for_table
from hepdata.modules.records.utils.submission import finalise_datasubmission
@fix.command()
@with_appcontext
def create_missing_datasubmission_records():
# Get submissions with missing IDs
missing_submissions = DataSubmission.query \
.join(HEPSubmission, HEPSubmission.publication_recid == DataSubmission.publication_recid) \
.filter(
DataSubmission.associated_recid == None,
DataSubmission.publication_inspire_id == None,
DataSubmission.version == HEPSubmission.version,
HEPSubmission.overall_status == 'finished')
missing_submissions = missing_submissions.all()
if not missing_submissions:
print("No datasubmissions found with missing record or inspire ids.")
return
# Organise missing submissions by publication
submissions_by_publication = {}
for submission in missing_submissions:
if submission.publication_recid in submissions_by_publication:
submissions_by_publication[submission.publication_recid].append(submission)
else:
<|fim_middle|>
# Loop through each publication
for publication_recid, submissions in submissions_by_publication.items():
publication_record = get_record_by_id(publication_recid)
current_time = "{:%Y-%m-%d %H:%M:%S}".format(datetime.utcnow())
generated_record_ids = []
for submission in submissions:
# Finalise each data submission that does not have a record
finalise_datasubmission(current_time, {},
generated_record_ids,
publication_record, publication_recid,
submission,
submission.version)
# Register the datasubmission's DOI
if not current_app.config.get('TESTING', False):
generate_doi_for_table.delay(submission.doi)
print(f"Generated DOI {submission.doi}")
else:
print(f"Would generate DOI {submission.doi}")
# finalise_datasubmission does not commit, so commit once for each publication
db.session.commit()
# Reindex the publication and its updated datasubmissions
index_record_ids([publication_recid] + generated_record_ids)
push_data_keywords(pub_ids=[publication_recid])
<|fim▁end|> | submissions_by_publication[submission.publication_recid] = [submission] |
<|file_name|>missing_record_ids.py<|end_file_name|><|fim▁begin|>from datetime import datetime
from flask import current_app
from flask.cli import with_appcontext
from invenio_db import db
from hepdata.cli import fix
from hepdata.ext.elasticsearch.api import index_record_ids, push_data_keywords
from hepdata.modules.submission.models import HEPSubmission, DataSubmission
from hepdata.modules.records.utils.common import get_record_by_id
from hepdata.modules.records.utils.doi_minter import generate_doi_for_table
from hepdata.modules.records.utils.submission import finalise_datasubmission
@fix.command()
@with_appcontext
def create_missing_datasubmission_records():
# Get submissions with missing IDs
missing_submissions = DataSubmission.query \
.join(HEPSubmission, HEPSubmission.publication_recid == DataSubmission.publication_recid) \
.filter(
DataSubmission.associated_recid == None,
DataSubmission.publication_inspire_id == None,
DataSubmission.version == HEPSubmission.version,
HEPSubmission.overall_status == 'finished')
missing_submissions = missing_submissions.all()
if not missing_submissions:
print("No datasubmissions found with missing record or inspire ids.")
return
# Organise missing submissions by publication
submissions_by_publication = {}
for submission in missing_submissions:
if submission.publication_recid in submissions_by_publication:
submissions_by_publication[submission.publication_recid].append(submission)
else:
submissions_by_publication[submission.publication_recid] = [submission]
# Loop through each publication
for publication_recid, submissions in submissions_by_publication.items():
publication_record = get_record_by_id(publication_recid)
current_time = "{:%Y-%m-%d %H:%M:%S}".format(datetime.utcnow())
generated_record_ids = []
for submission in submissions:
# Finalise each data submission that does not have a record
finalise_datasubmission(current_time, {},
generated_record_ids,
publication_record, publication_recid,
submission,
submission.version)
# Register the datasubmission's DOI
if not current_app.config.get('TESTING', False):
<|fim_middle|>
else:
print(f"Would generate DOI {submission.doi}")
# finalise_datasubmission does not commit, so commit once for each publication
db.session.commit()
# Reindex the publication and its updated datasubmissions
index_record_ids([publication_recid] + generated_record_ids)
push_data_keywords(pub_ids=[publication_recid])
<|fim▁end|> | generate_doi_for_table.delay(submission.doi)
print(f"Generated DOI {submission.doi}") |
<|file_name|>missing_record_ids.py<|end_file_name|><|fim▁begin|>from datetime import datetime
from flask import current_app
from flask.cli import with_appcontext
from invenio_db import db
from hepdata.cli import fix
from hepdata.ext.elasticsearch.api import index_record_ids, push_data_keywords
from hepdata.modules.submission.models import HEPSubmission, DataSubmission
from hepdata.modules.records.utils.common import get_record_by_id
from hepdata.modules.records.utils.doi_minter import generate_doi_for_table
from hepdata.modules.records.utils.submission import finalise_datasubmission
@fix.command()
@with_appcontext
def create_missing_datasubmission_records():
# Get submissions with missing IDs
missing_submissions = DataSubmission.query \
.join(HEPSubmission, HEPSubmission.publication_recid == DataSubmission.publication_recid) \
.filter(
DataSubmission.associated_recid == None,
DataSubmission.publication_inspire_id == None,
DataSubmission.version == HEPSubmission.version,
HEPSubmission.overall_status == 'finished')
missing_submissions = missing_submissions.all()
if not missing_submissions:
print("No datasubmissions found with missing record or inspire ids.")
return
# Organise missing submissions by publication
submissions_by_publication = {}
for submission in missing_submissions:
if submission.publication_recid in submissions_by_publication:
submissions_by_publication[submission.publication_recid].append(submission)
else:
submissions_by_publication[submission.publication_recid] = [submission]
# Loop through each publication
for publication_recid, submissions in submissions_by_publication.items():
publication_record = get_record_by_id(publication_recid)
current_time = "{:%Y-%m-%d %H:%M:%S}".format(datetime.utcnow())
generated_record_ids = []
for submission in submissions:
# Finalise each data submission that does not have a record
finalise_datasubmission(current_time, {},
generated_record_ids,
publication_record, publication_recid,
submission,
submission.version)
# Register the datasubmission's DOI
if not current_app.config.get('TESTING', False):
generate_doi_for_table.delay(submission.doi)
print(f"Generated DOI {submission.doi}")
else:
<|fim_middle|>
# finalise_datasubmission does not commit, so commit once for each publication
db.session.commit()
# Reindex the publication and its updated datasubmissions
index_record_ids([publication_recid] + generated_record_ids)
push_data_keywords(pub_ids=[publication_recid])
<|fim▁end|> | print(f"Would generate DOI {submission.doi}") |
<|file_name|>missing_record_ids.py<|end_file_name|><|fim▁begin|>from datetime import datetime
from flask import current_app
from flask.cli import with_appcontext
from invenio_db import db
from hepdata.cli import fix
from hepdata.ext.elasticsearch.api import index_record_ids, push_data_keywords
from hepdata.modules.submission.models import HEPSubmission, DataSubmission
from hepdata.modules.records.utils.common import get_record_by_id
from hepdata.modules.records.utils.doi_minter import generate_doi_for_table
from hepdata.modules.records.utils.submission import finalise_datasubmission
@fix.command()
@with_appcontext
def <|fim_middle|>():
# Get submissions with missing IDs
missing_submissions = DataSubmission.query \
.join(HEPSubmission, HEPSubmission.publication_recid == DataSubmission.publication_recid) \
.filter(
DataSubmission.associated_recid == None,
DataSubmission.publication_inspire_id == None,
DataSubmission.version == HEPSubmission.version,
HEPSubmission.overall_status == 'finished')
missing_submissions = missing_submissions.all()
if not missing_submissions:
print("No datasubmissions found with missing record or inspire ids.")
return
# Organise missing submissions by publication
submissions_by_publication = {}
for submission in missing_submissions:
if submission.publication_recid in submissions_by_publication:
submissions_by_publication[submission.publication_recid].append(submission)
else:
submissions_by_publication[submission.publication_recid] = [submission]
# Loop through each publication
for publication_recid, submissions in submissions_by_publication.items():
publication_record = get_record_by_id(publication_recid)
current_time = "{:%Y-%m-%d %H:%M:%S}".format(datetime.utcnow())
generated_record_ids = []
for submission in submissions:
# Finalise each data submission that does not have a record
finalise_datasubmission(current_time, {},
generated_record_ids,
publication_record, publication_recid,
submission,
submission.version)
# Register the datasubmission's DOI
if not current_app.config.get('TESTING', False):
generate_doi_for_table.delay(submission.doi)
print(f"Generated DOI {submission.doi}")
else:
print(f"Would generate DOI {submission.doi}")
# finalise_datasubmission does not commit, so commit once for each publication
db.session.commit()
# Reindex the publication and its updated datasubmissions
index_record_ids([publication_recid] + generated_record_ids)
push_data_keywords(pub_ids=[publication_recid])
<|fim▁end|> | create_missing_datasubmission_records |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|>__version_info__ = ( 1, 12, 0 )<|fim▁end|> | __version__ = "1.12.0" |
<|file_name|>test_config.py<|end_file_name|><|fim▁begin|>import codecs
import mock
import os
import tempfile
import unittest
from time import strftime
import six
from kinto import config
from kinto import __version__
class ConfigTest(unittest.TestCase):
def test_transpose_parameters_into_template(self):
self.maxDiff = None
template = "kinto.tpl"
dest = tempfile.mktemp()
config.render_template(template, dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
with codecs.open(dest, 'r', encoding='utf-8') as d:
destination_temp = d.read()
sample_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
"test_configuration/test.ini")
with codecs.open(sample_path, 'r', encoding='utf-8') as c:
sample = c.read()
self.assertEqual(destination_temp, sample)
def test_create_destination_directory(self):
dest = os.path.join(tempfile.mkdtemp(), 'config', 'kinto.ini')
config.render_template("kinto.tpl", dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
self.assertTrue(os.path.exists(dest))
@mock.patch('kinto.config.render_template')
def test_hmac_secret_is_text(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(type(kwargs['secret']), six.text_type)
@mock.patch('kinto.config.render_template')
def test_init_postgresql_values(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
postgresql_url = "postgres://postgres:postgres@localhost/postgres"
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.postgresql',
'cache_backend': 'kinto.core.cache.postgresql',
'permission_backend': 'kinto.core.permission.postgresql',
'storage_url': postgresql_url,
'cache_url': postgresql_url,<|fim▁hole|> 'permission_url': postgresql_url,
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def test_init_redis_values(self, mocked_render_template):
config.init('kinto.ini', 'redis')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
redis_url = "redis://localhost:6379"
self.maxDiff = None # See the full diff in case of error
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto_redis.storage',
'cache_backend': 'kinto_redis.cache',
'permission_backend': 'kinto_redis.permission',
'storage_url': redis_url + '/1',
'cache_url': redis_url + '/2',
'permission_url': redis_url + '/3',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def test_init_memory_values(self, mocked_render_template):
config.init('kinto.ini', 'memory')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
def test_render_template_creates_directory_if_necessary(self):
temp_path = tempfile.mkdtemp()
destination = os.path.join(temp_path, 'config/kinto.ini')
config.render_template('kinto.tpl', destination, **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(destination))
def test_render_template_works_with_file_in_cwd(self):
temp_path = tempfile.mkdtemp()
os.chdir(temp_path)
config.render_template('kinto.tpl', 'kinto.ini', **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(
os.path.join(temp_path, 'kinto.ini')
))<|fim▁end|> | |
<|file_name|>test_config.py<|end_file_name|><|fim▁begin|>import codecs
import mock
import os
import tempfile
import unittest
from time import strftime
import six
from kinto import config
from kinto import __version__
class ConfigTest(unittest.TestCase):
<|fim_middle|>
<|fim▁end|> | def test_transpose_parameters_into_template(self):
self.maxDiff = None
template = "kinto.tpl"
dest = tempfile.mktemp()
config.render_template(template, dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
with codecs.open(dest, 'r', encoding='utf-8') as d:
destination_temp = d.read()
sample_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
"test_configuration/test.ini")
with codecs.open(sample_path, 'r', encoding='utf-8') as c:
sample = c.read()
self.assertEqual(destination_temp, sample)
def test_create_destination_directory(self):
dest = os.path.join(tempfile.mkdtemp(), 'config', 'kinto.ini')
config.render_template("kinto.tpl", dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
self.assertTrue(os.path.exists(dest))
@mock.patch('kinto.config.render_template')
def test_hmac_secret_is_text(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(type(kwargs['secret']), six.text_type)
@mock.patch('kinto.config.render_template')
def test_init_postgresql_values(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
postgresql_url = "postgres://postgres:postgres@localhost/postgres"
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.postgresql',
'cache_backend': 'kinto.core.cache.postgresql',
'permission_backend': 'kinto.core.permission.postgresql',
'storage_url': postgresql_url,
'cache_url': postgresql_url,
'permission_url': postgresql_url,
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def test_init_redis_values(self, mocked_render_template):
config.init('kinto.ini', 'redis')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
redis_url = "redis://localhost:6379"
self.maxDiff = None # See the full diff in case of error
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto_redis.storage',
'cache_backend': 'kinto_redis.cache',
'permission_backend': 'kinto_redis.permission',
'storage_url': redis_url + '/1',
'cache_url': redis_url + '/2',
'permission_url': redis_url + '/3',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def test_init_memory_values(self, mocked_render_template):
config.init('kinto.ini', 'memory')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
def test_render_template_creates_directory_if_necessary(self):
temp_path = tempfile.mkdtemp()
destination = os.path.join(temp_path, 'config/kinto.ini')
config.render_template('kinto.tpl', destination, **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(destination))
def test_render_template_works_with_file_in_cwd(self):
temp_path = tempfile.mkdtemp()
os.chdir(temp_path)
config.render_template('kinto.tpl', 'kinto.ini', **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(
os.path.join(temp_path, 'kinto.ini')
)) |
<|file_name|>test_config.py<|end_file_name|><|fim▁begin|>import codecs
import mock
import os
import tempfile
import unittest
from time import strftime
import six
from kinto import config
from kinto import __version__
class ConfigTest(unittest.TestCase):
def test_transpose_parameters_into_template(self):
<|fim_middle|>
def test_create_destination_directory(self):
dest = os.path.join(tempfile.mkdtemp(), 'config', 'kinto.ini')
config.render_template("kinto.tpl", dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
self.assertTrue(os.path.exists(dest))
@mock.patch('kinto.config.render_template')
def test_hmac_secret_is_text(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(type(kwargs['secret']), six.text_type)
@mock.patch('kinto.config.render_template')
def test_init_postgresql_values(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
postgresql_url = "postgres://postgres:postgres@localhost/postgres"
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.postgresql',
'cache_backend': 'kinto.core.cache.postgresql',
'permission_backend': 'kinto.core.permission.postgresql',
'storage_url': postgresql_url,
'cache_url': postgresql_url,
'permission_url': postgresql_url,
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def test_init_redis_values(self, mocked_render_template):
config.init('kinto.ini', 'redis')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
redis_url = "redis://localhost:6379"
self.maxDiff = None # See the full diff in case of error
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto_redis.storage',
'cache_backend': 'kinto_redis.cache',
'permission_backend': 'kinto_redis.permission',
'storage_url': redis_url + '/1',
'cache_url': redis_url + '/2',
'permission_url': redis_url + '/3',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def test_init_memory_values(self, mocked_render_template):
config.init('kinto.ini', 'memory')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
def test_render_template_creates_directory_if_necessary(self):
temp_path = tempfile.mkdtemp()
destination = os.path.join(temp_path, 'config/kinto.ini')
config.render_template('kinto.tpl', destination, **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(destination))
def test_render_template_works_with_file_in_cwd(self):
temp_path = tempfile.mkdtemp()
os.chdir(temp_path)
config.render_template('kinto.tpl', 'kinto.ini', **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(
os.path.join(temp_path, 'kinto.ini')
))
<|fim▁end|> | self.maxDiff = None
template = "kinto.tpl"
dest = tempfile.mktemp()
config.render_template(template, dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
with codecs.open(dest, 'r', encoding='utf-8') as d:
destination_temp = d.read()
sample_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
"test_configuration/test.ini")
with codecs.open(sample_path, 'r', encoding='utf-8') as c:
sample = c.read()
self.assertEqual(destination_temp, sample) |
<|file_name|>test_config.py<|end_file_name|><|fim▁begin|>import codecs
import mock
import os
import tempfile
import unittest
from time import strftime
import six
from kinto import config
from kinto import __version__
class ConfigTest(unittest.TestCase):
def test_transpose_parameters_into_template(self):
self.maxDiff = None
template = "kinto.tpl"
dest = tempfile.mktemp()
config.render_template(template, dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
with codecs.open(dest, 'r', encoding='utf-8') as d:
destination_temp = d.read()
sample_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
"test_configuration/test.ini")
with codecs.open(sample_path, 'r', encoding='utf-8') as c:
sample = c.read()
self.assertEqual(destination_temp, sample)
def test_create_destination_directory(self):
<|fim_middle|>
@mock.patch('kinto.config.render_template')
def test_hmac_secret_is_text(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(type(kwargs['secret']), six.text_type)
@mock.patch('kinto.config.render_template')
def test_init_postgresql_values(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
postgresql_url = "postgres://postgres:postgres@localhost/postgres"
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.postgresql',
'cache_backend': 'kinto.core.cache.postgresql',
'permission_backend': 'kinto.core.permission.postgresql',
'storage_url': postgresql_url,
'cache_url': postgresql_url,
'permission_url': postgresql_url,
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def test_init_redis_values(self, mocked_render_template):
config.init('kinto.ini', 'redis')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
redis_url = "redis://localhost:6379"
self.maxDiff = None # See the full diff in case of error
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto_redis.storage',
'cache_backend': 'kinto_redis.cache',
'permission_backend': 'kinto_redis.permission',
'storage_url': redis_url + '/1',
'cache_url': redis_url + '/2',
'permission_url': redis_url + '/3',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def test_init_memory_values(self, mocked_render_template):
config.init('kinto.ini', 'memory')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
def test_render_template_creates_directory_if_necessary(self):
temp_path = tempfile.mkdtemp()
destination = os.path.join(temp_path, 'config/kinto.ini')
config.render_template('kinto.tpl', destination, **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(destination))
def test_render_template_works_with_file_in_cwd(self):
temp_path = tempfile.mkdtemp()
os.chdir(temp_path)
config.render_template('kinto.tpl', 'kinto.ini', **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(
os.path.join(temp_path, 'kinto.ini')
))
<|fim▁end|> | dest = os.path.join(tempfile.mkdtemp(), 'config', 'kinto.ini')
config.render_template("kinto.tpl", dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
self.assertTrue(os.path.exists(dest)) |
<|file_name|>test_config.py<|end_file_name|><|fim▁begin|>import codecs
import mock
import os
import tempfile
import unittest
from time import strftime
import six
from kinto import config
from kinto import __version__
class ConfigTest(unittest.TestCase):
def test_transpose_parameters_into_template(self):
self.maxDiff = None
template = "kinto.tpl"
dest = tempfile.mktemp()
config.render_template(template, dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
with codecs.open(dest, 'r', encoding='utf-8') as d:
destination_temp = d.read()
sample_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
"test_configuration/test.ini")
with codecs.open(sample_path, 'r', encoding='utf-8') as c:
sample = c.read()
self.assertEqual(destination_temp, sample)
def test_create_destination_directory(self):
dest = os.path.join(tempfile.mkdtemp(), 'config', 'kinto.ini')
config.render_template("kinto.tpl", dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
self.assertTrue(os.path.exists(dest))
@mock.patch('kinto.config.render_template')
def test_hmac_secret_is_text(self, mocked_render_template):
<|fim_middle|>
@mock.patch('kinto.config.render_template')
def test_init_postgresql_values(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
postgresql_url = "postgres://postgres:postgres@localhost/postgres"
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.postgresql',
'cache_backend': 'kinto.core.cache.postgresql',
'permission_backend': 'kinto.core.permission.postgresql',
'storage_url': postgresql_url,
'cache_url': postgresql_url,
'permission_url': postgresql_url,
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def test_init_redis_values(self, mocked_render_template):
config.init('kinto.ini', 'redis')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
redis_url = "redis://localhost:6379"
self.maxDiff = None # See the full diff in case of error
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto_redis.storage',
'cache_backend': 'kinto_redis.cache',
'permission_backend': 'kinto_redis.permission',
'storage_url': redis_url + '/1',
'cache_url': redis_url + '/2',
'permission_url': redis_url + '/3',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def test_init_memory_values(self, mocked_render_template):
config.init('kinto.ini', 'memory')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
def test_render_template_creates_directory_if_necessary(self):
temp_path = tempfile.mkdtemp()
destination = os.path.join(temp_path, 'config/kinto.ini')
config.render_template('kinto.tpl', destination, **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(destination))
def test_render_template_works_with_file_in_cwd(self):
temp_path = tempfile.mkdtemp()
os.chdir(temp_path)
config.render_template('kinto.tpl', 'kinto.ini', **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(
os.path.join(temp_path, 'kinto.ini')
))
<|fim▁end|> | config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(type(kwargs['secret']), six.text_type) |
<|file_name|>test_config.py<|end_file_name|><|fim▁begin|>import codecs
import mock
import os
import tempfile
import unittest
from time import strftime
import six
from kinto import config
from kinto import __version__
class ConfigTest(unittest.TestCase):
def test_transpose_parameters_into_template(self):
self.maxDiff = None
template = "kinto.tpl"
dest = tempfile.mktemp()
config.render_template(template, dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
with codecs.open(dest, 'r', encoding='utf-8') as d:
destination_temp = d.read()
sample_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
"test_configuration/test.ini")
with codecs.open(sample_path, 'r', encoding='utf-8') as c:
sample = c.read()
self.assertEqual(destination_temp, sample)
def test_create_destination_directory(self):
dest = os.path.join(tempfile.mkdtemp(), 'config', 'kinto.ini')
config.render_template("kinto.tpl", dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
self.assertTrue(os.path.exists(dest))
@mock.patch('kinto.config.render_template')
def test_hmac_secret_is_text(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(type(kwargs['secret']), six.text_type)
@mock.patch('kinto.config.render_template')
def test_init_postgresql_values(self, mocked_render_template):
<|fim_middle|>
@mock.patch('kinto.config.render_template')
def test_init_redis_values(self, mocked_render_template):
config.init('kinto.ini', 'redis')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
redis_url = "redis://localhost:6379"
self.maxDiff = None # See the full diff in case of error
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto_redis.storage',
'cache_backend': 'kinto_redis.cache',
'permission_backend': 'kinto_redis.permission',
'storage_url': redis_url + '/1',
'cache_url': redis_url + '/2',
'permission_url': redis_url + '/3',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def test_init_memory_values(self, mocked_render_template):
config.init('kinto.ini', 'memory')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
def test_render_template_creates_directory_if_necessary(self):
temp_path = tempfile.mkdtemp()
destination = os.path.join(temp_path, 'config/kinto.ini')
config.render_template('kinto.tpl', destination, **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(destination))
def test_render_template_works_with_file_in_cwd(self):
temp_path = tempfile.mkdtemp()
os.chdir(temp_path)
config.render_template('kinto.tpl', 'kinto.ini', **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(
os.path.join(temp_path, 'kinto.ini')
))
<|fim▁end|> | config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
postgresql_url = "postgres://postgres:postgres@localhost/postgres"
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.postgresql',
'cache_backend': 'kinto.core.cache.postgresql',
'permission_backend': 'kinto.core.permission.postgresql',
'storage_url': postgresql_url,
'cache_url': postgresql_url,
'permission_url': postgresql_url,
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
}) |
<|file_name|>test_config.py<|end_file_name|><|fim▁begin|>import codecs
import mock
import os
import tempfile
import unittest
from time import strftime
import six
from kinto import config
from kinto import __version__
class ConfigTest(unittest.TestCase):
def test_transpose_parameters_into_template(self):
self.maxDiff = None
template = "kinto.tpl"
dest = tempfile.mktemp()
config.render_template(template, dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
with codecs.open(dest, 'r', encoding='utf-8') as d:
destination_temp = d.read()
sample_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
"test_configuration/test.ini")
with codecs.open(sample_path, 'r', encoding='utf-8') as c:
sample = c.read()
self.assertEqual(destination_temp, sample)
def test_create_destination_directory(self):
dest = os.path.join(tempfile.mkdtemp(), 'config', 'kinto.ini')
config.render_template("kinto.tpl", dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
self.assertTrue(os.path.exists(dest))
@mock.patch('kinto.config.render_template')
def test_hmac_secret_is_text(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(type(kwargs['secret']), six.text_type)
@mock.patch('kinto.config.render_template')
def test_init_postgresql_values(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
postgresql_url = "postgres://postgres:postgres@localhost/postgres"
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.postgresql',
'cache_backend': 'kinto.core.cache.postgresql',
'permission_backend': 'kinto.core.permission.postgresql',
'storage_url': postgresql_url,
'cache_url': postgresql_url,
'permission_url': postgresql_url,
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def test_init_redis_values(self, mocked_render_template):
<|fim_middle|>
@mock.patch('kinto.config.render_template')
def test_init_memory_values(self, mocked_render_template):
config.init('kinto.ini', 'memory')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
def test_render_template_creates_directory_if_necessary(self):
temp_path = tempfile.mkdtemp()
destination = os.path.join(temp_path, 'config/kinto.ini')
config.render_template('kinto.tpl', destination, **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(destination))
def test_render_template_works_with_file_in_cwd(self):
temp_path = tempfile.mkdtemp()
os.chdir(temp_path)
config.render_template('kinto.tpl', 'kinto.ini', **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(
os.path.join(temp_path, 'kinto.ini')
))
<|fim▁end|> | config.init('kinto.ini', 'redis')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
redis_url = "redis://localhost:6379"
self.maxDiff = None # See the full diff in case of error
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto_redis.storage',
'cache_backend': 'kinto_redis.cache',
'permission_backend': 'kinto_redis.permission',
'storage_url': redis_url + '/1',
'cache_url': redis_url + '/2',
'permission_url': redis_url + '/3',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
}) |
<|file_name|>test_config.py<|end_file_name|><|fim▁begin|>import codecs
import mock
import os
import tempfile
import unittest
from time import strftime
import six
from kinto import config
from kinto import __version__
class ConfigTest(unittest.TestCase):
def test_transpose_parameters_into_template(self):
self.maxDiff = None
template = "kinto.tpl"
dest = tempfile.mktemp()
config.render_template(template, dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
with codecs.open(dest, 'r', encoding='utf-8') as d:
destination_temp = d.read()
sample_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
"test_configuration/test.ini")
with codecs.open(sample_path, 'r', encoding='utf-8') as c:
sample = c.read()
self.assertEqual(destination_temp, sample)
def test_create_destination_directory(self):
dest = os.path.join(tempfile.mkdtemp(), 'config', 'kinto.ini')
config.render_template("kinto.tpl", dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
self.assertTrue(os.path.exists(dest))
@mock.patch('kinto.config.render_template')
def test_hmac_secret_is_text(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(type(kwargs['secret']), six.text_type)
@mock.patch('kinto.config.render_template')
def test_init_postgresql_values(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
postgresql_url = "postgres://postgres:postgres@localhost/postgres"
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.postgresql',
'cache_backend': 'kinto.core.cache.postgresql',
'permission_backend': 'kinto.core.permission.postgresql',
'storage_url': postgresql_url,
'cache_url': postgresql_url,
'permission_url': postgresql_url,
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def test_init_redis_values(self, mocked_render_template):
config.init('kinto.ini', 'redis')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
redis_url = "redis://localhost:6379"
self.maxDiff = None # See the full diff in case of error
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto_redis.storage',
'cache_backend': 'kinto_redis.cache',
'permission_backend': 'kinto_redis.permission',
'storage_url': redis_url + '/1',
'cache_url': redis_url + '/2',
'permission_url': redis_url + '/3',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def test_init_memory_values(self, mocked_render_template):
<|fim_middle|>
def test_render_template_creates_directory_if_necessary(self):
temp_path = tempfile.mkdtemp()
destination = os.path.join(temp_path, 'config/kinto.ini')
config.render_template('kinto.tpl', destination, **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(destination))
def test_render_template_works_with_file_in_cwd(self):
temp_path = tempfile.mkdtemp()
os.chdir(temp_path)
config.render_template('kinto.tpl', 'kinto.ini', **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(
os.path.join(temp_path, 'kinto.ini')
))
<|fim▁end|> | config.init('kinto.ini', 'memory')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
}) |
<|file_name|>test_config.py<|end_file_name|><|fim▁begin|>import codecs
import mock
import os
import tempfile
import unittest
from time import strftime
import six
from kinto import config
from kinto import __version__
class ConfigTest(unittest.TestCase):
def test_transpose_parameters_into_template(self):
self.maxDiff = None
template = "kinto.tpl"
dest = tempfile.mktemp()
config.render_template(template, dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
with codecs.open(dest, 'r', encoding='utf-8') as d:
destination_temp = d.read()
sample_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
"test_configuration/test.ini")
with codecs.open(sample_path, 'r', encoding='utf-8') as c:
sample = c.read()
self.assertEqual(destination_temp, sample)
def test_create_destination_directory(self):
dest = os.path.join(tempfile.mkdtemp(), 'config', 'kinto.ini')
config.render_template("kinto.tpl", dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
self.assertTrue(os.path.exists(dest))
@mock.patch('kinto.config.render_template')
def test_hmac_secret_is_text(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(type(kwargs['secret']), six.text_type)
@mock.patch('kinto.config.render_template')
def test_init_postgresql_values(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
postgresql_url = "postgres://postgres:postgres@localhost/postgres"
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.postgresql',
'cache_backend': 'kinto.core.cache.postgresql',
'permission_backend': 'kinto.core.permission.postgresql',
'storage_url': postgresql_url,
'cache_url': postgresql_url,
'permission_url': postgresql_url,
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def test_init_redis_values(self, mocked_render_template):
config.init('kinto.ini', 'redis')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
redis_url = "redis://localhost:6379"
self.maxDiff = None # See the full diff in case of error
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto_redis.storage',
'cache_backend': 'kinto_redis.cache',
'permission_backend': 'kinto_redis.permission',
'storage_url': redis_url + '/1',
'cache_url': redis_url + '/2',
'permission_url': redis_url + '/3',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def test_init_memory_values(self, mocked_render_template):
config.init('kinto.ini', 'memory')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
def test_render_template_creates_directory_if_necessary(self):
<|fim_middle|>
def test_render_template_works_with_file_in_cwd(self):
temp_path = tempfile.mkdtemp()
os.chdir(temp_path)
config.render_template('kinto.tpl', 'kinto.ini', **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(
os.path.join(temp_path, 'kinto.ini')
))
<|fim▁end|> | temp_path = tempfile.mkdtemp()
destination = os.path.join(temp_path, 'config/kinto.ini')
config.render_template('kinto.tpl', destination, **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(destination)) |
<|file_name|>test_config.py<|end_file_name|><|fim▁begin|>import codecs
import mock
import os
import tempfile
import unittest
from time import strftime
import six
from kinto import config
from kinto import __version__
class ConfigTest(unittest.TestCase):
def test_transpose_parameters_into_template(self):
self.maxDiff = None
template = "kinto.tpl"
dest = tempfile.mktemp()
config.render_template(template, dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
with codecs.open(dest, 'r', encoding='utf-8') as d:
destination_temp = d.read()
sample_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
"test_configuration/test.ini")
with codecs.open(sample_path, 'r', encoding='utf-8') as c:
sample = c.read()
self.assertEqual(destination_temp, sample)
def test_create_destination_directory(self):
dest = os.path.join(tempfile.mkdtemp(), 'config', 'kinto.ini')
config.render_template("kinto.tpl", dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
self.assertTrue(os.path.exists(dest))
@mock.patch('kinto.config.render_template')
def test_hmac_secret_is_text(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(type(kwargs['secret']), six.text_type)
@mock.patch('kinto.config.render_template')
def test_init_postgresql_values(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
postgresql_url = "postgres://postgres:postgres@localhost/postgres"
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.postgresql',
'cache_backend': 'kinto.core.cache.postgresql',
'permission_backend': 'kinto.core.permission.postgresql',
'storage_url': postgresql_url,
'cache_url': postgresql_url,
'permission_url': postgresql_url,
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def test_init_redis_values(self, mocked_render_template):
config.init('kinto.ini', 'redis')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
redis_url = "redis://localhost:6379"
self.maxDiff = None # See the full diff in case of error
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto_redis.storage',
'cache_backend': 'kinto_redis.cache',
'permission_backend': 'kinto_redis.permission',
'storage_url': redis_url + '/1',
'cache_url': redis_url + '/2',
'permission_url': redis_url + '/3',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def test_init_memory_values(self, mocked_render_template):
config.init('kinto.ini', 'memory')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
def test_render_template_creates_directory_if_necessary(self):
temp_path = tempfile.mkdtemp()
destination = os.path.join(temp_path, 'config/kinto.ini')
config.render_template('kinto.tpl', destination, **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(destination))
def test_render_template_works_with_file_in_cwd(self):
<|fim_middle|>
<|fim▁end|> | temp_path = tempfile.mkdtemp()
os.chdir(temp_path)
config.render_template('kinto.tpl', 'kinto.ini', **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(
os.path.join(temp_path, 'kinto.ini')
)) |
<|file_name|>test_config.py<|end_file_name|><|fim▁begin|>import codecs
import mock
import os
import tempfile
import unittest
from time import strftime
import six
from kinto import config
from kinto import __version__
class ConfigTest(unittest.TestCase):
def <|fim_middle|>(self):
self.maxDiff = None
template = "kinto.tpl"
dest = tempfile.mktemp()
config.render_template(template, dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
with codecs.open(dest, 'r', encoding='utf-8') as d:
destination_temp = d.read()
sample_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
"test_configuration/test.ini")
with codecs.open(sample_path, 'r', encoding='utf-8') as c:
sample = c.read()
self.assertEqual(destination_temp, sample)
def test_create_destination_directory(self):
dest = os.path.join(tempfile.mkdtemp(), 'config', 'kinto.ini')
config.render_template("kinto.tpl", dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
self.assertTrue(os.path.exists(dest))
@mock.patch('kinto.config.render_template')
def test_hmac_secret_is_text(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(type(kwargs['secret']), six.text_type)
@mock.patch('kinto.config.render_template')
def test_init_postgresql_values(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
postgresql_url = "postgres://postgres:postgres@localhost/postgres"
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.postgresql',
'cache_backend': 'kinto.core.cache.postgresql',
'permission_backend': 'kinto.core.permission.postgresql',
'storage_url': postgresql_url,
'cache_url': postgresql_url,
'permission_url': postgresql_url,
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def test_init_redis_values(self, mocked_render_template):
config.init('kinto.ini', 'redis')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
redis_url = "redis://localhost:6379"
self.maxDiff = None # See the full diff in case of error
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto_redis.storage',
'cache_backend': 'kinto_redis.cache',
'permission_backend': 'kinto_redis.permission',
'storage_url': redis_url + '/1',
'cache_url': redis_url + '/2',
'permission_url': redis_url + '/3',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def test_init_memory_values(self, mocked_render_template):
config.init('kinto.ini', 'memory')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
def test_render_template_creates_directory_if_necessary(self):
temp_path = tempfile.mkdtemp()
destination = os.path.join(temp_path, 'config/kinto.ini')
config.render_template('kinto.tpl', destination, **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(destination))
def test_render_template_works_with_file_in_cwd(self):
temp_path = tempfile.mkdtemp()
os.chdir(temp_path)
config.render_template('kinto.tpl', 'kinto.ini', **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(
os.path.join(temp_path, 'kinto.ini')
))
<|fim▁end|> | test_transpose_parameters_into_template |
<|file_name|>test_config.py<|end_file_name|><|fim▁begin|>import codecs
import mock
import os
import tempfile
import unittest
from time import strftime
import six
from kinto import config
from kinto import __version__
class ConfigTest(unittest.TestCase):
def test_transpose_parameters_into_template(self):
self.maxDiff = None
template = "kinto.tpl"
dest = tempfile.mktemp()
config.render_template(template, dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
with codecs.open(dest, 'r', encoding='utf-8') as d:
destination_temp = d.read()
sample_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
"test_configuration/test.ini")
with codecs.open(sample_path, 'r', encoding='utf-8') as c:
sample = c.read()
self.assertEqual(destination_temp, sample)
def <|fim_middle|>(self):
dest = os.path.join(tempfile.mkdtemp(), 'config', 'kinto.ini')
config.render_template("kinto.tpl", dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
self.assertTrue(os.path.exists(dest))
@mock.patch('kinto.config.render_template')
def test_hmac_secret_is_text(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(type(kwargs['secret']), six.text_type)
@mock.patch('kinto.config.render_template')
def test_init_postgresql_values(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
postgresql_url = "postgres://postgres:postgres@localhost/postgres"
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.postgresql',
'cache_backend': 'kinto.core.cache.postgresql',
'permission_backend': 'kinto.core.permission.postgresql',
'storage_url': postgresql_url,
'cache_url': postgresql_url,
'permission_url': postgresql_url,
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def test_init_redis_values(self, mocked_render_template):
config.init('kinto.ini', 'redis')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
redis_url = "redis://localhost:6379"
self.maxDiff = None # See the full diff in case of error
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto_redis.storage',
'cache_backend': 'kinto_redis.cache',
'permission_backend': 'kinto_redis.permission',
'storage_url': redis_url + '/1',
'cache_url': redis_url + '/2',
'permission_url': redis_url + '/3',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def test_init_memory_values(self, mocked_render_template):
config.init('kinto.ini', 'memory')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
def test_render_template_creates_directory_if_necessary(self):
temp_path = tempfile.mkdtemp()
destination = os.path.join(temp_path, 'config/kinto.ini')
config.render_template('kinto.tpl', destination, **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(destination))
def test_render_template_works_with_file_in_cwd(self):
temp_path = tempfile.mkdtemp()
os.chdir(temp_path)
config.render_template('kinto.tpl', 'kinto.ini', **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(
os.path.join(temp_path, 'kinto.ini')
))
<|fim▁end|> | test_create_destination_directory |
<|file_name|>test_config.py<|end_file_name|><|fim▁begin|>import codecs
import mock
import os
import tempfile
import unittest
from time import strftime
import six
from kinto import config
from kinto import __version__
class ConfigTest(unittest.TestCase):
def test_transpose_parameters_into_template(self):
self.maxDiff = None
template = "kinto.tpl"
dest = tempfile.mktemp()
config.render_template(template, dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
with codecs.open(dest, 'r', encoding='utf-8') as d:
destination_temp = d.read()
sample_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
"test_configuration/test.ini")
with codecs.open(sample_path, 'r', encoding='utf-8') as c:
sample = c.read()
self.assertEqual(destination_temp, sample)
def test_create_destination_directory(self):
dest = os.path.join(tempfile.mkdtemp(), 'config', 'kinto.ini')
config.render_template("kinto.tpl", dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
self.assertTrue(os.path.exists(dest))
@mock.patch('kinto.config.render_template')
def <|fim_middle|>(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(type(kwargs['secret']), six.text_type)
@mock.patch('kinto.config.render_template')
def test_init_postgresql_values(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
postgresql_url = "postgres://postgres:postgres@localhost/postgres"
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.postgresql',
'cache_backend': 'kinto.core.cache.postgresql',
'permission_backend': 'kinto.core.permission.postgresql',
'storage_url': postgresql_url,
'cache_url': postgresql_url,
'permission_url': postgresql_url,
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def test_init_redis_values(self, mocked_render_template):
config.init('kinto.ini', 'redis')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
redis_url = "redis://localhost:6379"
self.maxDiff = None # See the full diff in case of error
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto_redis.storage',
'cache_backend': 'kinto_redis.cache',
'permission_backend': 'kinto_redis.permission',
'storage_url': redis_url + '/1',
'cache_url': redis_url + '/2',
'permission_url': redis_url + '/3',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def test_init_memory_values(self, mocked_render_template):
config.init('kinto.ini', 'memory')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
def test_render_template_creates_directory_if_necessary(self):
temp_path = tempfile.mkdtemp()
destination = os.path.join(temp_path, 'config/kinto.ini')
config.render_template('kinto.tpl', destination, **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(destination))
def test_render_template_works_with_file_in_cwd(self):
temp_path = tempfile.mkdtemp()
os.chdir(temp_path)
config.render_template('kinto.tpl', 'kinto.ini', **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(
os.path.join(temp_path, 'kinto.ini')
))
<|fim▁end|> | test_hmac_secret_is_text |
<|file_name|>test_config.py<|end_file_name|><|fim▁begin|>import codecs
import mock
import os
import tempfile
import unittest
from time import strftime
import six
from kinto import config
from kinto import __version__
class ConfigTest(unittest.TestCase):
def test_transpose_parameters_into_template(self):
self.maxDiff = None
template = "kinto.tpl"
dest = tempfile.mktemp()
config.render_template(template, dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
with codecs.open(dest, 'r', encoding='utf-8') as d:
destination_temp = d.read()
sample_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
"test_configuration/test.ini")
with codecs.open(sample_path, 'r', encoding='utf-8') as c:
sample = c.read()
self.assertEqual(destination_temp, sample)
def test_create_destination_directory(self):
dest = os.path.join(tempfile.mkdtemp(), 'config', 'kinto.ini')
config.render_template("kinto.tpl", dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
self.assertTrue(os.path.exists(dest))
@mock.patch('kinto.config.render_template')
def test_hmac_secret_is_text(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(type(kwargs['secret']), six.text_type)
@mock.patch('kinto.config.render_template')
def <|fim_middle|>(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
postgresql_url = "postgres://postgres:postgres@localhost/postgres"
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.postgresql',
'cache_backend': 'kinto.core.cache.postgresql',
'permission_backend': 'kinto.core.permission.postgresql',
'storage_url': postgresql_url,
'cache_url': postgresql_url,
'permission_url': postgresql_url,
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def test_init_redis_values(self, mocked_render_template):
config.init('kinto.ini', 'redis')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
redis_url = "redis://localhost:6379"
self.maxDiff = None # See the full diff in case of error
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto_redis.storage',
'cache_backend': 'kinto_redis.cache',
'permission_backend': 'kinto_redis.permission',
'storage_url': redis_url + '/1',
'cache_url': redis_url + '/2',
'permission_url': redis_url + '/3',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def test_init_memory_values(self, mocked_render_template):
config.init('kinto.ini', 'memory')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
def test_render_template_creates_directory_if_necessary(self):
temp_path = tempfile.mkdtemp()
destination = os.path.join(temp_path, 'config/kinto.ini')
config.render_template('kinto.tpl', destination, **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(destination))
def test_render_template_works_with_file_in_cwd(self):
temp_path = tempfile.mkdtemp()
os.chdir(temp_path)
config.render_template('kinto.tpl', 'kinto.ini', **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(
os.path.join(temp_path, 'kinto.ini')
))
<|fim▁end|> | test_init_postgresql_values |
<|file_name|>test_config.py<|end_file_name|><|fim▁begin|>import codecs
import mock
import os
import tempfile
import unittest
from time import strftime
import six
from kinto import config
from kinto import __version__
class ConfigTest(unittest.TestCase):
def test_transpose_parameters_into_template(self):
self.maxDiff = None
template = "kinto.tpl"
dest = tempfile.mktemp()
config.render_template(template, dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
with codecs.open(dest, 'r', encoding='utf-8') as d:
destination_temp = d.read()
sample_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
"test_configuration/test.ini")
with codecs.open(sample_path, 'r', encoding='utf-8') as c:
sample = c.read()
self.assertEqual(destination_temp, sample)
def test_create_destination_directory(self):
dest = os.path.join(tempfile.mkdtemp(), 'config', 'kinto.ini')
config.render_template("kinto.tpl", dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
self.assertTrue(os.path.exists(dest))
@mock.patch('kinto.config.render_template')
def test_hmac_secret_is_text(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(type(kwargs['secret']), six.text_type)
@mock.patch('kinto.config.render_template')
def test_init_postgresql_values(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
postgresql_url = "postgres://postgres:postgres@localhost/postgres"
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.postgresql',
'cache_backend': 'kinto.core.cache.postgresql',
'permission_backend': 'kinto.core.permission.postgresql',
'storage_url': postgresql_url,
'cache_url': postgresql_url,
'permission_url': postgresql_url,
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def <|fim_middle|>(self, mocked_render_template):
config.init('kinto.ini', 'redis')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
redis_url = "redis://localhost:6379"
self.maxDiff = None # See the full diff in case of error
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto_redis.storage',
'cache_backend': 'kinto_redis.cache',
'permission_backend': 'kinto_redis.permission',
'storage_url': redis_url + '/1',
'cache_url': redis_url + '/2',
'permission_url': redis_url + '/3',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def test_init_memory_values(self, mocked_render_template):
config.init('kinto.ini', 'memory')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
def test_render_template_creates_directory_if_necessary(self):
temp_path = tempfile.mkdtemp()
destination = os.path.join(temp_path, 'config/kinto.ini')
config.render_template('kinto.tpl', destination, **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(destination))
def test_render_template_works_with_file_in_cwd(self):
temp_path = tempfile.mkdtemp()
os.chdir(temp_path)
config.render_template('kinto.tpl', 'kinto.ini', **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(
os.path.join(temp_path, 'kinto.ini')
))
<|fim▁end|> | test_init_redis_values |
<|file_name|>test_config.py<|end_file_name|><|fim▁begin|>import codecs
import mock
import os
import tempfile
import unittest
from time import strftime
import six
from kinto import config
from kinto import __version__
class ConfigTest(unittest.TestCase):
def test_transpose_parameters_into_template(self):
self.maxDiff = None
template = "kinto.tpl"
dest = tempfile.mktemp()
config.render_template(template, dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
with codecs.open(dest, 'r', encoding='utf-8') as d:
destination_temp = d.read()
sample_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
"test_configuration/test.ini")
with codecs.open(sample_path, 'r', encoding='utf-8') as c:
sample = c.read()
self.assertEqual(destination_temp, sample)
def test_create_destination_directory(self):
dest = os.path.join(tempfile.mkdtemp(), 'config', 'kinto.ini')
config.render_template("kinto.tpl", dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
self.assertTrue(os.path.exists(dest))
@mock.patch('kinto.config.render_template')
def test_hmac_secret_is_text(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(type(kwargs['secret']), six.text_type)
@mock.patch('kinto.config.render_template')
def test_init_postgresql_values(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
postgresql_url = "postgres://postgres:postgres@localhost/postgres"
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.postgresql',
'cache_backend': 'kinto.core.cache.postgresql',
'permission_backend': 'kinto.core.permission.postgresql',
'storage_url': postgresql_url,
'cache_url': postgresql_url,
'permission_url': postgresql_url,
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def test_init_redis_values(self, mocked_render_template):
config.init('kinto.ini', 'redis')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
redis_url = "redis://localhost:6379"
self.maxDiff = None # See the full diff in case of error
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto_redis.storage',
'cache_backend': 'kinto_redis.cache',
'permission_backend': 'kinto_redis.permission',
'storage_url': redis_url + '/1',
'cache_url': redis_url + '/2',
'permission_url': redis_url + '/3',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def <|fim_middle|>(self, mocked_render_template):
config.init('kinto.ini', 'memory')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
def test_render_template_creates_directory_if_necessary(self):
temp_path = tempfile.mkdtemp()
destination = os.path.join(temp_path, 'config/kinto.ini')
config.render_template('kinto.tpl', destination, **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(destination))
def test_render_template_works_with_file_in_cwd(self):
temp_path = tempfile.mkdtemp()
os.chdir(temp_path)
config.render_template('kinto.tpl', 'kinto.ini', **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(
os.path.join(temp_path, 'kinto.ini')
))
<|fim▁end|> | test_init_memory_values |
<|file_name|>test_config.py<|end_file_name|><|fim▁begin|>import codecs
import mock
import os
import tempfile
import unittest
from time import strftime
import six
from kinto import config
from kinto import __version__
class ConfigTest(unittest.TestCase):
def test_transpose_parameters_into_template(self):
self.maxDiff = None
template = "kinto.tpl"
dest = tempfile.mktemp()
config.render_template(template, dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
with codecs.open(dest, 'r', encoding='utf-8') as d:
destination_temp = d.read()
sample_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
"test_configuration/test.ini")
with codecs.open(sample_path, 'r', encoding='utf-8') as c:
sample = c.read()
self.assertEqual(destination_temp, sample)
def test_create_destination_directory(self):
dest = os.path.join(tempfile.mkdtemp(), 'config', 'kinto.ini')
config.render_template("kinto.tpl", dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
self.assertTrue(os.path.exists(dest))
@mock.patch('kinto.config.render_template')
def test_hmac_secret_is_text(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(type(kwargs['secret']), six.text_type)
@mock.patch('kinto.config.render_template')
def test_init_postgresql_values(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
postgresql_url = "postgres://postgres:postgres@localhost/postgres"
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.postgresql',
'cache_backend': 'kinto.core.cache.postgresql',
'permission_backend': 'kinto.core.permission.postgresql',
'storage_url': postgresql_url,
'cache_url': postgresql_url,
'permission_url': postgresql_url,
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def test_init_redis_values(self, mocked_render_template):
config.init('kinto.ini', 'redis')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
redis_url = "redis://localhost:6379"
self.maxDiff = None # See the full diff in case of error
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto_redis.storage',
'cache_backend': 'kinto_redis.cache',
'permission_backend': 'kinto_redis.permission',
'storage_url': redis_url + '/1',
'cache_url': redis_url + '/2',
'permission_url': redis_url + '/3',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def test_init_memory_values(self, mocked_render_template):
config.init('kinto.ini', 'memory')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
def <|fim_middle|>(self):
temp_path = tempfile.mkdtemp()
destination = os.path.join(temp_path, 'config/kinto.ini')
config.render_template('kinto.tpl', destination, **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(destination))
def test_render_template_works_with_file_in_cwd(self):
temp_path = tempfile.mkdtemp()
os.chdir(temp_path)
config.render_template('kinto.tpl', 'kinto.ini', **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(
os.path.join(temp_path, 'kinto.ini')
))
<|fim▁end|> | test_render_template_creates_directory_if_necessary |
<|file_name|>test_config.py<|end_file_name|><|fim▁begin|>import codecs
import mock
import os
import tempfile
import unittest
from time import strftime
import six
from kinto import config
from kinto import __version__
class ConfigTest(unittest.TestCase):
def test_transpose_parameters_into_template(self):
self.maxDiff = None
template = "kinto.tpl"
dest = tempfile.mktemp()
config.render_template(template, dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
with codecs.open(dest, 'r', encoding='utf-8') as d:
destination_temp = d.read()
sample_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
"test_configuration/test.ini")
with codecs.open(sample_path, 'r', encoding='utf-8') as c:
sample = c.read()
self.assertEqual(destination_temp, sample)
def test_create_destination_directory(self):
dest = os.path.join(tempfile.mkdtemp(), 'config', 'kinto.ini')
config.render_template("kinto.tpl", dest,
secret='secret',
storage_backend='storage_backend',
cache_backend='cache_backend',
permission_backend='permission_backend',
storage_url='storage_url',
cache_url='cache_url',
permission_url='permission_url',
kinto_version='kinto_version',
config_file_timestamp='config_file_timestamp')
self.assertTrue(os.path.exists(dest))
@mock.patch('kinto.config.render_template')
def test_hmac_secret_is_text(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(type(kwargs['secret']), six.text_type)
@mock.patch('kinto.config.render_template')
def test_init_postgresql_values(self, mocked_render_template):
config.init('kinto.ini', 'postgresql')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
postgresql_url = "postgres://postgres:postgres@localhost/postgres"
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.postgresql',
'cache_backend': 'kinto.core.cache.postgresql',
'permission_backend': 'kinto.core.permission.postgresql',
'storage_url': postgresql_url,
'cache_url': postgresql_url,
'permission_url': postgresql_url,
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def test_init_redis_values(self, mocked_render_template):
config.init('kinto.ini', 'redis')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
redis_url = "redis://localhost:6379"
self.maxDiff = None # See the full diff in case of error
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto_redis.storage',
'cache_backend': 'kinto_redis.cache',
'permission_backend': 'kinto_redis.permission',
'storage_url': redis_url + '/1',
'cache_url': redis_url + '/2',
'permission_url': redis_url + '/3',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def test_init_memory_values(self, mocked_render_template):
config.init('kinto.ini', 'memory')
args, kwargs = list(mocked_render_template.call_args)
self.assertEquals(args, ('kinto.tpl', 'kinto.ini'))
self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
def test_render_template_creates_directory_if_necessary(self):
temp_path = tempfile.mkdtemp()
destination = os.path.join(temp_path, 'config/kinto.ini')
config.render_template('kinto.tpl', destination, **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(destination))
def <|fim_middle|>(self):
temp_path = tempfile.mkdtemp()
os.chdir(temp_path)
config.render_template('kinto.tpl', 'kinto.ini', **{
'secret': "abcd-ceci-est-un-secret",
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
'permission_url': '',
'kinto_version': '',
'config_file_timestamp': ''
})
self.assertTrue(os.path.exists(
os.path.join(temp_path, 'kinto.ini')
))
<|fim▁end|> | test_render_template_works_with_file_in_cwd |
<|file_name|>coolmoviezone.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# ..#######.########.#######.##....#..######..######.########....###...########.#######.########..######.
# .##.....#.##.....#.##......###...#.##....#.##....#.##.....#...##.##..##.....#.##......##.....#.##....##
# .##.....#.##.....#.##......####..#.##......##......##.....#..##...##.##.....#.##......##.....#.##......
# .##.....#.########.######..##.##.#..######.##......########.##.....#.########.######..########..######.
# .##.....#.##.......##......##..###.......#.##......##...##..########.##.......##......##...##........##
# .##.....#.##.......##......##...##.##....#.##....#.##....##.##.....#.##.......##......##....##.##....##
# ..#######.##.......#######.##....#..######..######.##.....#.##.....#.##.......#######.##.....#..######.
'''
OpenScrapers Project
This program 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.
This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
'''
<|fim▁hole|>
class source:
def __init__(self):
self.priority = 1
self.language = ['en']
self.domains = ['coolmoviezone.online']
self.base_link = 'https://coolmoviezone.online'
self.scraper = cfscrape.create_scraper()
def movie(self, imdb, title, localtitle, aliases, year):
try:
title = cleantitle.geturl(title)
url = self.base_link + '/%s-%s' % (title, year)
return url
except:
return
def sources(self, url, hostDict, hostprDict):
try:
sources = []
r = self.scraper.get(url).content
match = re.compile('<td align="center"><strong><a href="(.+?)"').findall(r)
for url in match:
host = url.split('//')[1].replace('www.', '')
host = host.split('/')[0].split('.')[0].title()
quality = source_utils.check_sd_url(url)
sources.append({'source': host, 'quality': quality, 'language': 'en', 'url': url, 'direct': False,
'debridonly': False})
except Exception:
return
return sources
def resolve(self, url):
return url<|fim▁end|> | import re
from openscrapers.modules import cleantitle, source_utils, cfscrape
|
<|file_name|>coolmoviezone.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# ..#######.########.#######.##....#..######..######.########....###...########.#######.########..######.
# .##.....#.##.....#.##......###...#.##....#.##....#.##.....#...##.##..##.....#.##......##.....#.##....##
# .##.....#.##.....#.##......####..#.##......##......##.....#..##...##.##.....#.##......##.....#.##......
# .##.....#.########.######..##.##.#..######.##......########.##.....#.########.######..########..######.
# .##.....#.##.......##......##..###.......#.##......##...##..########.##.......##......##...##........##
# .##.....#.##.......##......##...##.##....#.##....#.##....##.##.....#.##.......##......##....##.##....##
# ..#######.##.......#######.##....#..######..######.##.....#.##.....#.##.......#######.##.....#..######.
'''
OpenScrapers Project
This program 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.
This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
'''
import re
from openscrapers.modules import cleantitle, source_utils, cfscrape
class source:
<|fim_middle|>
<|fim▁end|> | def __init__(self):
self.priority = 1
self.language = ['en']
self.domains = ['coolmoviezone.online']
self.base_link = 'https://coolmoviezone.online'
self.scraper = cfscrape.create_scraper()
def movie(self, imdb, title, localtitle, aliases, year):
try:
title = cleantitle.geturl(title)
url = self.base_link + '/%s-%s' % (title, year)
return url
except:
return
def sources(self, url, hostDict, hostprDict):
try:
sources = []
r = self.scraper.get(url).content
match = re.compile('<td align="center"><strong><a href="(.+?)"').findall(r)
for url in match:
host = url.split('//')[1].replace('www.', '')
host = host.split('/')[0].split('.')[0].title()
quality = source_utils.check_sd_url(url)
sources.append({'source': host, 'quality': quality, 'language': 'en', 'url': url, 'direct': False,
'debridonly': False})
except Exception:
return
return sources
def resolve(self, url):
return url |
<|file_name|>coolmoviezone.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# ..#######.########.#######.##....#..######..######.########....###...########.#######.########..######.
# .##.....#.##.....#.##......###...#.##....#.##....#.##.....#...##.##..##.....#.##......##.....#.##....##
# .##.....#.##.....#.##......####..#.##......##......##.....#..##...##.##.....#.##......##.....#.##......
# .##.....#.########.######..##.##.#..######.##......########.##.....#.########.######..########..######.
# .##.....#.##.......##......##..###.......#.##......##...##..########.##.......##......##...##........##
# .##.....#.##.......##......##...##.##....#.##....#.##....##.##.....#.##.......##......##....##.##....##
# ..#######.##.......#######.##....#..######..######.##.....#.##.....#.##.......#######.##.....#..######.
'''
OpenScrapers Project
This program 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.
This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
'''
import re
from openscrapers.modules import cleantitle, source_utils, cfscrape
class source:
def __init__(self):
<|fim_middle|>
def movie(self, imdb, title, localtitle, aliases, year):
try:
title = cleantitle.geturl(title)
url = self.base_link + '/%s-%s' % (title, year)
return url
except:
return
def sources(self, url, hostDict, hostprDict):
try:
sources = []
r = self.scraper.get(url).content
match = re.compile('<td align="center"><strong><a href="(.+?)"').findall(r)
for url in match:
host = url.split('//')[1].replace('www.', '')
host = host.split('/')[0].split('.')[0].title()
quality = source_utils.check_sd_url(url)
sources.append({'source': host, 'quality': quality, 'language': 'en', 'url': url, 'direct': False,
'debridonly': False})
except Exception:
return
return sources
def resolve(self, url):
return url
<|fim▁end|> | self.priority = 1
self.language = ['en']
self.domains = ['coolmoviezone.online']
self.base_link = 'https://coolmoviezone.online'
self.scraper = cfscrape.create_scraper() |
<|file_name|>coolmoviezone.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# ..#######.########.#######.##....#..######..######.########....###...########.#######.########..######.
# .##.....#.##.....#.##......###...#.##....#.##....#.##.....#...##.##..##.....#.##......##.....#.##....##
# .##.....#.##.....#.##......####..#.##......##......##.....#..##...##.##.....#.##......##.....#.##......
# .##.....#.########.######..##.##.#..######.##......########.##.....#.########.######..########..######.
# .##.....#.##.......##......##..###.......#.##......##...##..########.##.......##......##...##........##
# .##.....#.##.......##......##...##.##....#.##....#.##....##.##.....#.##.......##......##....##.##....##
# ..#######.##.......#######.##....#..######..######.##.....#.##.....#.##.......#######.##.....#..######.
'''
OpenScrapers Project
This program 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.
This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
'''
import re
from openscrapers.modules import cleantitle, source_utils, cfscrape
class source:
def __init__(self):
self.priority = 1
self.language = ['en']
self.domains = ['coolmoviezone.online']
self.base_link = 'https://coolmoviezone.online'
self.scraper = cfscrape.create_scraper()
def movie(self, imdb, title, localtitle, aliases, year):
<|fim_middle|>
def sources(self, url, hostDict, hostprDict):
try:
sources = []
r = self.scraper.get(url).content
match = re.compile('<td align="center"><strong><a href="(.+?)"').findall(r)
for url in match:
host = url.split('//')[1].replace('www.', '')
host = host.split('/')[0].split('.')[0].title()
quality = source_utils.check_sd_url(url)
sources.append({'source': host, 'quality': quality, 'language': 'en', 'url': url, 'direct': False,
'debridonly': False})
except Exception:
return
return sources
def resolve(self, url):
return url
<|fim▁end|> | try:
title = cleantitle.geturl(title)
url = self.base_link + '/%s-%s' % (title, year)
return url
except:
return |
<|file_name|>coolmoviezone.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# ..#######.########.#######.##....#..######..######.########....###...########.#######.########..######.
# .##.....#.##.....#.##......###...#.##....#.##....#.##.....#...##.##..##.....#.##......##.....#.##....##
# .##.....#.##.....#.##......####..#.##......##......##.....#..##...##.##.....#.##......##.....#.##......
# .##.....#.########.######..##.##.#..######.##......########.##.....#.########.######..########..######.
# .##.....#.##.......##......##..###.......#.##......##...##..########.##.......##......##...##........##
# .##.....#.##.......##......##...##.##....#.##....#.##....##.##.....#.##.......##......##....##.##....##
# ..#######.##.......#######.##....#..######..######.##.....#.##.....#.##.......#######.##.....#..######.
'''
OpenScrapers Project
This program 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.
This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
'''
import re
from openscrapers.modules import cleantitle, source_utils, cfscrape
class source:
def __init__(self):
self.priority = 1
self.language = ['en']
self.domains = ['coolmoviezone.online']
self.base_link = 'https://coolmoviezone.online'
self.scraper = cfscrape.create_scraper()
def movie(self, imdb, title, localtitle, aliases, year):
try:
title = cleantitle.geturl(title)
url = self.base_link + '/%s-%s' % (title, year)
return url
except:
return
def sources(self, url, hostDict, hostprDict):
<|fim_middle|>
def resolve(self, url):
return url
<|fim▁end|> | try:
sources = []
r = self.scraper.get(url).content
match = re.compile('<td align="center"><strong><a href="(.+?)"').findall(r)
for url in match:
host = url.split('//')[1].replace('www.', '')
host = host.split('/')[0].split('.')[0].title()
quality = source_utils.check_sd_url(url)
sources.append({'source': host, 'quality': quality, 'language': 'en', 'url': url, 'direct': False,
'debridonly': False})
except Exception:
return
return sources |
<|file_name|>coolmoviezone.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# ..#######.########.#######.##....#..######..######.########....###...########.#######.########..######.
# .##.....#.##.....#.##......###...#.##....#.##....#.##.....#...##.##..##.....#.##......##.....#.##....##
# .##.....#.##.....#.##......####..#.##......##......##.....#..##...##.##.....#.##......##.....#.##......
# .##.....#.########.######..##.##.#..######.##......########.##.....#.########.######..########..######.
# .##.....#.##.......##......##..###.......#.##......##...##..########.##.......##......##...##........##
# .##.....#.##.......##......##...##.##....#.##....#.##....##.##.....#.##.......##......##....##.##....##
# ..#######.##.......#######.##....#..######..######.##.....#.##.....#.##.......#######.##.....#..######.
'''
OpenScrapers Project
This program 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.
This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
'''
import re
from openscrapers.modules import cleantitle, source_utils, cfscrape
class source:
def __init__(self):
self.priority = 1
self.language = ['en']
self.domains = ['coolmoviezone.online']
self.base_link = 'https://coolmoviezone.online'
self.scraper = cfscrape.create_scraper()
def movie(self, imdb, title, localtitle, aliases, year):
try:
title = cleantitle.geturl(title)
url = self.base_link + '/%s-%s' % (title, year)
return url
except:
return
def sources(self, url, hostDict, hostprDict):
try:
sources = []
r = self.scraper.get(url).content
match = re.compile('<td align="center"><strong><a href="(.+?)"').findall(r)
for url in match:
host = url.split('//')[1].replace('www.', '')
host = host.split('/')[0].split('.')[0].title()
quality = source_utils.check_sd_url(url)
sources.append({'source': host, 'quality': quality, 'language': 'en', 'url': url, 'direct': False,
'debridonly': False})
except Exception:
return
return sources
def resolve(self, url):
<|fim_middle|>
<|fim▁end|> | return url |
<|file_name|>coolmoviezone.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# ..#######.########.#######.##....#..######..######.########....###...########.#######.########..######.
# .##.....#.##.....#.##......###...#.##....#.##....#.##.....#...##.##..##.....#.##......##.....#.##....##
# .##.....#.##.....#.##......####..#.##......##......##.....#..##...##.##.....#.##......##.....#.##......
# .##.....#.########.######..##.##.#..######.##......########.##.....#.########.######..########..######.
# .##.....#.##.......##......##..###.......#.##......##...##..########.##.......##......##...##........##
# .##.....#.##.......##......##...##.##....#.##....#.##....##.##.....#.##.......##......##....##.##....##
# ..#######.##.......#######.##....#..######..######.##.....#.##.....#.##.......#######.##.....#..######.
'''
OpenScrapers Project
This program 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.
This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
'''
import re
from openscrapers.modules import cleantitle, source_utils, cfscrape
class source:
def <|fim_middle|>(self):
self.priority = 1
self.language = ['en']
self.domains = ['coolmoviezone.online']
self.base_link = 'https://coolmoviezone.online'
self.scraper = cfscrape.create_scraper()
def movie(self, imdb, title, localtitle, aliases, year):
try:
title = cleantitle.geturl(title)
url = self.base_link + '/%s-%s' % (title, year)
return url
except:
return
def sources(self, url, hostDict, hostprDict):
try:
sources = []
r = self.scraper.get(url).content
match = re.compile('<td align="center"><strong><a href="(.+?)"').findall(r)
for url in match:
host = url.split('//')[1].replace('www.', '')
host = host.split('/')[0].split('.')[0].title()
quality = source_utils.check_sd_url(url)
sources.append({'source': host, 'quality': quality, 'language': 'en', 'url': url, 'direct': False,
'debridonly': False})
except Exception:
return
return sources
def resolve(self, url):
return url
<|fim▁end|> | __init__ |
<|file_name|>coolmoviezone.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# ..#######.########.#######.##....#..######..######.########....###...########.#######.########..######.
# .##.....#.##.....#.##......###...#.##....#.##....#.##.....#...##.##..##.....#.##......##.....#.##....##
# .##.....#.##.....#.##......####..#.##......##......##.....#..##...##.##.....#.##......##.....#.##......
# .##.....#.########.######..##.##.#..######.##......########.##.....#.########.######..########..######.
# .##.....#.##.......##......##..###.......#.##......##...##..########.##.......##......##...##........##
# .##.....#.##.......##......##...##.##....#.##....#.##....##.##.....#.##.......##......##....##.##....##
# ..#######.##.......#######.##....#..######..######.##.....#.##.....#.##.......#######.##.....#..######.
'''
OpenScrapers Project
This program 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.
This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
'''
import re
from openscrapers.modules import cleantitle, source_utils, cfscrape
class source:
def __init__(self):
self.priority = 1
self.language = ['en']
self.domains = ['coolmoviezone.online']
self.base_link = 'https://coolmoviezone.online'
self.scraper = cfscrape.create_scraper()
def <|fim_middle|>(self, imdb, title, localtitle, aliases, year):
try:
title = cleantitle.geturl(title)
url = self.base_link + '/%s-%s' % (title, year)
return url
except:
return
def sources(self, url, hostDict, hostprDict):
try:
sources = []
r = self.scraper.get(url).content
match = re.compile('<td align="center"><strong><a href="(.+?)"').findall(r)
for url in match:
host = url.split('//')[1].replace('www.', '')
host = host.split('/')[0].split('.')[0].title()
quality = source_utils.check_sd_url(url)
sources.append({'source': host, 'quality': quality, 'language': 'en', 'url': url, 'direct': False,
'debridonly': False})
except Exception:
return
return sources
def resolve(self, url):
return url
<|fim▁end|> | movie |
<|file_name|>coolmoviezone.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# ..#######.########.#######.##....#..######..######.########....###...########.#######.########..######.
# .##.....#.##.....#.##......###...#.##....#.##....#.##.....#...##.##..##.....#.##......##.....#.##....##
# .##.....#.##.....#.##......####..#.##......##......##.....#..##...##.##.....#.##......##.....#.##......
# .##.....#.########.######..##.##.#..######.##......########.##.....#.########.######..########..######.
# .##.....#.##.......##......##..###.......#.##......##...##..########.##.......##......##...##........##
# .##.....#.##.......##......##...##.##....#.##....#.##....##.##.....#.##.......##......##....##.##....##
# ..#######.##.......#######.##....#..######..######.##.....#.##.....#.##.......#######.##.....#..######.
'''
OpenScrapers Project
This program 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.
This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
'''
import re
from openscrapers.modules import cleantitle, source_utils, cfscrape
class source:
def __init__(self):
self.priority = 1
self.language = ['en']
self.domains = ['coolmoviezone.online']
self.base_link = 'https://coolmoviezone.online'
self.scraper = cfscrape.create_scraper()
def movie(self, imdb, title, localtitle, aliases, year):
try:
title = cleantitle.geturl(title)
url = self.base_link + '/%s-%s' % (title, year)
return url
except:
return
def <|fim_middle|>(self, url, hostDict, hostprDict):
try:
sources = []
r = self.scraper.get(url).content
match = re.compile('<td align="center"><strong><a href="(.+?)"').findall(r)
for url in match:
host = url.split('//')[1].replace('www.', '')
host = host.split('/')[0].split('.')[0].title()
quality = source_utils.check_sd_url(url)
sources.append({'source': host, 'quality': quality, 'language': 'en', 'url': url, 'direct': False,
'debridonly': False})
except Exception:
return
return sources
def resolve(self, url):
return url
<|fim▁end|> | sources |
<|file_name|>coolmoviezone.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# ..#######.########.#######.##....#..######..######.########....###...########.#######.########..######.
# .##.....#.##.....#.##......###...#.##....#.##....#.##.....#...##.##..##.....#.##......##.....#.##....##
# .##.....#.##.....#.##......####..#.##......##......##.....#..##...##.##.....#.##......##.....#.##......
# .##.....#.########.######..##.##.#..######.##......########.##.....#.########.######..########..######.
# .##.....#.##.......##......##..###.......#.##......##...##..########.##.......##......##...##........##
# .##.....#.##.......##......##...##.##....#.##....#.##....##.##.....#.##.......##......##....##.##....##
# ..#######.##.......#######.##....#..######..######.##.....#.##.....#.##.......#######.##.....#..######.
'''
OpenScrapers Project
This program 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.
This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
'''
import re
from openscrapers.modules import cleantitle, source_utils, cfscrape
class source:
def __init__(self):
self.priority = 1
self.language = ['en']
self.domains = ['coolmoviezone.online']
self.base_link = 'https://coolmoviezone.online'
self.scraper = cfscrape.create_scraper()
def movie(self, imdb, title, localtitle, aliases, year):
try:
title = cleantitle.geturl(title)
url = self.base_link + '/%s-%s' % (title, year)
return url
except:
return
def sources(self, url, hostDict, hostprDict):
try:
sources = []
r = self.scraper.get(url).content
match = re.compile('<td align="center"><strong><a href="(.+?)"').findall(r)
for url in match:
host = url.split('//')[1].replace('www.', '')
host = host.split('/')[0].split('.')[0].title()
quality = source_utils.check_sd_url(url)
sources.append({'source': host, 'quality': quality, 'language': 'en', 'url': url, 'direct': False,
'debridonly': False})
except Exception:
return
return sources
def <|fim_middle|>(self, url):
return url
<|fim▁end|> | resolve |
<|file_name|>test_dauth.py<|end_file_name|><|fim▁begin|>from nintendo import dauth, switch
from anynet import http
import pytest
CHALLENGE_REQUEST = \
"POST /v6/challenge HTTP/1.1\r\n" \
"Host: 127.0.0.1:12345\r\n" \
<|fim▁hole|> "Accept: */*\r\n" \
"X-Nintendo-PowerState: FA\r\n" \
"Content-Length: 17\r\n" \
"Content-Type: application/x-www-form-urlencoded\r\n\r\n" \
"key_generation=11"
TOKEN_REQUEST = \
"POST /v6/device_auth_token HTTP/1.1\r\n" \
"Host: 127.0.0.1:12345\r\n" \
"User-Agent: libcurl (nnDauth; 16f4553f-9eee-4e39-9b61-59bc7c99b7c8; SDK 12.3.0.0)\r\n" \
"Accept: */*\r\n" \
"X-Nintendo-PowerState: FA\r\n" \
"Content-Length: 211\r\n" \
"Content-Type: application/x-www-form-urlencoded\r\n\r\n" \
"challenge=vaNgVZZH7gUse0y3t8Cksuln-TAVtvBmcD-ow59qp0E=&" \
"client_id=8f849b5d34778d8e&ist=false&key_generation=11&" \
"system_version=CusHY#000c0000#C-BynYNPXdQJNBZjx02Hizi8lRUSIKLwPGa5p8EY1uo=&" \
"mac=xRB_6mgnNqrnF9DRsEpYMg"
@pytest.mark.anyio
async def test_dauth():
async def handler(client, request):
if request.path == "/v6/challenge":
assert request.encode().decode() == CHALLENGE_REQUEST
response = http.HTTPResponse(200)
response.json = {
"challenge": "vaNgVZZH7gUse0y3t8Cksuln-TAVtvBmcD-ow59qp0E=",
"data": "dlL7ZBNSLmYo1hUlKYZiUA=="
}
return response
else:
assert request.encode().decode() == TOKEN_REQUEST
response = http.HTTPResponse(200)
response.json = {
"device_auth_token": "device token"
}
return response
async with http.serve(handler, "127.0.0.1", 12345):
keys = switch.KeySet()
keys["aes_kek_generation_source"] = bytes.fromhex("485d45ad27c07c7e538c0183f90ee845")
keys["master_key_0a"] = bytes.fromhex("37eed242e0f2ce6f8371e783c1a6a0ae")
client = dauth.DAuthClient(keys)
client.set_url("127.0.0.1:12345")
client.set_system_version(1200)
client.set_context(None)
response = await client.device_token(client.BAAS)
token = response["device_auth_token"]
assert token == "device token"<|fim▁end|> | "User-Agent: libcurl (nnDauth; 16f4553f-9eee-4e39-9b61-59bc7c99b7c8; SDK 12.3.0.0)\r\n" \
|
<|file_name|>test_dauth.py<|end_file_name|><|fim▁begin|>
from nintendo import dauth, switch
from anynet import http
import pytest
CHALLENGE_REQUEST = \
"POST /v6/challenge HTTP/1.1\r\n" \
"Host: 127.0.0.1:12345\r\n" \
"User-Agent: libcurl (nnDauth; 16f4553f-9eee-4e39-9b61-59bc7c99b7c8; SDK 12.3.0.0)\r\n" \
"Accept: */*\r\n" \
"X-Nintendo-PowerState: FA\r\n" \
"Content-Length: 17\r\n" \
"Content-Type: application/x-www-form-urlencoded\r\n\r\n" \
"key_generation=11"
TOKEN_REQUEST = \
"POST /v6/device_auth_token HTTP/1.1\r\n" \
"Host: 127.0.0.1:12345\r\n" \
"User-Agent: libcurl (nnDauth; 16f4553f-9eee-4e39-9b61-59bc7c99b7c8; SDK 12.3.0.0)\r\n" \
"Accept: */*\r\n" \
"X-Nintendo-PowerState: FA\r\n" \
"Content-Length: 211\r\n" \
"Content-Type: application/x-www-form-urlencoded\r\n\r\n" \
"challenge=vaNgVZZH7gUse0y3t8Cksuln-TAVtvBmcD-ow59qp0E=&" \
"client_id=8f849b5d34778d8e&ist=false&key_generation=11&" \
"system_version=CusHY#000c0000#C-BynYNPXdQJNBZjx02Hizi8lRUSIKLwPGa5p8EY1uo=&" \
"mac=xRB_6mgnNqrnF9DRsEpYMg"
@pytest.mark.anyio
async def test_dauth():
<|fim_middle|>
<|fim▁end|> | async def handler(client, request):
if request.path == "/v6/challenge":
assert request.encode().decode() == CHALLENGE_REQUEST
response = http.HTTPResponse(200)
response.json = {
"challenge": "vaNgVZZH7gUse0y3t8Cksuln-TAVtvBmcD-ow59qp0E=",
"data": "dlL7ZBNSLmYo1hUlKYZiUA=="
}
return response
else:
assert request.encode().decode() == TOKEN_REQUEST
response = http.HTTPResponse(200)
response.json = {
"device_auth_token": "device token"
}
return response
async with http.serve(handler, "127.0.0.1", 12345):
keys = switch.KeySet()
keys["aes_kek_generation_source"] = bytes.fromhex("485d45ad27c07c7e538c0183f90ee845")
keys["master_key_0a"] = bytes.fromhex("37eed242e0f2ce6f8371e783c1a6a0ae")
client = dauth.DAuthClient(keys)
client.set_url("127.0.0.1:12345")
client.set_system_version(1200)
client.set_context(None)
response = await client.device_token(client.BAAS)
token = response["device_auth_token"]
assert token == "device token" |
<|file_name|>test_dauth.py<|end_file_name|><|fim▁begin|>
from nintendo import dauth, switch
from anynet import http
import pytest
CHALLENGE_REQUEST = \
"POST /v6/challenge HTTP/1.1\r\n" \
"Host: 127.0.0.1:12345\r\n" \
"User-Agent: libcurl (nnDauth; 16f4553f-9eee-4e39-9b61-59bc7c99b7c8; SDK 12.3.0.0)\r\n" \
"Accept: */*\r\n" \
"X-Nintendo-PowerState: FA\r\n" \
"Content-Length: 17\r\n" \
"Content-Type: application/x-www-form-urlencoded\r\n\r\n" \
"key_generation=11"
TOKEN_REQUEST = \
"POST /v6/device_auth_token HTTP/1.1\r\n" \
"Host: 127.0.0.1:12345\r\n" \
"User-Agent: libcurl (nnDauth; 16f4553f-9eee-4e39-9b61-59bc7c99b7c8; SDK 12.3.0.0)\r\n" \
"Accept: */*\r\n" \
"X-Nintendo-PowerState: FA\r\n" \
"Content-Length: 211\r\n" \
"Content-Type: application/x-www-form-urlencoded\r\n\r\n" \
"challenge=vaNgVZZH7gUse0y3t8Cksuln-TAVtvBmcD-ow59qp0E=&" \
"client_id=8f849b5d34778d8e&ist=false&key_generation=11&" \
"system_version=CusHY#000c0000#C-BynYNPXdQJNBZjx02Hizi8lRUSIKLwPGa5p8EY1uo=&" \
"mac=xRB_6mgnNqrnF9DRsEpYMg"
@pytest.mark.anyio
async def test_dauth():
async def handler(client, request):
<|fim_middle|>
async with http.serve(handler, "127.0.0.1", 12345):
keys = switch.KeySet()
keys["aes_kek_generation_source"] = bytes.fromhex("485d45ad27c07c7e538c0183f90ee845")
keys["master_key_0a"] = bytes.fromhex("37eed242e0f2ce6f8371e783c1a6a0ae")
client = dauth.DAuthClient(keys)
client.set_url("127.0.0.1:12345")
client.set_system_version(1200)
client.set_context(None)
response = await client.device_token(client.BAAS)
token = response["device_auth_token"]
assert token == "device token"
<|fim▁end|> | if request.path == "/v6/challenge":
assert request.encode().decode() == CHALLENGE_REQUEST
response = http.HTTPResponse(200)
response.json = {
"challenge": "vaNgVZZH7gUse0y3t8Cksuln-TAVtvBmcD-ow59qp0E=",
"data": "dlL7ZBNSLmYo1hUlKYZiUA=="
}
return response
else:
assert request.encode().decode() == TOKEN_REQUEST
response = http.HTTPResponse(200)
response.json = {
"device_auth_token": "device token"
}
return response |
<|file_name|>test_dauth.py<|end_file_name|><|fim▁begin|>
from nintendo import dauth, switch
from anynet import http
import pytest
CHALLENGE_REQUEST = \
"POST /v6/challenge HTTP/1.1\r\n" \
"Host: 127.0.0.1:12345\r\n" \
"User-Agent: libcurl (nnDauth; 16f4553f-9eee-4e39-9b61-59bc7c99b7c8; SDK 12.3.0.0)\r\n" \
"Accept: */*\r\n" \
"X-Nintendo-PowerState: FA\r\n" \
"Content-Length: 17\r\n" \
"Content-Type: application/x-www-form-urlencoded\r\n\r\n" \
"key_generation=11"
TOKEN_REQUEST = \
"POST /v6/device_auth_token HTTP/1.1\r\n" \
"Host: 127.0.0.1:12345\r\n" \
"User-Agent: libcurl (nnDauth; 16f4553f-9eee-4e39-9b61-59bc7c99b7c8; SDK 12.3.0.0)\r\n" \
"Accept: */*\r\n" \
"X-Nintendo-PowerState: FA\r\n" \
"Content-Length: 211\r\n" \
"Content-Type: application/x-www-form-urlencoded\r\n\r\n" \
"challenge=vaNgVZZH7gUse0y3t8Cksuln-TAVtvBmcD-ow59qp0E=&" \
"client_id=8f849b5d34778d8e&ist=false&key_generation=11&" \
"system_version=CusHY#000c0000#C-BynYNPXdQJNBZjx02Hizi8lRUSIKLwPGa5p8EY1uo=&" \
"mac=xRB_6mgnNqrnF9DRsEpYMg"
@pytest.mark.anyio
async def test_dauth():
async def handler(client, request):
if request.path == "/v6/challenge":
<|fim_middle|>
else:
assert request.encode().decode() == TOKEN_REQUEST
response = http.HTTPResponse(200)
response.json = {
"device_auth_token": "device token"
}
return response
async with http.serve(handler, "127.0.0.1", 12345):
keys = switch.KeySet()
keys["aes_kek_generation_source"] = bytes.fromhex("485d45ad27c07c7e538c0183f90ee845")
keys["master_key_0a"] = bytes.fromhex("37eed242e0f2ce6f8371e783c1a6a0ae")
client = dauth.DAuthClient(keys)
client.set_url("127.0.0.1:12345")
client.set_system_version(1200)
client.set_context(None)
response = await client.device_token(client.BAAS)
token = response["device_auth_token"]
assert token == "device token"
<|fim▁end|> | assert request.encode().decode() == CHALLENGE_REQUEST
response = http.HTTPResponse(200)
response.json = {
"challenge": "vaNgVZZH7gUse0y3t8Cksuln-TAVtvBmcD-ow59qp0E=",
"data": "dlL7ZBNSLmYo1hUlKYZiUA=="
}
return response |
<|file_name|>test_dauth.py<|end_file_name|><|fim▁begin|>
from nintendo import dauth, switch
from anynet import http
import pytest
CHALLENGE_REQUEST = \
"POST /v6/challenge HTTP/1.1\r\n" \
"Host: 127.0.0.1:12345\r\n" \
"User-Agent: libcurl (nnDauth; 16f4553f-9eee-4e39-9b61-59bc7c99b7c8; SDK 12.3.0.0)\r\n" \
"Accept: */*\r\n" \
"X-Nintendo-PowerState: FA\r\n" \
"Content-Length: 17\r\n" \
"Content-Type: application/x-www-form-urlencoded\r\n\r\n" \
"key_generation=11"
TOKEN_REQUEST = \
"POST /v6/device_auth_token HTTP/1.1\r\n" \
"Host: 127.0.0.1:12345\r\n" \
"User-Agent: libcurl (nnDauth; 16f4553f-9eee-4e39-9b61-59bc7c99b7c8; SDK 12.3.0.0)\r\n" \
"Accept: */*\r\n" \
"X-Nintendo-PowerState: FA\r\n" \
"Content-Length: 211\r\n" \
"Content-Type: application/x-www-form-urlencoded\r\n\r\n" \
"challenge=vaNgVZZH7gUse0y3t8Cksuln-TAVtvBmcD-ow59qp0E=&" \
"client_id=8f849b5d34778d8e&ist=false&key_generation=11&" \
"system_version=CusHY#000c0000#C-BynYNPXdQJNBZjx02Hizi8lRUSIKLwPGa5p8EY1uo=&" \
"mac=xRB_6mgnNqrnF9DRsEpYMg"
@pytest.mark.anyio
async def test_dauth():
async def handler(client, request):
if request.path == "/v6/challenge":
assert request.encode().decode() == CHALLENGE_REQUEST
response = http.HTTPResponse(200)
response.json = {
"challenge": "vaNgVZZH7gUse0y3t8Cksuln-TAVtvBmcD-ow59qp0E=",
"data": "dlL7ZBNSLmYo1hUlKYZiUA=="
}
return response
else:
<|fim_middle|>
async with http.serve(handler, "127.0.0.1", 12345):
keys = switch.KeySet()
keys["aes_kek_generation_source"] = bytes.fromhex("485d45ad27c07c7e538c0183f90ee845")
keys["master_key_0a"] = bytes.fromhex("37eed242e0f2ce6f8371e783c1a6a0ae")
client = dauth.DAuthClient(keys)
client.set_url("127.0.0.1:12345")
client.set_system_version(1200)
client.set_context(None)
response = await client.device_token(client.BAAS)
token = response["device_auth_token"]
assert token == "device token"
<|fim▁end|> | assert request.encode().decode() == TOKEN_REQUEST
response = http.HTTPResponse(200)
response.json = {
"device_auth_token": "device token"
}
return response |
<|file_name|>test_dauth.py<|end_file_name|><|fim▁begin|>
from nintendo import dauth, switch
from anynet import http
import pytest
CHALLENGE_REQUEST = \
"POST /v6/challenge HTTP/1.1\r\n" \
"Host: 127.0.0.1:12345\r\n" \
"User-Agent: libcurl (nnDauth; 16f4553f-9eee-4e39-9b61-59bc7c99b7c8; SDK 12.3.0.0)\r\n" \
"Accept: */*\r\n" \
"X-Nintendo-PowerState: FA\r\n" \
"Content-Length: 17\r\n" \
"Content-Type: application/x-www-form-urlencoded\r\n\r\n" \
"key_generation=11"
TOKEN_REQUEST = \
"POST /v6/device_auth_token HTTP/1.1\r\n" \
"Host: 127.0.0.1:12345\r\n" \
"User-Agent: libcurl (nnDauth; 16f4553f-9eee-4e39-9b61-59bc7c99b7c8; SDK 12.3.0.0)\r\n" \
"Accept: */*\r\n" \
"X-Nintendo-PowerState: FA\r\n" \
"Content-Length: 211\r\n" \
"Content-Type: application/x-www-form-urlencoded\r\n\r\n" \
"challenge=vaNgVZZH7gUse0y3t8Cksuln-TAVtvBmcD-ow59qp0E=&" \
"client_id=8f849b5d34778d8e&ist=false&key_generation=11&" \
"system_version=CusHY#000c0000#C-BynYNPXdQJNBZjx02Hizi8lRUSIKLwPGa5p8EY1uo=&" \
"mac=xRB_6mgnNqrnF9DRsEpYMg"
@pytest.mark.anyio
async def <|fim_middle|>():
async def handler(client, request):
if request.path == "/v6/challenge":
assert request.encode().decode() == CHALLENGE_REQUEST
response = http.HTTPResponse(200)
response.json = {
"challenge": "vaNgVZZH7gUse0y3t8Cksuln-TAVtvBmcD-ow59qp0E=",
"data": "dlL7ZBNSLmYo1hUlKYZiUA=="
}
return response
else:
assert request.encode().decode() == TOKEN_REQUEST
response = http.HTTPResponse(200)
response.json = {
"device_auth_token": "device token"
}
return response
async with http.serve(handler, "127.0.0.1", 12345):
keys = switch.KeySet()
keys["aes_kek_generation_source"] = bytes.fromhex("485d45ad27c07c7e538c0183f90ee845")
keys["master_key_0a"] = bytes.fromhex("37eed242e0f2ce6f8371e783c1a6a0ae")
client = dauth.DAuthClient(keys)
client.set_url("127.0.0.1:12345")
client.set_system_version(1200)
client.set_context(None)
response = await client.device_token(client.BAAS)
token = response["device_auth_token"]
assert token == "device token"
<|fim▁end|> | test_dauth |
<|file_name|>test_dauth.py<|end_file_name|><|fim▁begin|>
from nintendo import dauth, switch
from anynet import http
import pytest
CHALLENGE_REQUEST = \
"POST /v6/challenge HTTP/1.1\r\n" \
"Host: 127.0.0.1:12345\r\n" \
"User-Agent: libcurl (nnDauth; 16f4553f-9eee-4e39-9b61-59bc7c99b7c8; SDK 12.3.0.0)\r\n" \
"Accept: */*\r\n" \
"X-Nintendo-PowerState: FA\r\n" \
"Content-Length: 17\r\n" \
"Content-Type: application/x-www-form-urlencoded\r\n\r\n" \
"key_generation=11"
TOKEN_REQUEST = \
"POST /v6/device_auth_token HTTP/1.1\r\n" \
"Host: 127.0.0.1:12345\r\n" \
"User-Agent: libcurl (nnDauth; 16f4553f-9eee-4e39-9b61-59bc7c99b7c8; SDK 12.3.0.0)\r\n" \
"Accept: */*\r\n" \
"X-Nintendo-PowerState: FA\r\n" \
"Content-Length: 211\r\n" \
"Content-Type: application/x-www-form-urlencoded\r\n\r\n" \
"challenge=vaNgVZZH7gUse0y3t8Cksuln-TAVtvBmcD-ow59qp0E=&" \
"client_id=8f849b5d34778d8e&ist=false&key_generation=11&" \
"system_version=CusHY#000c0000#C-BynYNPXdQJNBZjx02Hizi8lRUSIKLwPGa5p8EY1uo=&" \
"mac=xRB_6mgnNqrnF9DRsEpYMg"
@pytest.mark.anyio
async def test_dauth():
async def <|fim_middle|>(client, request):
if request.path == "/v6/challenge":
assert request.encode().decode() == CHALLENGE_REQUEST
response = http.HTTPResponse(200)
response.json = {
"challenge": "vaNgVZZH7gUse0y3t8Cksuln-TAVtvBmcD-ow59qp0E=",
"data": "dlL7ZBNSLmYo1hUlKYZiUA=="
}
return response
else:
assert request.encode().decode() == TOKEN_REQUEST
response = http.HTTPResponse(200)
response.json = {
"device_auth_token": "device token"
}
return response
async with http.serve(handler, "127.0.0.1", 12345):
keys = switch.KeySet()
keys["aes_kek_generation_source"] = bytes.fromhex("485d45ad27c07c7e538c0183f90ee845")
keys["master_key_0a"] = bytes.fromhex("37eed242e0f2ce6f8371e783c1a6a0ae")
client = dauth.DAuthClient(keys)
client.set_url("127.0.0.1:12345")
client.set_system_version(1200)
client.set_context(None)
response = await client.device_token(client.BAAS)
token = response["device_auth_token"]
assert token == "device token"
<|fim▁end|> | handler |
<|file_name|>base.py<|end_file_name|><|fim▁begin|>"""
Django settings for lwc 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
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(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/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '7fm_f66p8e!p%o=sr%d&cue(%+bh@@j_y6*b3d@t^c5%i8)1)2'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
#Share url
SHARER_URL = "http://127.0.0.1:8000/?ref="
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'joins',<|fim▁hole|>
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',
'lwc.middleware.ReferMiddleware',
]
ROOT_URLCONF = 'lwc.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 = 'lwc.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# 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 = 'UTC'
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', 'static_root')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static', 'static_dirs'),
)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'media')<|fim▁end|> | ] |
<|file_name|>federated_cifar10.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
#
# http://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.
"""Federated CIFAR-10 classification library using TFF."""
import functools
from typing import Callable, Optional
from absl import logging
import tensorflow as tf
import tensorflow_federated as tff
from fedopt_guide import training_loop
from utils.datasets import cifar10_dataset
from utils.models import resnet_models
CIFAR_SHAPE = (32, 32, 3)
NUM_CLASSES = 100
def run_federated(
iterative_process_builder: Callable[..., tff.templates.IterativeProcess],
client_epochs_per_round: int,
client_batch_size: int,
clients_per_round: int,
client_datasets_random_seed: Optional[int] = None,
crop_size: Optional[int] = 24,
total_rounds: Optional[int] = 1500,
experiment_name: Optional[str] = 'federated_cifar10',
root_output_dir: Optional[str] = '/tmp/fed_opt',
uniform_weighting: Optional[bool] = False,
**kwargs):
"""Runs an iterative process on the CIFAR-10 classification task.
This method will load and pre-process dataset and construct a model used for
the task. It then uses `iterative_process_builder` to create an iterative
process that it applies to the task, using
`federated_research.utils.training_loop`.
We assume that the iterative process has the following functional type
signatures:
* `initialize`: `( -> S@SERVER)` where `S` represents the server state.
* `next`: `<S@SERVER, {B*}@CLIENTS> -> <S@SERVER, T@SERVER>` where `S`
represents the server state, `{B*}` represents the client datasets,
and `T` represents a python `Mapping` object.
The iterative process must also have a callable attribute `get_model_weights`
that takes as input the state of the iterative process, and returns a
`tff.learning.ModelWeights` object.
Args:
iterative_process_builder: A function that accepts a no-arg `model_fn`, and
returns a `tff.templates.IterativeProcess`. The `model_fn` must return a
`tff.learning.Model`.
client_epochs_per_round: An integer representing the number of epochs of
training performed per client in each training round.
client_batch_size: An integer representing the batch size used on clients.
clients_per_round: An integer representing the number of clients
participating in each round.
client_datasets_random_seed: An optional int used to seed which clients are
sampled at each round. If `None`, no seed is used.
crop_size: An optional integer representing the resulting size of input<|fim▁hole|> total_rounds: The number of federated training rounds.
experiment_name: The name of the experiment being run. This will be appended
to the `root_output_dir` for purposes of writing outputs.
root_output_dir: The name of the root output directory for writing
experiment outputs.
uniform_weighting: Whether to weigh clients uniformly. If false, clients are
weighted by the number of samples.
**kwargs: Additional arguments configuring the training loop. For details on
supported arguments, see `federated_research/utils/training_utils.py`.
"""
crop_shape = (crop_size, crop_size, 3)
cifar_train, _ = cifar10_dataset.get_federated_datasets(
train_client_epochs_per_round=client_epochs_per_round,
train_client_batch_size=client_batch_size,
crop_shape=crop_shape)
_, cifar_test = cifar10_dataset.get_centralized_datasets(
crop_shape=crop_shape)
input_spec = cifar_train.create_tf_dataset_for_client(
cifar_train.client_ids[0]).element_spec
model_builder = functools.partial(
resnet_models.create_resnet18,
input_shape=crop_shape,
num_classes=NUM_CLASSES)
loss_builder = tf.keras.losses.SparseCategoricalCrossentropy
metrics_builder = lambda: [tf.keras.metrics.SparseCategoricalAccuracy()]
def tff_model_fn() -> tff.learning.Model:
return tff.learning.from_keras_model(
keras_model=model_builder(),
input_spec=input_spec,
loss=loss_builder(),
metrics=metrics_builder())
if uniform_weighting:
client_weight_fn = tff.learning.ClientWeighting.UNIFORM
else:
client_weight_fn = tff.learning.ClientWeighting.NUM_EXAMPLES
training_process = iterative_process_builder(tff_model_fn, client_weight_fn)
client_datasets_fn = functools.partial(
tff.simulation.build_uniform_sampling_fn(
dataset=cifar_train.client_ids,
random_seed=client_datasets_random_seed), # pytype: disable=wrong-keyword-args # gen-stub-imports
size=clients_per_round)
evaluate_fn = tff.learning.build_federated_evaluation(
tff_model_fn, use_experimental_simulation_loop=True)
def validation_fn(model_weights, round_num):
del round_num
return evaluate_fn(model_weights, [cifar_test])
def test_fn(model_weights):
return evaluate_fn(model_weights, [cifar_test])
logging.info('Training model:')
logging.info(model_builder().summary())
training_loop.run(
iterative_process=training_process,
train_client_datasets_fn=client_datasets_fn,
evaluation_fn=validation_fn,
test_fn=test_fn,
total_rounds=total_rounds,
experiment_name=experiment_name,
root_output_dir=root_output_dir,
**kwargs)<|fim▁end|> | images after preprocessing. |
<|file_name|>federated_cifar10.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
#
# http://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.
"""Federated CIFAR-10 classification library using TFF."""
import functools
from typing import Callable, Optional
from absl import logging
import tensorflow as tf
import tensorflow_federated as tff
from fedopt_guide import training_loop
from utils.datasets import cifar10_dataset
from utils.models import resnet_models
CIFAR_SHAPE = (32, 32, 3)
NUM_CLASSES = 100
def run_federated(
iterative_process_builder: Callable[..., tff.templates.IterativeProcess],
client_epochs_per_round: int,
client_batch_size: int,
clients_per_round: int,
client_datasets_random_seed: Optional[int] = None,
crop_size: Optional[int] = 24,
total_rounds: Optional[int] = 1500,
experiment_name: Optional[str] = 'federated_cifar10',
root_output_dir: Optional[str] = '/tmp/fed_opt',
uniform_weighting: Optional[bool] = False,
**kwargs):
<|fim_middle|>
<|fim▁end|> | """Runs an iterative process on the CIFAR-10 classification task.
This method will load and pre-process dataset and construct a model used for
the task. It then uses `iterative_process_builder` to create an iterative
process that it applies to the task, using
`federated_research.utils.training_loop`.
We assume that the iterative process has the following functional type
signatures:
* `initialize`: `( -> S@SERVER)` where `S` represents the server state.
* `next`: `<S@SERVER, {B*}@CLIENTS> -> <S@SERVER, T@SERVER>` where `S`
represents the server state, `{B*}` represents the client datasets,
and `T` represents a python `Mapping` object.
The iterative process must also have a callable attribute `get_model_weights`
that takes as input the state of the iterative process, and returns a
`tff.learning.ModelWeights` object.
Args:
iterative_process_builder: A function that accepts a no-arg `model_fn`, and
returns a `tff.templates.IterativeProcess`. The `model_fn` must return a
`tff.learning.Model`.
client_epochs_per_round: An integer representing the number of epochs of
training performed per client in each training round.
client_batch_size: An integer representing the batch size used on clients.
clients_per_round: An integer representing the number of clients
participating in each round.
client_datasets_random_seed: An optional int used to seed which clients are
sampled at each round. If `None`, no seed is used.
crop_size: An optional integer representing the resulting size of input
images after preprocessing.
total_rounds: The number of federated training rounds.
experiment_name: The name of the experiment being run. This will be appended
to the `root_output_dir` for purposes of writing outputs.
root_output_dir: The name of the root output directory for writing
experiment outputs.
uniform_weighting: Whether to weigh clients uniformly. If false, clients are
weighted by the number of samples.
**kwargs: Additional arguments configuring the training loop. For details on
supported arguments, see `federated_research/utils/training_utils.py`.
"""
crop_shape = (crop_size, crop_size, 3)
cifar_train, _ = cifar10_dataset.get_federated_datasets(
train_client_epochs_per_round=client_epochs_per_round,
train_client_batch_size=client_batch_size,
crop_shape=crop_shape)
_, cifar_test = cifar10_dataset.get_centralized_datasets(
crop_shape=crop_shape)
input_spec = cifar_train.create_tf_dataset_for_client(
cifar_train.client_ids[0]).element_spec
model_builder = functools.partial(
resnet_models.create_resnet18,
input_shape=crop_shape,
num_classes=NUM_CLASSES)
loss_builder = tf.keras.losses.SparseCategoricalCrossentropy
metrics_builder = lambda: [tf.keras.metrics.SparseCategoricalAccuracy()]
def tff_model_fn() -> tff.learning.Model:
return tff.learning.from_keras_model(
keras_model=model_builder(),
input_spec=input_spec,
loss=loss_builder(),
metrics=metrics_builder())
if uniform_weighting:
client_weight_fn = tff.learning.ClientWeighting.UNIFORM
else:
client_weight_fn = tff.learning.ClientWeighting.NUM_EXAMPLES
training_process = iterative_process_builder(tff_model_fn, client_weight_fn)
client_datasets_fn = functools.partial(
tff.simulation.build_uniform_sampling_fn(
dataset=cifar_train.client_ids,
random_seed=client_datasets_random_seed), # pytype: disable=wrong-keyword-args # gen-stub-imports
size=clients_per_round)
evaluate_fn = tff.learning.build_federated_evaluation(
tff_model_fn, use_experimental_simulation_loop=True)
def validation_fn(model_weights, round_num):
del round_num
return evaluate_fn(model_weights, [cifar_test])
def test_fn(model_weights):
return evaluate_fn(model_weights, [cifar_test])
logging.info('Training model:')
logging.info(model_builder().summary())
training_loop.run(
iterative_process=training_process,
train_client_datasets_fn=client_datasets_fn,
evaluation_fn=validation_fn,
test_fn=test_fn,
total_rounds=total_rounds,
experiment_name=experiment_name,
root_output_dir=root_output_dir,
**kwargs) |
<|file_name|>federated_cifar10.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
#
# http://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.
"""Federated CIFAR-10 classification library using TFF."""
import functools
from typing import Callable, Optional
from absl import logging
import tensorflow as tf
import tensorflow_federated as tff
from fedopt_guide import training_loop
from utils.datasets import cifar10_dataset
from utils.models import resnet_models
CIFAR_SHAPE = (32, 32, 3)
NUM_CLASSES = 100
def run_federated(
iterative_process_builder: Callable[..., tff.templates.IterativeProcess],
client_epochs_per_round: int,
client_batch_size: int,
clients_per_round: int,
client_datasets_random_seed: Optional[int] = None,
crop_size: Optional[int] = 24,
total_rounds: Optional[int] = 1500,
experiment_name: Optional[str] = 'federated_cifar10',
root_output_dir: Optional[str] = '/tmp/fed_opt',
uniform_weighting: Optional[bool] = False,
**kwargs):
"""Runs an iterative process on the CIFAR-10 classification task.
This method will load and pre-process dataset and construct a model used for
the task. It then uses `iterative_process_builder` to create an iterative
process that it applies to the task, using
`federated_research.utils.training_loop`.
We assume that the iterative process has the following functional type
signatures:
* `initialize`: `( -> S@SERVER)` where `S` represents the server state.
* `next`: `<S@SERVER, {B*}@CLIENTS> -> <S@SERVER, T@SERVER>` where `S`
represents the server state, `{B*}` represents the client datasets,
and `T` represents a python `Mapping` object.
The iterative process must also have a callable attribute `get_model_weights`
that takes as input the state of the iterative process, and returns a
`tff.learning.ModelWeights` object.
Args:
iterative_process_builder: A function that accepts a no-arg `model_fn`, and
returns a `tff.templates.IterativeProcess`. The `model_fn` must return a
`tff.learning.Model`.
client_epochs_per_round: An integer representing the number of epochs of
training performed per client in each training round.
client_batch_size: An integer representing the batch size used on clients.
clients_per_round: An integer representing the number of clients
participating in each round.
client_datasets_random_seed: An optional int used to seed which clients are
sampled at each round. If `None`, no seed is used.
crop_size: An optional integer representing the resulting size of input
images after preprocessing.
total_rounds: The number of federated training rounds.
experiment_name: The name of the experiment being run. This will be appended
to the `root_output_dir` for purposes of writing outputs.
root_output_dir: The name of the root output directory for writing
experiment outputs.
uniform_weighting: Whether to weigh clients uniformly. If false, clients are
weighted by the number of samples.
**kwargs: Additional arguments configuring the training loop. For details on
supported arguments, see `federated_research/utils/training_utils.py`.
"""
crop_shape = (crop_size, crop_size, 3)
cifar_train, _ = cifar10_dataset.get_federated_datasets(
train_client_epochs_per_round=client_epochs_per_round,
train_client_batch_size=client_batch_size,
crop_shape=crop_shape)
_, cifar_test = cifar10_dataset.get_centralized_datasets(
crop_shape=crop_shape)
input_spec = cifar_train.create_tf_dataset_for_client(
cifar_train.client_ids[0]).element_spec
model_builder = functools.partial(
resnet_models.create_resnet18,
input_shape=crop_shape,
num_classes=NUM_CLASSES)
loss_builder = tf.keras.losses.SparseCategoricalCrossentropy
metrics_builder = lambda: [tf.keras.metrics.SparseCategoricalAccuracy()]
def tff_model_fn() -> tff.learning.Model:
<|fim_middle|>
if uniform_weighting:
client_weight_fn = tff.learning.ClientWeighting.UNIFORM
else:
client_weight_fn = tff.learning.ClientWeighting.NUM_EXAMPLES
training_process = iterative_process_builder(tff_model_fn, client_weight_fn)
client_datasets_fn = functools.partial(
tff.simulation.build_uniform_sampling_fn(
dataset=cifar_train.client_ids,
random_seed=client_datasets_random_seed), # pytype: disable=wrong-keyword-args # gen-stub-imports
size=clients_per_round)
evaluate_fn = tff.learning.build_federated_evaluation(
tff_model_fn, use_experimental_simulation_loop=True)
def validation_fn(model_weights, round_num):
del round_num
return evaluate_fn(model_weights, [cifar_test])
def test_fn(model_weights):
return evaluate_fn(model_weights, [cifar_test])
logging.info('Training model:')
logging.info(model_builder().summary())
training_loop.run(
iterative_process=training_process,
train_client_datasets_fn=client_datasets_fn,
evaluation_fn=validation_fn,
test_fn=test_fn,
total_rounds=total_rounds,
experiment_name=experiment_name,
root_output_dir=root_output_dir,
**kwargs)
<|fim▁end|> | return tff.learning.from_keras_model(
keras_model=model_builder(),
input_spec=input_spec,
loss=loss_builder(),
metrics=metrics_builder()) |
<|file_name|>federated_cifar10.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
#
# http://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.
"""Federated CIFAR-10 classification library using TFF."""
import functools
from typing import Callable, Optional
from absl import logging
import tensorflow as tf
import tensorflow_federated as tff
from fedopt_guide import training_loop
from utils.datasets import cifar10_dataset
from utils.models import resnet_models
CIFAR_SHAPE = (32, 32, 3)
NUM_CLASSES = 100
def run_federated(
iterative_process_builder: Callable[..., tff.templates.IterativeProcess],
client_epochs_per_round: int,
client_batch_size: int,
clients_per_round: int,
client_datasets_random_seed: Optional[int] = None,
crop_size: Optional[int] = 24,
total_rounds: Optional[int] = 1500,
experiment_name: Optional[str] = 'federated_cifar10',
root_output_dir: Optional[str] = '/tmp/fed_opt',
uniform_weighting: Optional[bool] = False,
**kwargs):
"""Runs an iterative process on the CIFAR-10 classification task.
This method will load and pre-process dataset and construct a model used for
the task. It then uses `iterative_process_builder` to create an iterative
process that it applies to the task, using
`federated_research.utils.training_loop`.
We assume that the iterative process has the following functional type
signatures:
* `initialize`: `( -> S@SERVER)` where `S` represents the server state.
* `next`: `<S@SERVER, {B*}@CLIENTS> -> <S@SERVER, T@SERVER>` where `S`
represents the server state, `{B*}` represents the client datasets,
and `T` represents a python `Mapping` object.
The iterative process must also have a callable attribute `get_model_weights`
that takes as input the state of the iterative process, and returns a
`tff.learning.ModelWeights` object.
Args:
iterative_process_builder: A function that accepts a no-arg `model_fn`, and
returns a `tff.templates.IterativeProcess`. The `model_fn` must return a
`tff.learning.Model`.
client_epochs_per_round: An integer representing the number of epochs of
training performed per client in each training round.
client_batch_size: An integer representing the batch size used on clients.
clients_per_round: An integer representing the number of clients
participating in each round.
client_datasets_random_seed: An optional int used to seed which clients are
sampled at each round. If `None`, no seed is used.
crop_size: An optional integer representing the resulting size of input
images after preprocessing.
total_rounds: The number of federated training rounds.
experiment_name: The name of the experiment being run. This will be appended
to the `root_output_dir` for purposes of writing outputs.
root_output_dir: The name of the root output directory for writing
experiment outputs.
uniform_weighting: Whether to weigh clients uniformly. If false, clients are
weighted by the number of samples.
**kwargs: Additional arguments configuring the training loop. For details on
supported arguments, see `federated_research/utils/training_utils.py`.
"""
crop_shape = (crop_size, crop_size, 3)
cifar_train, _ = cifar10_dataset.get_federated_datasets(
train_client_epochs_per_round=client_epochs_per_round,
train_client_batch_size=client_batch_size,
crop_shape=crop_shape)
_, cifar_test = cifar10_dataset.get_centralized_datasets(
crop_shape=crop_shape)
input_spec = cifar_train.create_tf_dataset_for_client(
cifar_train.client_ids[0]).element_spec
model_builder = functools.partial(
resnet_models.create_resnet18,
input_shape=crop_shape,
num_classes=NUM_CLASSES)
loss_builder = tf.keras.losses.SparseCategoricalCrossentropy
metrics_builder = lambda: [tf.keras.metrics.SparseCategoricalAccuracy()]
def tff_model_fn() -> tff.learning.Model:
return tff.learning.from_keras_model(
keras_model=model_builder(),
input_spec=input_spec,
loss=loss_builder(),
metrics=metrics_builder())
if uniform_weighting:
client_weight_fn = tff.learning.ClientWeighting.UNIFORM
else:
client_weight_fn = tff.learning.ClientWeighting.NUM_EXAMPLES
training_process = iterative_process_builder(tff_model_fn, client_weight_fn)
client_datasets_fn = functools.partial(
tff.simulation.build_uniform_sampling_fn(
dataset=cifar_train.client_ids,
random_seed=client_datasets_random_seed), # pytype: disable=wrong-keyword-args # gen-stub-imports
size=clients_per_round)
evaluate_fn = tff.learning.build_federated_evaluation(
tff_model_fn, use_experimental_simulation_loop=True)
def validation_fn(model_weights, round_num):
<|fim_middle|>
def test_fn(model_weights):
return evaluate_fn(model_weights, [cifar_test])
logging.info('Training model:')
logging.info(model_builder().summary())
training_loop.run(
iterative_process=training_process,
train_client_datasets_fn=client_datasets_fn,
evaluation_fn=validation_fn,
test_fn=test_fn,
total_rounds=total_rounds,
experiment_name=experiment_name,
root_output_dir=root_output_dir,
**kwargs)
<|fim▁end|> | del round_num
return evaluate_fn(model_weights, [cifar_test]) |
<|file_name|>federated_cifar10.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
#
# http://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.
"""Federated CIFAR-10 classification library using TFF."""
import functools
from typing import Callable, Optional
from absl import logging
import tensorflow as tf
import tensorflow_federated as tff
from fedopt_guide import training_loop
from utils.datasets import cifar10_dataset
from utils.models import resnet_models
CIFAR_SHAPE = (32, 32, 3)
NUM_CLASSES = 100
def run_federated(
iterative_process_builder: Callable[..., tff.templates.IterativeProcess],
client_epochs_per_round: int,
client_batch_size: int,
clients_per_round: int,
client_datasets_random_seed: Optional[int] = None,
crop_size: Optional[int] = 24,
total_rounds: Optional[int] = 1500,
experiment_name: Optional[str] = 'federated_cifar10',
root_output_dir: Optional[str] = '/tmp/fed_opt',
uniform_weighting: Optional[bool] = False,
**kwargs):
"""Runs an iterative process on the CIFAR-10 classification task.
This method will load and pre-process dataset and construct a model used for
the task. It then uses `iterative_process_builder` to create an iterative
process that it applies to the task, using
`federated_research.utils.training_loop`.
We assume that the iterative process has the following functional type
signatures:
* `initialize`: `( -> S@SERVER)` where `S` represents the server state.
* `next`: `<S@SERVER, {B*}@CLIENTS> -> <S@SERVER, T@SERVER>` where `S`
represents the server state, `{B*}` represents the client datasets,
and `T` represents a python `Mapping` object.
The iterative process must also have a callable attribute `get_model_weights`
that takes as input the state of the iterative process, and returns a
`tff.learning.ModelWeights` object.
Args:
iterative_process_builder: A function that accepts a no-arg `model_fn`, and
returns a `tff.templates.IterativeProcess`. The `model_fn` must return a
`tff.learning.Model`.
client_epochs_per_round: An integer representing the number of epochs of
training performed per client in each training round.
client_batch_size: An integer representing the batch size used on clients.
clients_per_round: An integer representing the number of clients
participating in each round.
client_datasets_random_seed: An optional int used to seed which clients are
sampled at each round. If `None`, no seed is used.
crop_size: An optional integer representing the resulting size of input
images after preprocessing.
total_rounds: The number of federated training rounds.
experiment_name: The name of the experiment being run. This will be appended
to the `root_output_dir` for purposes of writing outputs.
root_output_dir: The name of the root output directory for writing
experiment outputs.
uniform_weighting: Whether to weigh clients uniformly. If false, clients are
weighted by the number of samples.
**kwargs: Additional arguments configuring the training loop. For details on
supported arguments, see `federated_research/utils/training_utils.py`.
"""
crop_shape = (crop_size, crop_size, 3)
cifar_train, _ = cifar10_dataset.get_federated_datasets(
train_client_epochs_per_round=client_epochs_per_round,
train_client_batch_size=client_batch_size,
crop_shape=crop_shape)
_, cifar_test = cifar10_dataset.get_centralized_datasets(
crop_shape=crop_shape)
input_spec = cifar_train.create_tf_dataset_for_client(
cifar_train.client_ids[0]).element_spec
model_builder = functools.partial(
resnet_models.create_resnet18,
input_shape=crop_shape,
num_classes=NUM_CLASSES)
loss_builder = tf.keras.losses.SparseCategoricalCrossentropy
metrics_builder = lambda: [tf.keras.metrics.SparseCategoricalAccuracy()]
def tff_model_fn() -> tff.learning.Model:
return tff.learning.from_keras_model(
keras_model=model_builder(),
input_spec=input_spec,
loss=loss_builder(),
metrics=metrics_builder())
if uniform_weighting:
client_weight_fn = tff.learning.ClientWeighting.UNIFORM
else:
client_weight_fn = tff.learning.ClientWeighting.NUM_EXAMPLES
training_process = iterative_process_builder(tff_model_fn, client_weight_fn)
client_datasets_fn = functools.partial(
tff.simulation.build_uniform_sampling_fn(
dataset=cifar_train.client_ids,
random_seed=client_datasets_random_seed), # pytype: disable=wrong-keyword-args # gen-stub-imports
size=clients_per_round)
evaluate_fn = tff.learning.build_federated_evaluation(
tff_model_fn, use_experimental_simulation_loop=True)
def validation_fn(model_weights, round_num):
del round_num
return evaluate_fn(model_weights, [cifar_test])
def test_fn(model_weights):
<|fim_middle|>
logging.info('Training model:')
logging.info(model_builder().summary())
training_loop.run(
iterative_process=training_process,
train_client_datasets_fn=client_datasets_fn,
evaluation_fn=validation_fn,
test_fn=test_fn,
total_rounds=total_rounds,
experiment_name=experiment_name,
root_output_dir=root_output_dir,
**kwargs)
<|fim▁end|> | return evaluate_fn(model_weights, [cifar_test]) |
<|file_name|>federated_cifar10.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
#
# http://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.
"""Federated CIFAR-10 classification library using TFF."""
import functools
from typing import Callable, Optional
from absl import logging
import tensorflow as tf
import tensorflow_federated as tff
from fedopt_guide import training_loop
from utils.datasets import cifar10_dataset
from utils.models import resnet_models
CIFAR_SHAPE = (32, 32, 3)
NUM_CLASSES = 100
def run_federated(
iterative_process_builder: Callable[..., tff.templates.IterativeProcess],
client_epochs_per_round: int,
client_batch_size: int,
clients_per_round: int,
client_datasets_random_seed: Optional[int] = None,
crop_size: Optional[int] = 24,
total_rounds: Optional[int] = 1500,
experiment_name: Optional[str] = 'federated_cifar10',
root_output_dir: Optional[str] = '/tmp/fed_opt',
uniform_weighting: Optional[bool] = False,
**kwargs):
"""Runs an iterative process on the CIFAR-10 classification task.
This method will load and pre-process dataset and construct a model used for
the task. It then uses `iterative_process_builder` to create an iterative
process that it applies to the task, using
`federated_research.utils.training_loop`.
We assume that the iterative process has the following functional type
signatures:
* `initialize`: `( -> S@SERVER)` where `S` represents the server state.
* `next`: `<S@SERVER, {B*}@CLIENTS> -> <S@SERVER, T@SERVER>` where `S`
represents the server state, `{B*}` represents the client datasets,
and `T` represents a python `Mapping` object.
The iterative process must also have a callable attribute `get_model_weights`
that takes as input the state of the iterative process, and returns a
`tff.learning.ModelWeights` object.
Args:
iterative_process_builder: A function that accepts a no-arg `model_fn`, and
returns a `tff.templates.IterativeProcess`. The `model_fn` must return a
`tff.learning.Model`.
client_epochs_per_round: An integer representing the number of epochs of
training performed per client in each training round.
client_batch_size: An integer representing the batch size used on clients.
clients_per_round: An integer representing the number of clients
participating in each round.
client_datasets_random_seed: An optional int used to seed which clients are
sampled at each round. If `None`, no seed is used.
crop_size: An optional integer representing the resulting size of input
images after preprocessing.
total_rounds: The number of federated training rounds.
experiment_name: The name of the experiment being run. This will be appended
to the `root_output_dir` for purposes of writing outputs.
root_output_dir: The name of the root output directory for writing
experiment outputs.
uniform_weighting: Whether to weigh clients uniformly. If false, clients are
weighted by the number of samples.
**kwargs: Additional arguments configuring the training loop. For details on
supported arguments, see `federated_research/utils/training_utils.py`.
"""
crop_shape = (crop_size, crop_size, 3)
cifar_train, _ = cifar10_dataset.get_federated_datasets(
train_client_epochs_per_round=client_epochs_per_round,
train_client_batch_size=client_batch_size,
crop_shape=crop_shape)
_, cifar_test = cifar10_dataset.get_centralized_datasets(
crop_shape=crop_shape)
input_spec = cifar_train.create_tf_dataset_for_client(
cifar_train.client_ids[0]).element_spec
model_builder = functools.partial(
resnet_models.create_resnet18,
input_shape=crop_shape,
num_classes=NUM_CLASSES)
loss_builder = tf.keras.losses.SparseCategoricalCrossentropy
metrics_builder = lambda: [tf.keras.metrics.SparseCategoricalAccuracy()]
def tff_model_fn() -> tff.learning.Model:
return tff.learning.from_keras_model(
keras_model=model_builder(),
input_spec=input_spec,
loss=loss_builder(),
metrics=metrics_builder())
if uniform_weighting:
<|fim_middle|>
else:
client_weight_fn = tff.learning.ClientWeighting.NUM_EXAMPLES
training_process = iterative_process_builder(tff_model_fn, client_weight_fn)
client_datasets_fn = functools.partial(
tff.simulation.build_uniform_sampling_fn(
dataset=cifar_train.client_ids,
random_seed=client_datasets_random_seed), # pytype: disable=wrong-keyword-args # gen-stub-imports
size=clients_per_round)
evaluate_fn = tff.learning.build_federated_evaluation(
tff_model_fn, use_experimental_simulation_loop=True)
def validation_fn(model_weights, round_num):
del round_num
return evaluate_fn(model_weights, [cifar_test])
def test_fn(model_weights):
return evaluate_fn(model_weights, [cifar_test])
logging.info('Training model:')
logging.info(model_builder().summary())
training_loop.run(
iterative_process=training_process,
train_client_datasets_fn=client_datasets_fn,
evaluation_fn=validation_fn,
test_fn=test_fn,
total_rounds=total_rounds,
experiment_name=experiment_name,
root_output_dir=root_output_dir,
**kwargs)
<|fim▁end|> | client_weight_fn = tff.learning.ClientWeighting.UNIFORM |
<|file_name|>federated_cifar10.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
#
# http://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.
"""Federated CIFAR-10 classification library using TFF."""
import functools
from typing import Callable, Optional
from absl import logging
import tensorflow as tf
import tensorflow_federated as tff
from fedopt_guide import training_loop
from utils.datasets import cifar10_dataset
from utils.models import resnet_models
CIFAR_SHAPE = (32, 32, 3)
NUM_CLASSES = 100
def run_federated(
iterative_process_builder: Callable[..., tff.templates.IterativeProcess],
client_epochs_per_round: int,
client_batch_size: int,
clients_per_round: int,
client_datasets_random_seed: Optional[int] = None,
crop_size: Optional[int] = 24,
total_rounds: Optional[int] = 1500,
experiment_name: Optional[str] = 'federated_cifar10',
root_output_dir: Optional[str] = '/tmp/fed_opt',
uniform_weighting: Optional[bool] = False,
**kwargs):
"""Runs an iterative process on the CIFAR-10 classification task.
This method will load and pre-process dataset and construct a model used for
the task. It then uses `iterative_process_builder` to create an iterative
process that it applies to the task, using
`federated_research.utils.training_loop`.
We assume that the iterative process has the following functional type
signatures:
* `initialize`: `( -> S@SERVER)` where `S` represents the server state.
* `next`: `<S@SERVER, {B*}@CLIENTS> -> <S@SERVER, T@SERVER>` where `S`
represents the server state, `{B*}` represents the client datasets,
and `T` represents a python `Mapping` object.
The iterative process must also have a callable attribute `get_model_weights`
that takes as input the state of the iterative process, and returns a
`tff.learning.ModelWeights` object.
Args:
iterative_process_builder: A function that accepts a no-arg `model_fn`, and
returns a `tff.templates.IterativeProcess`. The `model_fn` must return a
`tff.learning.Model`.
client_epochs_per_round: An integer representing the number of epochs of
training performed per client in each training round.
client_batch_size: An integer representing the batch size used on clients.
clients_per_round: An integer representing the number of clients
participating in each round.
client_datasets_random_seed: An optional int used to seed which clients are
sampled at each round. If `None`, no seed is used.
crop_size: An optional integer representing the resulting size of input
images after preprocessing.
total_rounds: The number of federated training rounds.
experiment_name: The name of the experiment being run. This will be appended
to the `root_output_dir` for purposes of writing outputs.
root_output_dir: The name of the root output directory for writing
experiment outputs.
uniform_weighting: Whether to weigh clients uniformly. If false, clients are
weighted by the number of samples.
**kwargs: Additional arguments configuring the training loop. For details on
supported arguments, see `federated_research/utils/training_utils.py`.
"""
crop_shape = (crop_size, crop_size, 3)
cifar_train, _ = cifar10_dataset.get_federated_datasets(
train_client_epochs_per_round=client_epochs_per_round,
train_client_batch_size=client_batch_size,
crop_shape=crop_shape)
_, cifar_test = cifar10_dataset.get_centralized_datasets(
crop_shape=crop_shape)
input_spec = cifar_train.create_tf_dataset_for_client(
cifar_train.client_ids[0]).element_spec
model_builder = functools.partial(
resnet_models.create_resnet18,
input_shape=crop_shape,
num_classes=NUM_CLASSES)
loss_builder = tf.keras.losses.SparseCategoricalCrossentropy
metrics_builder = lambda: [tf.keras.metrics.SparseCategoricalAccuracy()]
def tff_model_fn() -> tff.learning.Model:
return tff.learning.from_keras_model(
keras_model=model_builder(),
input_spec=input_spec,
loss=loss_builder(),
metrics=metrics_builder())
if uniform_weighting:
client_weight_fn = tff.learning.ClientWeighting.UNIFORM
else:
<|fim_middle|>
training_process = iterative_process_builder(tff_model_fn, client_weight_fn)
client_datasets_fn = functools.partial(
tff.simulation.build_uniform_sampling_fn(
dataset=cifar_train.client_ids,
random_seed=client_datasets_random_seed), # pytype: disable=wrong-keyword-args # gen-stub-imports
size=clients_per_round)
evaluate_fn = tff.learning.build_federated_evaluation(
tff_model_fn, use_experimental_simulation_loop=True)
def validation_fn(model_weights, round_num):
del round_num
return evaluate_fn(model_weights, [cifar_test])
def test_fn(model_weights):
return evaluate_fn(model_weights, [cifar_test])
logging.info('Training model:')
logging.info(model_builder().summary())
training_loop.run(
iterative_process=training_process,
train_client_datasets_fn=client_datasets_fn,
evaluation_fn=validation_fn,
test_fn=test_fn,
total_rounds=total_rounds,
experiment_name=experiment_name,
root_output_dir=root_output_dir,
**kwargs)
<|fim▁end|> | client_weight_fn = tff.learning.ClientWeighting.NUM_EXAMPLES |
<|file_name|>federated_cifar10.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
#
# http://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.
"""Federated CIFAR-10 classification library using TFF."""
import functools
from typing import Callable, Optional
from absl import logging
import tensorflow as tf
import tensorflow_federated as tff
from fedopt_guide import training_loop
from utils.datasets import cifar10_dataset
from utils.models import resnet_models
CIFAR_SHAPE = (32, 32, 3)
NUM_CLASSES = 100
def <|fim_middle|>(
iterative_process_builder: Callable[..., tff.templates.IterativeProcess],
client_epochs_per_round: int,
client_batch_size: int,
clients_per_round: int,
client_datasets_random_seed: Optional[int] = None,
crop_size: Optional[int] = 24,
total_rounds: Optional[int] = 1500,
experiment_name: Optional[str] = 'federated_cifar10',
root_output_dir: Optional[str] = '/tmp/fed_opt',
uniform_weighting: Optional[bool] = False,
**kwargs):
"""Runs an iterative process on the CIFAR-10 classification task.
This method will load and pre-process dataset and construct a model used for
the task. It then uses `iterative_process_builder` to create an iterative
process that it applies to the task, using
`federated_research.utils.training_loop`.
We assume that the iterative process has the following functional type
signatures:
* `initialize`: `( -> S@SERVER)` where `S` represents the server state.
* `next`: `<S@SERVER, {B*}@CLIENTS> -> <S@SERVER, T@SERVER>` where `S`
represents the server state, `{B*}` represents the client datasets,
and `T` represents a python `Mapping` object.
The iterative process must also have a callable attribute `get_model_weights`
that takes as input the state of the iterative process, and returns a
`tff.learning.ModelWeights` object.
Args:
iterative_process_builder: A function that accepts a no-arg `model_fn`, and
returns a `tff.templates.IterativeProcess`. The `model_fn` must return a
`tff.learning.Model`.
client_epochs_per_round: An integer representing the number of epochs of
training performed per client in each training round.
client_batch_size: An integer representing the batch size used on clients.
clients_per_round: An integer representing the number of clients
participating in each round.
client_datasets_random_seed: An optional int used to seed which clients are
sampled at each round. If `None`, no seed is used.
crop_size: An optional integer representing the resulting size of input
images after preprocessing.
total_rounds: The number of federated training rounds.
experiment_name: The name of the experiment being run. This will be appended
to the `root_output_dir` for purposes of writing outputs.
root_output_dir: The name of the root output directory for writing
experiment outputs.
uniform_weighting: Whether to weigh clients uniformly. If false, clients are
weighted by the number of samples.
**kwargs: Additional arguments configuring the training loop. For details on
supported arguments, see `federated_research/utils/training_utils.py`.
"""
crop_shape = (crop_size, crop_size, 3)
cifar_train, _ = cifar10_dataset.get_federated_datasets(
train_client_epochs_per_round=client_epochs_per_round,
train_client_batch_size=client_batch_size,
crop_shape=crop_shape)
_, cifar_test = cifar10_dataset.get_centralized_datasets(
crop_shape=crop_shape)
input_spec = cifar_train.create_tf_dataset_for_client(
cifar_train.client_ids[0]).element_spec
model_builder = functools.partial(
resnet_models.create_resnet18,
input_shape=crop_shape,
num_classes=NUM_CLASSES)
loss_builder = tf.keras.losses.SparseCategoricalCrossentropy
metrics_builder = lambda: [tf.keras.metrics.SparseCategoricalAccuracy()]
def tff_model_fn() -> tff.learning.Model:
return tff.learning.from_keras_model(
keras_model=model_builder(),
input_spec=input_spec,
loss=loss_builder(),
metrics=metrics_builder())
if uniform_weighting:
client_weight_fn = tff.learning.ClientWeighting.UNIFORM
else:
client_weight_fn = tff.learning.ClientWeighting.NUM_EXAMPLES
training_process = iterative_process_builder(tff_model_fn, client_weight_fn)
client_datasets_fn = functools.partial(
tff.simulation.build_uniform_sampling_fn(
dataset=cifar_train.client_ids,
random_seed=client_datasets_random_seed), # pytype: disable=wrong-keyword-args # gen-stub-imports
size=clients_per_round)
evaluate_fn = tff.learning.build_federated_evaluation(
tff_model_fn, use_experimental_simulation_loop=True)
def validation_fn(model_weights, round_num):
del round_num
return evaluate_fn(model_weights, [cifar_test])
def test_fn(model_weights):
return evaluate_fn(model_weights, [cifar_test])
logging.info('Training model:')
logging.info(model_builder().summary())
training_loop.run(
iterative_process=training_process,
train_client_datasets_fn=client_datasets_fn,
evaluation_fn=validation_fn,
test_fn=test_fn,
total_rounds=total_rounds,
experiment_name=experiment_name,
root_output_dir=root_output_dir,
**kwargs)
<|fim▁end|> | run_federated |
<|file_name|>federated_cifar10.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
#
# http://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.
"""Federated CIFAR-10 classification library using TFF."""
import functools
from typing import Callable, Optional
from absl import logging
import tensorflow as tf
import tensorflow_federated as tff
from fedopt_guide import training_loop
from utils.datasets import cifar10_dataset
from utils.models import resnet_models
CIFAR_SHAPE = (32, 32, 3)
NUM_CLASSES = 100
def run_federated(
iterative_process_builder: Callable[..., tff.templates.IterativeProcess],
client_epochs_per_round: int,
client_batch_size: int,
clients_per_round: int,
client_datasets_random_seed: Optional[int] = None,
crop_size: Optional[int] = 24,
total_rounds: Optional[int] = 1500,
experiment_name: Optional[str] = 'federated_cifar10',
root_output_dir: Optional[str] = '/tmp/fed_opt',
uniform_weighting: Optional[bool] = False,
**kwargs):
"""Runs an iterative process on the CIFAR-10 classification task.
This method will load and pre-process dataset and construct a model used for
the task. It then uses `iterative_process_builder` to create an iterative
process that it applies to the task, using
`federated_research.utils.training_loop`.
We assume that the iterative process has the following functional type
signatures:
* `initialize`: `( -> S@SERVER)` where `S` represents the server state.
* `next`: `<S@SERVER, {B*}@CLIENTS> -> <S@SERVER, T@SERVER>` where `S`
represents the server state, `{B*}` represents the client datasets,
and `T` represents a python `Mapping` object.
The iterative process must also have a callable attribute `get_model_weights`
that takes as input the state of the iterative process, and returns a
`tff.learning.ModelWeights` object.
Args:
iterative_process_builder: A function that accepts a no-arg `model_fn`, and
returns a `tff.templates.IterativeProcess`. The `model_fn` must return a
`tff.learning.Model`.
client_epochs_per_round: An integer representing the number of epochs of
training performed per client in each training round.
client_batch_size: An integer representing the batch size used on clients.
clients_per_round: An integer representing the number of clients
participating in each round.
client_datasets_random_seed: An optional int used to seed which clients are
sampled at each round. If `None`, no seed is used.
crop_size: An optional integer representing the resulting size of input
images after preprocessing.
total_rounds: The number of federated training rounds.
experiment_name: The name of the experiment being run. This will be appended
to the `root_output_dir` for purposes of writing outputs.
root_output_dir: The name of the root output directory for writing
experiment outputs.
uniform_weighting: Whether to weigh clients uniformly. If false, clients are
weighted by the number of samples.
**kwargs: Additional arguments configuring the training loop. For details on
supported arguments, see `federated_research/utils/training_utils.py`.
"""
crop_shape = (crop_size, crop_size, 3)
cifar_train, _ = cifar10_dataset.get_federated_datasets(
train_client_epochs_per_round=client_epochs_per_round,
train_client_batch_size=client_batch_size,
crop_shape=crop_shape)
_, cifar_test = cifar10_dataset.get_centralized_datasets(
crop_shape=crop_shape)
input_spec = cifar_train.create_tf_dataset_for_client(
cifar_train.client_ids[0]).element_spec
model_builder = functools.partial(
resnet_models.create_resnet18,
input_shape=crop_shape,
num_classes=NUM_CLASSES)
loss_builder = tf.keras.losses.SparseCategoricalCrossentropy
metrics_builder = lambda: [tf.keras.metrics.SparseCategoricalAccuracy()]
def <|fim_middle|>() -> tff.learning.Model:
return tff.learning.from_keras_model(
keras_model=model_builder(),
input_spec=input_spec,
loss=loss_builder(),
metrics=metrics_builder())
if uniform_weighting:
client_weight_fn = tff.learning.ClientWeighting.UNIFORM
else:
client_weight_fn = tff.learning.ClientWeighting.NUM_EXAMPLES
training_process = iterative_process_builder(tff_model_fn, client_weight_fn)
client_datasets_fn = functools.partial(
tff.simulation.build_uniform_sampling_fn(
dataset=cifar_train.client_ids,
random_seed=client_datasets_random_seed), # pytype: disable=wrong-keyword-args # gen-stub-imports
size=clients_per_round)
evaluate_fn = tff.learning.build_federated_evaluation(
tff_model_fn, use_experimental_simulation_loop=True)
def validation_fn(model_weights, round_num):
del round_num
return evaluate_fn(model_weights, [cifar_test])
def test_fn(model_weights):
return evaluate_fn(model_weights, [cifar_test])
logging.info('Training model:')
logging.info(model_builder().summary())
training_loop.run(
iterative_process=training_process,
train_client_datasets_fn=client_datasets_fn,
evaluation_fn=validation_fn,
test_fn=test_fn,
total_rounds=total_rounds,
experiment_name=experiment_name,
root_output_dir=root_output_dir,
**kwargs)
<|fim▁end|> | tff_model_fn |
<|file_name|>federated_cifar10.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
#
# http://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.
"""Federated CIFAR-10 classification library using TFF."""
import functools
from typing import Callable, Optional
from absl import logging
import tensorflow as tf
import tensorflow_federated as tff
from fedopt_guide import training_loop
from utils.datasets import cifar10_dataset
from utils.models import resnet_models
CIFAR_SHAPE = (32, 32, 3)
NUM_CLASSES = 100
def run_federated(
iterative_process_builder: Callable[..., tff.templates.IterativeProcess],
client_epochs_per_round: int,
client_batch_size: int,
clients_per_round: int,
client_datasets_random_seed: Optional[int] = None,
crop_size: Optional[int] = 24,
total_rounds: Optional[int] = 1500,
experiment_name: Optional[str] = 'federated_cifar10',
root_output_dir: Optional[str] = '/tmp/fed_opt',
uniform_weighting: Optional[bool] = False,
**kwargs):
"""Runs an iterative process on the CIFAR-10 classification task.
This method will load and pre-process dataset and construct a model used for
the task. It then uses `iterative_process_builder` to create an iterative
process that it applies to the task, using
`federated_research.utils.training_loop`.
We assume that the iterative process has the following functional type
signatures:
* `initialize`: `( -> S@SERVER)` where `S` represents the server state.
* `next`: `<S@SERVER, {B*}@CLIENTS> -> <S@SERVER, T@SERVER>` where `S`
represents the server state, `{B*}` represents the client datasets,
and `T` represents a python `Mapping` object.
The iterative process must also have a callable attribute `get_model_weights`
that takes as input the state of the iterative process, and returns a
`tff.learning.ModelWeights` object.
Args:
iterative_process_builder: A function that accepts a no-arg `model_fn`, and
returns a `tff.templates.IterativeProcess`. The `model_fn` must return a
`tff.learning.Model`.
client_epochs_per_round: An integer representing the number of epochs of
training performed per client in each training round.
client_batch_size: An integer representing the batch size used on clients.
clients_per_round: An integer representing the number of clients
participating in each round.
client_datasets_random_seed: An optional int used to seed which clients are
sampled at each round. If `None`, no seed is used.
crop_size: An optional integer representing the resulting size of input
images after preprocessing.
total_rounds: The number of federated training rounds.
experiment_name: The name of the experiment being run. This will be appended
to the `root_output_dir` for purposes of writing outputs.
root_output_dir: The name of the root output directory for writing
experiment outputs.
uniform_weighting: Whether to weigh clients uniformly. If false, clients are
weighted by the number of samples.
**kwargs: Additional arguments configuring the training loop. For details on
supported arguments, see `federated_research/utils/training_utils.py`.
"""
crop_shape = (crop_size, crop_size, 3)
cifar_train, _ = cifar10_dataset.get_federated_datasets(
train_client_epochs_per_round=client_epochs_per_round,
train_client_batch_size=client_batch_size,
crop_shape=crop_shape)
_, cifar_test = cifar10_dataset.get_centralized_datasets(
crop_shape=crop_shape)
input_spec = cifar_train.create_tf_dataset_for_client(
cifar_train.client_ids[0]).element_spec
model_builder = functools.partial(
resnet_models.create_resnet18,
input_shape=crop_shape,
num_classes=NUM_CLASSES)
loss_builder = tf.keras.losses.SparseCategoricalCrossentropy
metrics_builder = lambda: [tf.keras.metrics.SparseCategoricalAccuracy()]
def tff_model_fn() -> tff.learning.Model:
return tff.learning.from_keras_model(
keras_model=model_builder(),
input_spec=input_spec,
loss=loss_builder(),
metrics=metrics_builder())
if uniform_weighting:
client_weight_fn = tff.learning.ClientWeighting.UNIFORM
else:
client_weight_fn = tff.learning.ClientWeighting.NUM_EXAMPLES
training_process = iterative_process_builder(tff_model_fn, client_weight_fn)
client_datasets_fn = functools.partial(
tff.simulation.build_uniform_sampling_fn(
dataset=cifar_train.client_ids,
random_seed=client_datasets_random_seed), # pytype: disable=wrong-keyword-args # gen-stub-imports
size=clients_per_round)
evaluate_fn = tff.learning.build_federated_evaluation(
tff_model_fn, use_experimental_simulation_loop=True)
def <|fim_middle|>(model_weights, round_num):
del round_num
return evaluate_fn(model_weights, [cifar_test])
def test_fn(model_weights):
return evaluate_fn(model_weights, [cifar_test])
logging.info('Training model:')
logging.info(model_builder().summary())
training_loop.run(
iterative_process=training_process,
train_client_datasets_fn=client_datasets_fn,
evaluation_fn=validation_fn,
test_fn=test_fn,
total_rounds=total_rounds,
experiment_name=experiment_name,
root_output_dir=root_output_dir,
**kwargs)
<|fim▁end|> | validation_fn |
<|file_name|>federated_cifar10.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
#
# http://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.
"""Federated CIFAR-10 classification library using TFF."""
import functools
from typing import Callable, Optional
from absl import logging
import tensorflow as tf
import tensorflow_federated as tff
from fedopt_guide import training_loop
from utils.datasets import cifar10_dataset
from utils.models import resnet_models
CIFAR_SHAPE = (32, 32, 3)
NUM_CLASSES = 100
def run_federated(
iterative_process_builder: Callable[..., tff.templates.IterativeProcess],
client_epochs_per_round: int,
client_batch_size: int,
clients_per_round: int,
client_datasets_random_seed: Optional[int] = None,
crop_size: Optional[int] = 24,
total_rounds: Optional[int] = 1500,
experiment_name: Optional[str] = 'federated_cifar10',
root_output_dir: Optional[str] = '/tmp/fed_opt',
uniform_weighting: Optional[bool] = False,
**kwargs):
"""Runs an iterative process on the CIFAR-10 classification task.
This method will load and pre-process dataset and construct a model used for
the task. It then uses `iterative_process_builder` to create an iterative
process that it applies to the task, using
`federated_research.utils.training_loop`.
We assume that the iterative process has the following functional type
signatures:
* `initialize`: `( -> S@SERVER)` where `S` represents the server state.
* `next`: `<S@SERVER, {B*}@CLIENTS> -> <S@SERVER, T@SERVER>` where `S`
represents the server state, `{B*}` represents the client datasets,
and `T` represents a python `Mapping` object.
The iterative process must also have a callable attribute `get_model_weights`
that takes as input the state of the iterative process, and returns a
`tff.learning.ModelWeights` object.
Args:
iterative_process_builder: A function that accepts a no-arg `model_fn`, and
returns a `tff.templates.IterativeProcess`. The `model_fn` must return a
`tff.learning.Model`.
client_epochs_per_round: An integer representing the number of epochs of
training performed per client in each training round.
client_batch_size: An integer representing the batch size used on clients.
clients_per_round: An integer representing the number of clients
participating in each round.
client_datasets_random_seed: An optional int used to seed which clients are
sampled at each round. If `None`, no seed is used.
crop_size: An optional integer representing the resulting size of input
images after preprocessing.
total_rounds: The number of federated training rounds.
experiment_name: The name of the experiment being run. This will be appended
to the `root_output_dir` for purposes of writing outputs.
root_output_dir: The name of the root output directory for writing
experiment outputs.
uniform_weighting: Whether to weigh clients uniformly. If false, clients are
weighted by the number of samples.
**kwargs: Additional arguments configuring the training loop. For details on
supported arguments, see `federated_research/utils/training_utils.py`.
"""
crop_shape = (crop_size, crop_size, 3)
cifar_train, _ = cifar10_dataset.get_federated_datasets(
train_client_epochs_per_round=client_epochs_per_round,
train_client_batch_size=client_batch_size,
crop_shape=crop_shape)
_, cifar_test = cifar10_dataset.get_centralized_datasets(
crop_shape=crop_shape)
input_spec = cifar_train.create_tf_dataset_for_client(
cifar_train.client_ids[0]).element_spec
model_builder = functools.partial(
resnet_models.create_resnet18,
input_shape=crop_shape,
num_classes=NUM_CLASSES)
loss_builder = tf.keras.losses.SparseCategoricalCrossentropy
metrics_builder = lambda: [tf.keras.metrics.SparseCategoricalAccuracy()]
def tff_model_fn() -> tff.learning.Model:
return tff.learning.from_keras_model(
keras_model=model_builder(),
input_spec=input_spec,
loss=loss_builder(),
metrics=metrics_builder())
if uniform_weighting:
client_weight_fn = tff.learning.ClientWeighting.UNIFORM
else:
client_weight_fn = tff.learning.ClientWeighting.NUM_EXAMPLES
training_process = iterative_process_builder(tff_model_fn, client_weight_fn)
client_datasets_fn = functools.partial(
tff.simulation.build_uniform_sampling_fn(
dataset=cifar_train.client_ids,
random_seed=client_datasets_random_seed), # pytype: disable=wrong-keyword-args # gen-stub-imports
size=clients_per_round)
evaluate_fn = tff.learning.build_federated_evaluation(
tff_model_fn, use_experimental_simulation_loop=True)
def validation_fn(model_weights, round_num):
del round_num
return evaluate_fn(model_weights, [cifar_test])
def <|fim_middle|>(model_weights):
return evaluate_fn(model_weights, [cifar_test])
logging.info('Training model:')
logging.info(model_builder().summary())
training_loop.run(
iterative_process=training_process,
train_client_datasets_fn=client_datasets_fn,
evaluation_fn=validation_fn,
test_fn=test_fn,
total_rounds=total_rounds,
experiment_name=experiment_name,
root_output_dir=root_output_dir,
**kwargs)
<|fim▁end|> | test_fn |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""
Provides functionality to emulate keyboard presses on host machine.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/keyboard/
"""
import voluptuous as vol
from homeassistant.const import (
SERVICE_MEDIA_NEXT_TRACK, SERVICE_MEDIA_PLAY_PAUSE,
SERVICE_MEDIA_PREVIOUS_TRACK, SERVICE_VOLUME_DOWN, SERVICE_VOLUME_MUTE,
SERVICE_VOLUME_UP)
REQUIREMENTS = ['pyuserinput==0.1.11']
DOMAIN = 'keyboard'
TAP_KEY_SCHEMA = vol.Schema({})
def setup(hass, config):
"""Listen for keyboard events."""
import pykeyboard # pylint: disable=import-error
keyboard = pykeyboard.PyKeyboard()
keyboard.special_key_assignment()
hass.services.register(DOMAIN, SERVICE_VOLUME_UP,
lambda service:
keyboard.tap_key(keyboard.volume_up_key),
schema=TAP_KEY_SCHEMA)
hass.services.register(DOMAIN, SERVICE_VOLUME_DOWN,
lambda service:
keyboard.tap_key(keyboard.volume_down_key),
schema=TAP_KEY_SCHEMA)
hass.services.register(DOMAIN, SERVICE_VOLUME_MUTE,
lambda service:
keyboard.tap_key(keyboard.volume_mute_key),
schema=TAP_KEY_SCHEMA)
hass.services.register(DOMAIN, SERVICE_MEDIA_PLAY_PAUSE,
lambda service:
keyboard.tap_key(keyboard.media_play_pause_key),
schema=TAP_KEY_SCHEMA)
hass.services.register(DOMAIN, SERVICE_MEDIA_NEXT_TRACK,
lambda service:<|fim▁hole|>
hass.services.register(DOMAIN, SERVICE_MEDIA_PREVIOUS_TRACK,
lambda service:
keyboard.tap_key(keyboard.media_prev_track_key),
schema=TAP_KEY_SCHEMA)
return True<|fim▁end|> | keyboard.tap_key(keyboard.media_next_track_key),
schema=TAP_KEY_SCHEMA) |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""
Provides functionality to emulate keyboard presses on host machine.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/keyboard/
"""
import voluptuous as vol
from homeassistant.const import (
SERVICE_MEDIA_NEXT_TRACK, SERVICE_MEDIA_PLAY_PAUSE,
SERVICE_MEDIA_PREVIOUS_TRACK, SERVICE_VOLUME_DOWN, SERVICE_VOLUME_MUTE,
SERVICE_VOLUME_UP)
REQUIREMENTS = ['pyuserinput==0.1.11']
DOMAIN = 'keyboard'
TAP_KEY_SCHEMA = vol.Schema({})
def setup(hass, config):
<|fim_middle|>
<|fim▁end|> | """Listen for keyboard events."""
import pykeyboard # pylint: disable=import-error
keyboard = pykeyboard.PyKeyboard()
keyboard.special_key_assignment()
hass.services.register(DOMAIN, SERVICE_VOLUME_UP,
lambda service:
keyboard.tap_key(keyboard.volume_up_key),
schema=TAP_KEY_SCHEMA)
hass.services.register(DOMAIN, SERVICE_VOLUME_DOWN,
lambda service:
keyboard.tap_key(keyboard.volume_down_key),
schema=TAP_KEY_SCHEMA)
hass.services.register(DOMAIN, SERVICE_VOLUME_MUTE,
lambda service:
keyboard.tap_key(keyboard.volume_mute_key),
schema=TAP_KEY_SCHEMA)
hass.services.register(DOMAIN, SERVICE_MEDIA_PLAY_PAUSE,
lambda service:
keyboard.tap_key(keyboard.media_play_pause_key),
schema=TAP_KEY_SCHEMA)
hass.services.register(DOMAIN, SERVICE_MEDIA_NEXT_TRACK,
lambda service:
keyboard.tap_key(keyboard.media_next_track_key),
schema=TAP_KEY_SCHEMA)
hass.services.register(DOMAIN, SERVICE_MEDIA_PREVIOUS_TRACK,
lambda service:
keyboard.tap_key(keyboard.media_prev_track_key),
schema=TAP_KEY_SCHEMA)
return True |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""
Provides functionality to emulate keyboard presses on host machine.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/keyboard/
"""
import voluptuous as vol
from homeassistant.const import (
SERVICE_MEDIA_NEXT_TRACK, SERVICE_MEDIA_PLAY_PAUSE,
SERVICE_MEDIA_PREVIOUS_TRACK, SERVICE_VOLUME_DOWN, SERVICE_VOLUME_MUTE,
SERVICE_VOLUME_UP)
REQUIREMENTS = ['pyuserinput==0.1.11']
DOMAIN = 'keyboard'
TAP_KEY_SCHEMA = vol.Schema({})
def <|fim_middle|>(hass, config):
"""Listen for keyboard events."""
import pykeyboard # pylint: disable=import-error
keyboard = pykeyboard.PyKeyboard()
keyboard.special_key_assignment()
hass.services.register(DOMAIN, SERVICE_VOLUME_UP,
lambda service:
keyboard.tap_key(keyboard.volume_up_key),
schema=TAP_KEY_SCHEMA)
hass.services.register(DOMAIN, SERVICE_VOLUME_DOWN,
lambda service:
keyboard.tap_key(keyboard.volume_down_key),
schema=TAP_KEY_SCHEMA)
hass.services.register(DOMAIN, SERVICE_VOLUME_MUTE,
lambda service:
keyboard.tap_key(keyboard.volume_mute_key),
schema=TAP_KEY_SCHEMA)
hass.services.register(DOMAIN, SERVICE_MEDIA_PLAY_PAUSE,
lambda service:
keyboard.tap_key(keyboard.media_play_pause_key),
schema=TAP_KEY_SCHEMA)
hass.services.register(DOMAIN, SERVICE_MEDIA_NEXT_TRACK,
lambda service:
keyboard.tap_key(keyboard.media_next_track_key),
schema=TAP_KEY_SCHEMA)
hass.services.register(DOMAIN, SERVICE_MEDIA_PREVIOUS_TRACK,
lambda service:
keyboard.tap_key(keyboard.media_prev_track_key),
schema=TAP_KEY_SCHEMA)
return True
<|fim▁end|> | setup |
<|file_name|>worker.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2013 ASMlover. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#<|fim▁hole|>#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materialsprovided with the
# distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import zmq
import time
if __name__ == '__main__':
ctx = zmq.Context()
worker = ctx.socket(zmq.PULL)
worker.connect('tcp://localhost:5555')
sinker = ctx.socket(zmq.PUSH)
sinker.connect('tcp://localhost:6666')
print 'all workers are ready ...'
while True:
try:
msg = worker.recv()
print 'begin to work on task use `%s ms`' % msg
time.sleep(int(msg) * 0.001)
print '\tfinished this task'
sinker.send('finished task which used `%s ms`' % msg)
except KeyboardInterrupt:
break
sinker.close()
worker.close()<|fim▁end|> | # * Redistributions of source code must retain the above copyright
# notice, this list ofconditions and the following disclaimer. |
<|file_name|>worker.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2013 ASMlover. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list ofconditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materialsprovided with the
# distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import zmq
import time
if __name__ == '__main__':
<|fim_middle|>
<|fim▁end|> | ctx = zmq.Context()
worker = ctx.socket(zmq.PULL)
worker.connect('tcp://localhost:5555')
sinker = ctx.socket(zmq.PUSH)
sinker.connect('tcp://localhost:6666')
print 'all workers are ready ...'
while True:
try:
msg = worker.recv()
print 'begin to work on task use `%s ms`' % msg
time.sleep(int(msg) * 0.001)
print '\tfinished this task'
sinker.send('finished task which used `%s ms`' % msg)
except KeyboardInterrupt:
break
sinker.close()
worker.close() |
<|file_name|>views.py<|end_file_name|><|fim▁begin|># # product
import logging
from django.contrib import messages
from django.contrib.auth.decorators import user_passes_test
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from dojo.utils import add_breadcrumb
from dojo.forms import ToolTypeForm
from dojo.models import Tool_Type
logger = logging.getLogger(__name__)
@user_passes_test(lambda u: u.is_staff)
def new_tool_type(request):
if request.method == 'POST':
tform = ToolTypeForm(request.POST, instance=Tool_Type())
if tform.is_valid():<|fim▁hole|> extra_tags='alert-success')
return HttpResponseRedirect(reverse('tool_type', ))
else:
tform = ToolTypeForm()
add_breadcrumb(title="New Tool Type Configuration", top_level=False, request=request)
return render(request, 'dojo/new_tool_type.html',
{'tform': tform})
@user_passes_test(lambda u: u.is_staff)
def edit_tool_type(request, ttid):
tool_type = Tool_Type.objects.get(pk=ttid)
if request.method == 'POST':
tform = ToolTypeForm(request.POST, instance=tool_type)
if tform.is_valid():
tform.save()
messages.add_message(request,
messages.SUCCESS,
'Tool Type Configuration Successfully Updated.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('tool_type', ))
else:
tform = ToolTypeForm(instance=tool_type)
add_breadcrumb(title="Edit Tool Type Configuration", top_level=False, request=request)
return render(request,
'dojo/edit_tool_type.html',
{
'tform': tform,
})
@user_passes_test(lambda u: u.is_staff)
def tool_type(request):
confs = Tool_Type.objects.all().order_by('name')
add_breadcrumb(title="Tool Type List", top_level=not len(request.GET), request=request)
return render(request,
'dojo/tool_type.html',
{'confs': confs,
})<|fim▁end|> | tform.save()
messages.add_message(request,
messages.SUCCESS,
'Tool Type Configuration Successfully Created.', |
<|file_name|>views.py<|end_file_name|><|fim▁begin|># # product
import logging
from django.contrib import messages
from django.contrib.auth.decorators import user_passes_test
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from dojo.utils import add_breadcrumb
from dojo.forms import ToolTypeForm
from dojo.models import Tool_Type
logger = logging.getLogger(__name__)
@user_passes_test(lambda u: u.is_staff)
def new_tool_type(request):
<|fim_middle|>
@user_passes_test(lambda u: u.is_staff)
def edit_tool_type(request, ttid):
tool_type = Tool_Type.objects.get(pk=ttid)
if request.method == 'POST':
tform = ToolTypeForm(request.POST, instance=tool_type)
if tform.is_valid():
tform.save()
messages.add_message(request,
messages.SUCCESS,
'Tool Type Configuration Successfully Updated.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('tool_type', ))
else:
tform = ToolTypeForm(instance=tool_type)
add_breadcrumb(title="Edit Tool Type Configuration", top_level=False, request=request)
return render(request,
'dojo/edit_tool_type.html',
{
'tform': tform,
})
@user_passes_test(lambda u: u.is_staff)
def tool_type(request):
confs = Tool_Type.objects.all().order_by('name')
add_breadcrumb(title="Tool Type List", top_level=not len(request.GET), request=request)
return render(request,
'dojo/tool_type.html',
{'confs': confs,
})
<|fim▁end|> | if request.method == 'POST':
tform = ToolTypeForm(request.POST, instance=Tool_Type())
if tform.is_valid():
tform.save()
messages.add_message(request,
messages.SUCCESS,
'Tool Type Configuration Successfully Created.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('tool_type', ))
else:
tform = ToolTypeForm()
add_breadcrumb(title="New Tool Type Configuration", top_level=False, request=request)
return render(request, 'dojo/new_tool_type.html',
{'tform': tform}) |
<|file_name|>views.py<|end_file_name|><|fim▁begin|># # product
import logging
from django.contrib import messages
from django.contrib.auth.decorators import user_passes_test
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from dojo.utils import add_breadcrumb
from dojo.forms import ToolTypeForm
from dojo.models import Tool_Type
logger = logging.getLogger(__name__)
@user_passes_test(lambda u: u.is_staff)
def new_tool_type(request):
if request.method == 'POST':
tform = ToolTypeForm(request.POST, instance=Tool_Type())
if tform.is_valid():
tform.save()
messages.add_message(request,
messages.SUCCESS,
'Tool Type Configuration Successfully Created.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('tool_type', ))
else:
tform = ToolTypeForm()
add_breadcrumb(title="New Tool Type Configuration", top_level=False, request=request)
return render(request, 'dojo/new_tool_type.html',
{'tform': tform})
@user_passes_test(lambda u: u.is_staff)
def edit_tool_type(request, ttid):
<|fim_middle|>
@user_passes_test(lambda u: u.is_staff)
def tool_type(request):
confs = Tool_Type.objects.all().order_by('name')
add_breadcrumb(title="Tool Type List", top_level=not len(request.GET), request=request)
return render(request,
'dojo/tool_type.html',
{'confs': confs,
})
<|fim▁end|> | tool_type = Tool_Type.objects.get(pk=ttid)
if request.method == 'POST':
tform = ToolTypeForm(request.POST, instance=tool_type)
if tform.is_valid():
tform.save()
messages.add_message(request,
messages.SUCCESS,
'Tool Type Configuration Successfully Updated.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('tool_type', ))
else:
tform = ToolTypeForm(instance=tool_type)
add_breadcrumb(title="Edit Tool Type Configuration", top_level=False, request=request)
return render(request,
'dojo/edit_tool_type.html',
{
'tform': tform,
}) |
<|file_name|>views.py<|end_file_name|><|fim▁begin|># # product
import logging
from django.contrib import messages
from django.contrib.auth.decorators import user_passes_test
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from dojo.utils import add_breadcrumb
from dojo.forms import ToolTypeForm
from dojo.models import Tool_Type
logger = logging.getLogger(__name__)
@user_passes_test(lambda u: u.is_staff)
def new_tool_type(request):
if request.method == 'POST':
tform = ToolTypeForm(request.POST, instance=Tool_Type())
if tform.is_valid():
tform.save()
messages.add_message(request,
messages.SUCCESS,
'Tool Type Configuration Successfully Created.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('tool_type', ))
else:
tform = ToolTypeForm()
add_breadcrumb(title="New Tool Type Configuration", top_level=False, request=request)
return render(request, 'dojo/new_tool_type.html',
{'tform': tform})
@user_passes_test(lambda u: u.is_staff)
def edit_tool_type(request, ttid):
tool_type = Tool_Type.objects.get(pk=ttid)
if request.method == 'POST':
tform = ToolTypeForm(request.POST, instance=tool_type)
if tform.is_valid():
tform.save()
messages.add_message(request,
messages.SUCCESS,
'Tool Type Configuration Successfully Updated.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('tool_type', ))
else:
tform = ToolTypeForm(instance=tool_type)
add_breadcrumb(title="Edit Tool Type Configuration", top_level=False, request=request)
return render(request,
'dojo/edit_tool_type.html',
{
'tform': tform,
})
@user_passes_test(lambda u: u.is_staff)
def tool_type(request):
<|fim_middle|>
<|fim▁end|> | confs = Tool_Type.objects.all().order_by('name')
add_breadcrumb(title="Tool Type List", top_level=not len(request.GET), request=request)
return render(request,
'dojo/tool_type.html',
{'confs': confs,
}) |
<|file_name|>views.py<|end_file_name|><|fim▁begin|># # product
import logging
from django.contrib import messages
from django.contrib.auth.decorators import user_passes_test
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from dojo.utils import add_breadcrumb
from dojo.forms import ToolTypeForm
from dojo.models import Tool_Type
logger = logging.getLogger(__name__)
@user_passes_test(lambda u: u.is_staff)
def new_tool_type(request):
if request.method == 'POST':
<|fim_middle|>
else:
tform = ToolTypeForm()
add_breadcrumb(title="New Tool Type Configuration", top_level=False, request=request)
return render(request, 'dojo/new_tool_type.html',
{'tform': tform})
@user_passes_test(lambda u: u.is_staff)
def edit_tool_type(request, ttid):
tool_type = Tool_Type.objects.get(pk=ttid)
if request.method == 'POST':
tform = ToolTypeForm(request.POST, instance=tool_type)
if tform.is_valid():
tform.save()
messages.add_message(request,
messages.SUCCESS,
'Tool Type Configuration Successfully Updated.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('tool_type', ))
else:
tform = ToolTypeForm(instance=tool_type)
add_breadcrumb(title="Edit Tool Type Configuration", top_level=False, request=request)
return render(request,
'dojo/edit_tool_type.html',
{
'tform': tform,
})
@user_passes_test(lambda u: u.is_staff)
def tool_type(request):
confs = Tool_Type.objects.all().order_by('name')
add_breadcrumb(title="Tool Type List", top_level=not len(request.GET), request=request)
return render(request,
'dojo/tool_type.html',
{'confs': confs,
})
<|fim▁end|> | tform = ToolTypeForm(request.POST, instance=Tool_Type())
if tform.is_valid():
tform.save()
messages.add_message(request,
messages.SUCCESS,
'Tool Type Configuration Successfully Created.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('tool_type', )) |
<|file_name|>views.py<|end_file_name|><|fim▁begin|># # product
import logging
from django.contrib import messages
from django.contrib.auth.decorators import user_passes_test
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from dojo.utils import add_breadcrumb
from dojo.forms import ToolTypeForm
from dojo.models import Tool_Type
logger = logging.getLogger(__name__)
@user_passes_test(lambda u: u.is_staff)
def new_tool_type(request):
if request.method == 'POST':
tform = ToolTypeForm(request.POST, instance=Tool_Type())
if tform.is_valid():
<|fim_middle|>
else:
tform = ToolTypeForm()
add_breadcrumb(title="New Tool Type Configuration", top_level=False, request=request)
return render(request, 'dojo/new_tool_type.html',
{'tform': tform})
@user_passes_test(lambda u: u.is_staff)
def edit_tool_type(request, ttid):
tool_type = Tool_Type.objects.get(pk=ttid)
if request.method == 'POST':
tform = ToolTypeForm(request.POST, instance=tool_type)
if tform.is_valid():
tform.save()
messages.add_message(request,
messages.SUCCESS,
'Tool Type Configuration Successfully Updated.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('tool_type', ))
else:
tform = ToolTypeForm(instance=tool_type)
add_breadcrumb(title="Edit Tool Type Configuration", top_level=False, request=request)
return render(request,
'dojo/edit_tool_type.html',
{
'tform': tform,
})
@user_passes_test(lambda u: u.is_staff)
def tool_type(request):
confs = Tool_Type.objects.all().order_by('name')
add_breadcrumb(title="Tool Type List", top_level=not len(request.GET), request=request)
return render(request,
'dojo/tool_type.html',
{'confs': confs,
})
<|fim▁end|> | tform.save()
messages.add_message(request,
messages.SUCCESS,
'Tool Type Configuration Successfully Created.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('tool_type', )) |
<|file_name|>views.py<|end_file_name|><|fim▁begin|># # product
import logging
from django.contrib import messages
from django.contrib.auth.decorators import user_passes_test
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from dojo.utils import add_breadcrumb
from dojo.forms import ToolTypeForm
from dojo.models import Tool_Type
logger = logging.getLogger(__name__)
@user_passes_test(lambda u: u.is_staff)
def new_tool_type(request):
if request.method == 'POST':
tform = ToolTypeForm(request.POST, instance=Tool_Type())
if tform.is_valid():
tform.save()
messages.add_message(request,
messages.SUCCESS,
'Tool Type Configuration Successfully Created.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('tool_type', ))
else:
<|fim_middle|>
return render(request, 'dojo/new_tool_type.html',
{'tform': tform})
@user_passes_test(lambda u: u.is_staff)
def edit_tool_type(request, ttid):
tool_type = Tool_Type.objects.get(pk=ttid)
if request.method == 'POST':
tform = ToolTypeForm(request.POST, instance=tool_type)
if tform.is_valid():
tform.save()
messages.add_message(request,
messages.SUCCESS,
'Tool Type Configuration Successfully Updated.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('tool_type', ))
else:
tform = ToolTypeForm(instance=tool_type)
add_breadcrumb(title="Edit Tool Type Configuration", top_level=False, request=request)
return render(request,
'dojo/edit_tool_type.html',
{
'tform': tform,
})
@user_passes_test(lambda u: u.is_staff)
def tool_type(request):
confs = Tool_Type.objects.all().order_by('name')
add_breadcrumb(title="Tool Type List", top_level=not len(request.GET), request=request)
return render(request,
'dojo/tool_type.html',
{'confs': confs,
})
<|fim▁end|> | tform = ToolTypeForm()
add_breadcrumb(title="New Tool Type Configuration", top_level=False, request=request) |
<|file_name|>views.py<|end_file_name|><|fim▁begin|># # product
import logging
from django.contrib import messages
from django.contrib.auth.decorators import user_passes_test
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from dojo.utils import add_breadcrumb
from dojo.forms import ToolTypeForm
from dojo.models import Tool_Type
logger = logging.getLogger(__name__)
@user_passes_test(lambda u: u.is_staff)
def new_tool_type(request):
if request.method == 'POST':
tform = ToolTypeForm(request.POST, instance=Tool_Type())
if tform.is_valid():
tform.save()
messages.add_message(request,
messages.SUCCESS,
'Tool Type Configuration Successfully Created.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('tool_type', ))
else:
tform = ToolTypeForm()
add_breadcrumb(title="New Tool Type Configuration", top_level=False, request=request)
return render(request, 'dojo/new_tool_type.html',
{'tform': tform})
@user_passes_test(lambda u: u.is_staff)
def edit_tool_type(request, ttid):
tool_type = Tool_Type.objects.get(pk=ttid)
if request.method == 'POST':
<|fim_middle|>
else:
tform = ToolTypeForm(instance=tool_type)
add_breadcrumb(title="Edit Tool Type Configuration", top_level=False, request=request)
return render(request,
'dojo/edit_tool_type.html',
{
'tform': tform,
})
@user_passes_test(lambda u: u.is_staff)
def tool_type(request):
confs = Tool_Type.objects.all().order_by('name')
add_breadcrumb(title="Tool Type List", top_level=not len(request.GET), request=request)
return render(request,
'dojo/tool_type.html',
{'confs': confs,
})
<|fim▁end|> | tform = ToolTypeForm(request.POST, instance=tool_type)
if tform.is_valid():
tform.save()
messages.add_message(request,
messages.SUCCESS,
'Tool Type Configuration Successfully Updated.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('tool_type', )) |
<|file_name|>views.py<|end_file_name|><|fim▁begin|># # product
import logging
from django.contrib import messages
from django.contrib.auth.decorators import user_passes_test
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from dojo.utils import add_breadcrumb
from dojo.forms import ToolTypeForm
from dojo.models import Tool_Type
logger = logging.getLogger(__name__)
@user_passes_test(lambda u: u.is_staff)
def new_tool_type(request):
if request.method == 'POST':
tform = ToolTypeForm(request.POST, instance=Tool_Type())
if tform.is_valid():
tform.save()
messages.add_message(request,
messages.SUCCESS,
'Tool Type Configuration Successfully Created.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('tool_type', ))
else:
tform = ToolTypeForm()
add_breadcrumb(title="New Tool Type Configuration", top_level=False, request=request)
return render(request, 'dojo/new_tool_type.html',
{'tform': tform})
@user_passes_test(lambda u: u.is_staff)
def edit_tool_type(request, ttid):
tool_type = Tool_Type.objects.get(pk=ttid)
if request.method == 'POST':
tform = ToolTypeForm(request.POST, instance=tool_type)
if tform.is_valid():
<|fim_middle|>
else:
tform = ToolTypeForm(instance=tool_type)
add_breadcrumb(title="Edit Tool Type Configuration", top_level=False, request=request)
return render(request,
'dojo/edit_tool_type.html',
{
'tform': tform,
})
@user_passes_test(lambda u: u.is_staff)
def tool_type(request):
confs = Tool_Type.objects.all().order_by('name')
add_breadcrumb(title="Tool Type List", top_level=not len(request.GET), request=request)
return render(request,
'dojo/tool_type.html',
{'confs': confs,
})
<|fim▁end|> | tform.save()
messages.add_message(request,
messages.SUCCESS,
'Tool Type Configuration Successfully Updated.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('tool_type', )) |
<|file_name|>views.py<|end_file_name|><|fim▁begin|># # product
import logging
from django.contrib import messages
from django.contrib.auth.decorators import user_passes_test
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from dojo.utils import add_breadcrumb
from dojo.forms import ToolTypeForm
from dojo.models import Tool_Type
logger = logging.getLogger(__name__)
@user_passes_test(lambda u: u.is_staff)
def new_tool_type(request):
if request.method == 'POST':
tform = ToolTypeForm(request.POST, instance=Tool_Type())
if tform.is_valid():
tform.save()
messages.add_message(request,
messages.SUCCESS,
'Tool Type Configuration Successfully Created.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('tool_type', ))
else:
tform = ToolTypeForm()
add_breadcrumb(title="New Tool Type Configuration", top_level=False, request=request)
return render(request, 'dojo/new_tool_type.html',
{'tform': tform})
@user_passes_test(lambda u: u.is_staff)
def edit_tool_type(request, ttid):
tool_type = Tool_Type.objects.get(pk=ttid)
if request.method == 'POST':
tform = ToolTypeForm(request.POST, instance=tool_type)
if tform.is_valid():
tform.save()
messages.add_message(request,
messages.SUCCESS,
'Tool Type Configuration Successfully Updated.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('tool_type', ))
else:
<|fim_middle|>
add_breadcrumb(title="Edit Tool Type Configuration", top_level=False, request=request)
return render(request,
'dojo/edit_tool_type.html',
{
'tform': tform,
})
@user_passes_test(lambda u: u.is_staff)
def tool_type(request):
confs = Tool_Type.objects.all().order_by('name')
add_breadcrumb(title="Tool Type List", top_level=not len(request.GET), request=request)
return render(request,
'dojo/tool_type.html',
{'confs': confs,
})
<|fim▁end|> | tform = ToolTypeForm(instance=tool_type) |
<|file_name|>views.py<|end_file_name|><|fim▁begin|># # product
import logging
from django.contrib import messages
from django.contrib.auth.decorators import user_passes_test
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from dojo.utils import add_breadcrumb
from dojo.forms import ToolTypeForm
from dojo.models import Tool_Type
logger = logging.getLogger(__name__)
@user_passes_test(lambda u: u.is_staff)
def <|fim_middle|>(request):
if request.method == 'POST':
tform = ToolTypeForm(request.POST, instance=Tool_Type())
if tform.is_valid():
tform.save()
messages.add_message(request,
messages.SUCCESS,
'Tool Type Configuration Successfully Created.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('tool_type', ))
else:
tform = ToolTypeForm()
add_breadcrumb(title="New Tool Type Configuration", top_level=False, request=request)
return render(request, 'dojo/new_tool_type.html',
{'tform': tform})
@user_passes_test(lambda u: u.is_staff)
def edit_tool_type(request, ttid):
tool_type = Tool_Type.objects.get(pk=ttid)
if request.method == 'POST':
tform = ToolTypeForm(request.POST, instance=tool_type)
if tform.is_valid():
tform.save()
messages.add_message(request,
messages.SUCCESS,
'Tool Type Configuration Successfully Updated.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('tool_type', ))
else:
tform = ToolTypeForm(instance=tool_type)
add_breadcrumb(title="Edit Tool Type Configuration", top_level=False, request=request)
return render(request,
'dojo/edit_tool_type.html',
{
'tform': tform,
})
@user_passes_test(lambda u: u.is_staff)
def tool_type(request):
confs = Tool_Type.objects.all().order_by('name')
add_breadcrumb(title="Tool Type List", top_level=not len(request.GET), request=request)
return render(request,
'dojo/tool_type.html',
{'confs': confs,
})
<|fim▁end|> | new_tool_type |
<|file_name|>views.py<|end_file_name|><|fim▁begin|># # product
import logging
from django.contrib import messages
from django.contrib.auth.decorators import user_passes_test
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from dojo.utils import add_breadcrumb
from dojo.forms import ToolTypeForm
from dojo.models import Tool_Type
logger = logging.getLogger(__name__)
@user_passes_test(lambda u: u.is_staff)
def new_tool_type(request):
if request.method == 'POST':
tform = ToolTypeForm(request.POST, instance=Tool_Type())
if tform.is_valid():
tform.save()
messages.add_message(request,
messages.SUCCESS,
'Tool Type Configuration Successfully Created.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('tool_type', ))
else:
tform = ToolTypeForm()
add_breadcrumb(title="New Tool Type Configuration", top_level=False, request=request)
return render(request, 'dojo/new_tool_type.html',
{'tform': tform})
@user_passes_test(lambda u: u.is_staff)
def <|fim_middle|>(request, ttid):
tool_type = Tool_Type.objects.get(pk=ttid)
if request.method == 'POST':
tform = ToolTypeForm(request.POST, instance=tool_type)
if tform.is_valid():
tform.save()
messages.add_message(request,
messages.SUCCESS,
'Tool Type Configuration Successfully Updated.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('tool_type', ))
else:
tform = ToolTypeForm(instance=tool_type)
add_breadcrumb(title="Edit Tool Type Configuration", top_level=False, request=request)
return render(request,
'dojo/edit_tool_type.html',
{
'tform': tform,
})
@user_passes_test(lambda u: u.is_staff)
def tool_type(request):
confs = Tool_Type.objects.all().order_by('name')
add_breadcrumb(title="Tool Type List", top_level=not len(request.GET), request=request)
return render(request,
'dojo/tool_type.html',
{'confs': confs,
})
<|fim▁end|> | edit_tool_type |
<|file_name|>views.py<|end_file_name|><|fim▁begin|># # product
import logging
from django.contrib import messages
from django.contrib.auth.decorators import user_passes_test
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from dojo.utils import add_breadcrumb
from dojo.forms import ToolTypeForm
from dojo.models import Tool_Type
logger = logging.getLogger(__name__)
@user_passes_test(lambda u: u.is_staff)
def new_tool_type(request):
if request.method == 'POST':
tform = ToolTypeForm(request.POST, instance=Tool_Type())
if tform.is_valid():
tform.save()
messages.add_message(request,
messages.SUCCESS,
'Tool Type Configuration Successfully Created.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('tool_type', ))
else:
tform = ToolTypeForm()
add_breadcrumb(title="New Tool Type Configuration", top_level=False, request=request)
return render(request, 'dojo/new_tool_type.html',
{'tform': tform})
@user_passes_test(lambda u: u.is_staff)
def edit_tool_type(request, ttid):
tool_type = Tool_Type.objects.get(pk=ttid)
if request.method == 'POST':
tform = ToolTypeForm(request.POST, instance=tool_type)
if tform.is_valid():
tform.save()
messages.add_message(request,
messages.SUCCESS,
'Tool Type Configuration Successfully Updated.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('tool_type', ))
else:
tform = ToolTypeForm(instance=tool_type)
add_breadcrumb(title="Edit Tool Type Configuration", top_level=False, request=request)
return render(request,
'dojo/edit_tool_type.html',
{
'tform': tform,
})
@user_passes_test(lambda u: u.is_staff)
def <|fim_middle|>(request):
confs = Tool_Type.objects.all().order_by('name')
add_breadcrumb(title="Tool Type List", top_level=not len(request.GET), request=request)
return render(request,
'dojo/tool_type.html',
{'confs': confs,
})
<|fim▁end|> | tool_type |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# LICENSE
#
# Copyright (c) 2010-2017, GEM Foundation, G. Weatherill, M. Pagani,
# D. Monelli.
#
# The Hazard Modeller's Toolkit is free software: you can redistribute
# it and/or modify it under the terms of the GNU Affero General Public
#License as published by the Free Software Foundation, either version
#3 of the License, or (at your option) any later version.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>
#
#DISCLAIMER
#
# The software Hazard Modeller's Toolkit (openquake.hmtk) provided herein<|fim▁hole|># It is distributed for the purpose of open collaboration and in the
# hope that it will be useful to the scientific, engineering, disaster
# risk and software design communities.
#
# The software is NOT distributed as part of GEM's OpenQuake suite
# (http://www.globalquakemodel.org/openquake) and must be considered as a
# separate entity. The software provided herein is designed and implemented
# by scientific staff. It is not developed to the design standards, nor
# subject to same level of critical review by professional software
# developers, as GEM's OpenQuake software suite.
#
# Feedback and contribution to the software is welcome, and can be
# directed to the hazard scientific staff of the GEM Model Facility
# ([email protected]).
#
# The Hazard Modeller's Toolkit (openquake.hmtk) is therefore distributed 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.
#
# The GEM Foundation, and the authors of the software, assume no
# liability for use of the software.<|fim▁end|> | #is released as a prototype implementation on behalf of
# scientists and engineers working within the GEM Foundation (Global
#Earthquake Model).
# |
<|file_name|>setAwayMessageEvent.py<|end_file_name|><|fim▁begin|>from common.log import logUtils as log
from constants import clientPackets
from constants import serverPackets
def handle(userToken, packetData):
# get token data
username = userToken.username
# Read packet data
packetData = clientPackets.setAwayMessage(packetData)
# Set token away message
userToken.awayMessage = packetData["awayMessage"]
# Send private message from fokabot
if packetData["awayMessage"] == "":
fokaMessage = "Your away message has been reset"
else:<|fim▁hole|><|fim▁end|> | fokaMessage = "Your away message is now: {}".format(packetData["awayMessage"])
userToken.enqueue(serverPackets.sendMessage("FokaBot", username, fokaMessage))
log.info("{} has changed their away message to: {}".format(username, packetData["awayMessage"])) |
<|file_name|>setAwayMessageEvent.py<|end_file_name|><|fim▁begin|>from common.log import logUtils as log
from constants import clientPackets
from constants import serverPackets
def handle(userToken, packetData):
# get token data
<|fim_middle|>
<|fim▁end|> | username = userToken.username
# Read packet data
packetData = clientPackets.setAwayMessage(packetData)
# Set token away message
userToken.awayMessage = packetData["awayMessage"]
# Send private message from fokabot
if packetData["awayMessage"] == "":
fokaMessage = "Your away message has been reset"
else:
fokaMessage = "Your away message is now: {}".format(packetData["awayMessage"])
userToken.enqueue(serverPackets.sendMessage("FokaBot", username, fokaMessage))
log.info("{} has changed their away message to: {}".format(username, packetData["awayMessage"])) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.