prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>user_defined.py<|end_file_name|><|fim▁begin|># Author: Prabhu Ramachandran <prabhu [at] aero . iitb . ac . in>
# Copyright (c) 2008, Enthought, Inc.
# License: BSD Style.
# Enthought library imports.
from tvtk.tools.tvtk_doc import TVTKFilterChooser, TVTK_FILTERS
# Local imports.
from mayavi.filters.filter_base import FilterBase
from mayavi.core.common import handle_children_state, error
from mayavi.core.pipeline_info import PipelineInfo
################################################################################
# `UserDefined` class.
################################################################################
class UserDefined(FilterBase):
"""
This filter lets the user define their own filter
dynamically/interactively. It is like `FilterBase` but allows a
user to specify the class without writing any code.
"""
# The version of this class. Used for persistence.
__version__ = 0
input_info = PipelineInfo(datasets=['any'],
attribute_types=['any'],
attributes=['any'])
output_info = PipelineInfo(datasets=['any'],
attribute_types=['any'],
attributes=['any'])
######################################################################
# `object` interface.
######################################################################
def __set_pure_state__(self, state):
# Create and set the filter.
children = [f for f in [self.filter] if f is not None]
handle_children_state(children, [state.filter])
self.filter = children[0]
self.update_pipeline()
# Restore our state.
super(UserDefined, self).__set_pure_state__(state)
######################################################################
# `UserDefined` interface.
######################################################################
def <|fim_middle|>(self):
"""Setup the filter if none has been set or check it if it
already has been."""
obj = self.filter
if not self._check_object(obj):
if obj is not None:
cname = obj.__class__.__name__
error('Invalid filter %s chosen! Try again!'%cname)
obj = self._choose_filter()
self.filter = obj
######################################################################
# Non-public interface.
######################################################################
def _choose_filter(self):
chooser = TVTKFilterChooser()
chooser.edit_traits(kind='livemodal')
obj = chooser.object
if obj is None:
error('Invalid filter chosen! Try again!')
return obj
def _check_object(self, obj):
if obj is None:
return False
if obj.__class__.__name__ in TVTK_FILTERS:
return True
return False
def _filter_changed(self, old, new):
self.name = 'UserDefined:%s'%new.__class__.__name__
super(UserDefined, self)._filter_changed(old, new)
<|fim▁end|> | setup_filter |
<|file_name|>user_defined.py<|end_file_name|><|fim▁begin|># Author: Prabhu Ramachandran <prabhu [at] aero . iitb . ac . in>
# Copyright (c) 2008, Enthought, Inc.
# License: BSD Style.
# Enthought library imports.
from tvtk.tools.tvtk_doc import TVTKFilterChooser, TVTK_FILTERS
# Local imports.
from mayavi.filters.filter_base import FilterBase
from mayavi.core.common import handle_children_state, error
from mayavi.core.pipeline_info import PipelineInfo
################################################################################
# `UserDefined` class.
################################################################################
class UserDefined(FilterBase):
"""
This filter lets the user define their own filter
dynamically/interactively. It is like `FilterBase` but allows a
user to specify the class without writing any code.
"""
# The version of this class. Used for persistence.
__version__ = 0
input_info = PipelineInfo(datasets=['any'],
attribute_types=['any'],
attributes=['any'])
output_info = PipelineInfo(datasets=['any'],
attribute_types=['any'],
attributes=['any'])
######################################################################
# `object` interface.
######################################################################
def __set_pure_state__(self, state):
# Create and set the filter.
children = [f for f in [self.filter] if f is not None]
handle_children_state(children, [state.filter])
self.filter = children[0]
self.update_pipeline()
# Restore our state.
super(UserDefined, self).__set_pure_state__(state)
######################################################################
# `UserDefined` interface.
######################################################################
def setup_filter(self):
"""Setup the filter if none has been set or check it if it
already has been."""
obj = self.filter
if not self._check_object(obj):
if obj is not None:
cname = obj.__class__.__name__
error('Invalid filter %s chosen! Try again!'%cname)
obj = self._choose_filter()
self.filter = obj
######################################################################
# Non-public interface.
######################################################################
def <|fim_middle|>(self):
chooser = TVTKFilterChooser()
chooser.edit_traits(kind='livemodal')
obj = chooser.object
if obj is None:
error('Invalid filter chosen! Try again!')
return obj
def _check_object(self, obj):
if obj is None:
return False
if obj.__class__.__name__ in TVTK_FILTERS:
return True
return False
def _filter_changed(self, old, new):
self.name = 'UserDefined:%s'%new.__class__.__name__
super(UserDefined, self)._filter_changed(old, new)
<|fim▁end|> | _choose_filter |
<|file_name|>user_defined.py<|end_file_name|><|fim▁begin|># Author: Prabhu Ramachandran <prabhu [at] aero . iitb . ac . in>
# Copyright (c) 2008, Enthought, Inc.
# License: BSD Style.
# Enthought library imports.
from tvtk.tools.tvtk_doc import TVTKFilterChooser, TVTK_FILTERS
# Local imports.
from mayavi.filters.filter_base import FilterBase
from mayavi.core.common import handle_children_state, error
from mayavi.core.pipeline_info import PipelineInfo
################################################################################
# `UserDefined` class.
################################################################################
class UserDefined(FilterBase):
"""
This filter lets the user define their own filter
dynamically/interactively. It is like `FilterBase` but allows a
user to specify the class without writing any code.
"""
# The version of this class. Used for persistence.
__version__ = 0
input_info = PipelineInfo(datasets=['any'],
attribute_types=['any'],
attributes=['any'])
output_info = PipelineInfo(datasets=['any'],
attribute_types=['any'],
attributes=['any'])
######################################################################
# `object` interface.
######################################################################
def __set_pure_state__(self, state):
# Create and set the filter.
children = [f for f in [self.filter] if f is not None]
handle_children_state(children, [state.filter])
self.filter = children[0]
self.update_pipeline()
# Restore our state.
super(UserDefined, self).__set_pure_state__(state)
######################################################################
# `UserDefined` interface.
######################################################################
def setup_filter(self):
"""Setup the filter if none has been set or check it if it
already has been."""
obj = self.filter
if not self._check_object(obj):
if obj is not None:
cname = obj.__class__.__name__
error('Invalid filter %s chosen! Try again!'%cname)
obj = self._choose_filter()
self.filter = obj
######################################################################
# Non-public interface.
######################################################################
def _choose_filter(self):
chooser = TVTKFilterChooser()
chooser.edit_traits(kind='livemodal')
obj = chooser.object
if obj is None:
error('Invalid filter chosen! Try again!')
return obj
def <|fim_middle|>(self, obj):
if obj is None:
return False
if obj.__class__.__name__ in TVTK_FILTERS:
return True
return False
def _filter_changed(self, old, new):
self.name = 'UserDefined:%s'%new.__class__.__name__
super(UserDefined, self)._filter_changed(old, new)
<|fim▁end|> | _check_object |
<|file_name|>user_defined.py<|end_file_name|><|fim▁begin|># Author: Prabhu Ramachandran <prabhu [at] aero . iitb . ac . in>
# Copyright (c) 2008, Enthought, Inc.
# License: BSD Style.
# Enthought library imports.
from tvtk.tools.tvtk_doc import TVTKFilterChooser, TVTK_FILTERS
# Local imports.
from mayavi.filters.filter_base import FilterBase
from mayavi.core.common import handle_children_state, error
from mayavi.core.pipeline_info import PipelineInfo
################################################################################
# `UserDefined` class.
################################################################################
class UserDefined(FilterBase):
"""
This filter lets the user define their own filter
dynamically/interactively. It is like `FilterBase` but allows a
user to specify the class without writing any code.
"""
# The version of this class. Used for persistence.
__version__ = 0
input_info = PipelineInfo(datasets=['any'],
attribute_types=['any'],
attributes=['any'])
output_info = PipelineInfo(datasets=['any'],
attribute_types=['any'],
attributes=['any'])
######################################################################
# `object` interface.
######################################################################
def __set_pure_state__(self, state):
# Create and set the filter.
children = [f for f in [self.filter] if f is not None]
handle_children_state(children, [state.filter])
self.filter = children[0]
self.update_pipeline()
# Restore our state.
super(UserDefined, self).__set_pure_state__(state)
######################################################################
# `UserDefined` interface.
######################################################################
def setup_filter(self):
"""Setup the filter if none has been set or check it if it
already has been."""
obj = self.filter
if not self._check_object(obj):
if obj is not None:
cname = obj.__class__.__name__
error('Invalid filter %s chosen! Try again!'%cname)
obj = self._choose_filter()
self.filter = obj
######################################################################
# Non-public interface.
######################################################################
def _choose_filter(self):
chooser = TVTKFilterChooser()
chooser.edit_traits(kind='livemodal')
obj = chooser.object
if obj is None:
error('Invalid filter chosen! Try again!')
return obj
def _check_object(self, obj):
if obj is None:
return False
if obj.__class__.__name__ in TVTK_FILTERS:
return True
return False
def <|fim_middle|>(self, old, new):
self.name = 'UserDefined:%s'%new.__class__.__name__
super(UserDefined, self)._filter_changed(old, new)
<|fim▁end|> | _filter_changed |
<|file_name|>SchedulingComponent.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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.
from ThreadedComponent import threadedcomponent, threadedadaptivecommscomponent
import heapq
import time
class SchedulingComponentMixin(object):
"""
SchedulingComponent() -> new SchedulingComponent
Base class for a threadedcomponent with an inbuilt scheduler, allowing a
component to block until a scheduled event is ready or a message is received
on an inbox.
"""
Inboxes = {"inbox" : "Standard inbox for receiving data from other components",
"control" : "Standard inbox for receiving control messages from other components",
"event" : "Scheduled events which are ready to be processed"}
def __init__(self, **argd):
super(SchedulingComponentMixin, self).__init__(**argd)
self.eventQueue = []
def scheduleRel(self, message, delay, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after a delay.
"""
return self.scheduleAbs(message, time.time() + delay, priority)
def scheduleAbs(self, message, eventTime, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after at a specified time.
"""
event = eventTime, priority, message
heapq.heappush(self.eventQueue, event)
return event
def cancelEvent(self, event):
""" Remove a scheduled event from the scheduler """
self.eventQueue.remove(event)
heapq.heapify(self.eventQueue)
def eventReady(self):
""" Returns true if there is an event ready to be processed """
if self.eventQueue:
eventTime = self.eventQueue[0][0]
if time.time() >= eventTime:
return True
return False
def pause(self):
"""
Sleep until there is either an event ready or a message is received on
an inbox
"""
if self.eventReady():
self.signalEvent()
else:
if self.eventQueue:
eventTime = self.eventQueue[0][0]
super(SchedulingComponentMixin, self).pause(eventTime - time.time())
if self.eventReady():
self.signalEvent()
else:<|fim▁hole|>
def signalEvent(self):
"""
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.heappop(self.eventQueue)
#print "Signalling, late by:", (time.time() - eventTime)
if not self.inqueues["event"].full():
self.inqueues["event"].put(message)
class SchedulingComponent(SchedulingComponentMixin, threadedcomponent):
def __init__(self, **argd):
super(SchedulingComponent, self).__init__(**argd)
class SchedulingAdaptiveCommsComponent(SchedulingComponentMixin,
threadedadaptivecommscomponent):
def __init__(self, **argd):
super(SchedulingAdaptiveCommsComponent, self).__init__(**argd)<|fim▁end|> | super(SchedulingComponentMixin, self).pause() |
<|file_name|>SchedulingComponent.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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.
from ThreadedComponent import threadedcomponent, threadedadaptivecommscomponent
import heapq
import time
class SchedulingComponentMixin(object):
<|fim_middle|>
class SchedulingComponent(SchedulingComponentMixin, threadedcomponent):
def __init__(self, **argd):
super(SchedulingComponent, self).__init__(**argd)
class SchedulingAdaptiveCommsComponent(SchedulingComponentMixin,
threadedadaptivecommscomponent):
def __init__(self, **argd):
super(SchedulingAdaptiveCommsComponent, self).__init__(**argd)
<|fim▁end|> | """
SchedulingComponent() -> new SchedulingComponent
Base class for a threadedcomponent with an inbuilt scheduler, allowing a
component to block until a scheduled event is ready or a message is received
on an inbox.
"""
Inboxes = {"inbox" : "Standard inbox for receiving data from other components",
"control" : "Standard inbox for receiving control messages from other components",
"event" : "Scheduled events which are ready to be processed"}
def __init__(self, **argd):
super(SchedulingComponentMixin, self).__init__(**argd)
self.eventQueue = []
def scheduleRel(self, message, delay, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after a delay.
"""
return self.scheduleAbs(message, time.time() + delay, priority)
def scheduleAbs(self, message, eventTime, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after at a specified time.
"""
event = eventTime, priority, message
heapq.heappush(self.eventQueue, event)
return event
def cancelEvent(self, event):
""" Remove a scheduled event from the scheduler """
self.eventQueue.remove(event)
heapq.heapify(self.eventQueue)
def eventReady(self):
""" Returns true if there is an event ready to be processed """
if self.eventQueue:
eventTime = self.eventQueue[0][0]
if time.time() >= eventTime:
return True
return False
def pause(self):
"""
Sleep until there is either an event ready or a message is received on
an inbox
"""
if self.eventReady():
self.signalEvent()
else:
if self.eventQueue:
eventTime = self.eventQueue[0][0]
super(SchedulingComponentMixin, self).pause(eventTime - time.time())
if self.eventReady():
self.signalEvent()
else:
super(SchedulingComponentMixin, self).pause()
def signalEvent(self):
"""
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.heappop(self.eventQueue)
#print "Signalling, late by:", (time.time() - eventTime)
if not self.inqueues["event"].full():
self.inqueues["event"].put(message) |
<|file_name|>SchedulingComponent.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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.
from ThreadedComponent import threadedcomponent, threadedadaptivecommscomponent
import heapq
import time
class SchedulingComponentMixin(object):
"""
SchedulingComponent() -> new SchedulingComponent
Base class for a threadedcomponent with an inbuilt scheduler, allowing a
component to block until a scheduled event is ready or a message is received
on an inbox.
"""
Inboxes = {"inbox" : "Standard inbox for receiving data from other components",
"control" : "Standard inbox for receiving control messages from other components",
"event" : "Scheduled events which are ready to be processed"}
def __init__(self, **argd):
<|fim_middle|>
def scheduleRel(self, message, delay, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after a delay.
"""
return self.scheduleAbs(message, time.time() + delay, priority)
def scheduleAbs(self, message, eventTime, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after at a specified time.
"""
event = eventTime, priority, message
heapq.heappush(self.eventQueue, event)
return event
def cancelEvent(self, event):
""" Remove a scheduled event from the scheduler """
self.eventQueue.remove(event)
heapq.heapify(self.eventQueue)
def eventReady(self):
""" Returns true if there is an event ready to be processed """
if self.eventQueue:
eventTime = self.eventQueue[0][0]
if time.time() >= eventTime:
return True
return False
def pause(self):
"""
Sleep until there is either an event ready or a message is received on
an inbox
"""
if self.eventReady():
self.signalEvent()
else:
if self.eventQueue:
eventTime = self.eventQueue[0][0]
super(SchedulingComponentMixin, self).pause(eventTime - time.time())
if self.eventReady():
self.signalEvent()
else:
super(SchedulingComponentMixin, self).pause()
def signalEvent(self):
"""
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.heappop(self.eventQueue)
#print "Signalling, late by:", (time.time() - eventTime)
if not self.inqueues["event"].full():
self.inqueues["event"].put(message)
class SchedulingComponent(SchedulingComponentMixin, threadedcomponent):
def __init__(self, **argd):
super(SchedulingComponent, self).__init__(**argd)
class SchedulingAdaptiveCommsComponent(SchedulingComponentMixin,
threadedadaptivecommscomponent):
def __init__(self, **argd):
super(SchedulingAdaptiveCommsComponent, self).__init__(**argd)
<|fim▁end|> | super(SchedulingComponentMixin, self).__init__(**argd)
self.eventQueue = [] |
<|file_name|>SchedulingComponent.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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.
from ThreadedComponent import threadedcomponent, threadedadaptivecommscomponent
import heapq
import time
class SchedulingComponentMixin(object):
"""
SchedulingComponent() -> new SchedulingComponent
Base class for a threadedcomponent with an inbuilt scheduler, allowing a
component to block until a scheduled event is ready or a message is received
on an inbox.
"""
Inboxes = {"inbox" : "Standard inbox for receiving data from other components",
"control" : "Standard inbox for receiving control messages from other components",
"event" : "Scheduled events which are ready to be processed"}
def __init__(self, **argd):
super(SchedulingComponentMixin, self).__init__(**argd)
self.eventQueue = []
def scheduleRel(self, message, delay, priority=1):
<|fim_middle|>
def scheduleAbs(self, message, eventTime, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after at a specified time.
"""
event = eventTime, priority, message
heapq.heappush(self.eventQueue, event)
return event
def cancelEvent(self, event):
""" Remove a scheduled event from the scheduler """
self.eventQueue.remove(event)
heapq.heapify(self.eventQueue)
def eventReady(self):
""" Returns true if there is an event ready to be processed """
if self.eventQueue:
eventTime = self.eventQueue[0][0]
if time.time() >= eventTime:
return True
return False
def pause(self):
"""
Sleep until there is either an event ready or a message is received on
an inbox
"""
if self.eventReady():
self.signalEvent()
else:
if self.eventQueue:
eventTime = self.eventQueue[0][0]
super(SchedulingComponentMixin, self).pause(eventTime - time.time())
if self.eventReady():
self.signalEvent()
else:
super(SchedulingComponentMixin, self).pause()
def signalEvent(self):
"""
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.heappop(self.eventQueue)
#print "Signalling, late by:", (time.time() - eventTime)
if not self.inqueues["event"].full():
self.inqueues["event"].put(message)
class SchedulingComponent(SchedulingComponentMixin, threadedcomponent):
def __init__(self, **argd):
super(SchedulingComponent, self).__init__(**argd)
class SchedulingAdaptiveCommsComponent(SchedulingComponentMixin,
threadedadaptivecommscomponent):
def __init__(self, **argd):
super(SchedulingAdaptiveCommsComponent, self).__init__(**argd)
<|fim▁end|> | """
Schedule an event to wake the component and send a message to the
"event" inbox after a delay.
"""
return self.scheduleAbs(message, time.time() + delay, priority) |
<|file_name|>SchedulingComponent.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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.
from ThreadedComponent import threadedcomponent, threadedadaptivecommscomponent
import heapq
import time
class SchedulingComponentMixin(object):
"""
SchedulingComponent() -> new SchedulingComponent
Base class for a threadedcomponent with an inbuilt scheduler, allowing a
component to block until a scheduled event is ready or a message is received
on an inbox.
"""
Inboxes = {"inbox" : "Standard inbox for receiving data from other components",
"control" : "Standard inbox for receiving control messages from other components",
"event" : "Scheduled events which are ready to be processed"}
def __init__(self, **argd):
super(SchedulingComponentMixin, self).__init__(**argd)
self.eventQueue = []
def scheduleRel(self, message, delay, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after a delay.
"""
return self.scheduleAbs(message, time.time() + delay, priority)
def scheduleAbs(self, message, eventTime, priority=1):
<|fim_middle|>
def cancelEvent(self, event):
""" Remove a scheduled event from the scheduler """
self.eventQueue.remove(event)
heapq.heapify(self.eventQueue)
def eventReady(self):
""" Returns true if there is an event ready to be processed """
if self.eventQueue:
eventTime = self.eventQueue[0][0]
if time.time() >= eventTime:
return True
return False
def pause(self):
"""
Sleep until there is either an event ready or a message is received on
an inbox
"""
if self.eventReady():
self.signalEvent()
else:
if self.eventQueue:
eventTime = self.eventQueue[0][0]
super(SchedulingComponentMixin, self).pause(eventTime - time.time())
if self.eventReady():
self.signalEvent()
else:
super(SchedulingComponentMixin, self).pause()
def signalEvent(self):
"""
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.heappop(self.eventQueue)
#print "Signalling, late by:", (time.time() - eventTime)
if not self.inqueues["event"].full():
self.inqueues["event"].put(message)
class SchedulingComponent(SchedulingComponentMixin, threadedcomponent):
def __init__(self, **argd):
super(SchedulingComponent, self).__init__(**argd)
class SchedulingAdaptiveCommsComponent(SchedulingComponentMixin,
threadedadaptivecommscomponent):
def __init__(self, **argd):
super(SchedulingAdaptiveCommsComponent, self).__init__(**argd)
<|fim▁end|> | """
Schedule an event to wake the component and send a message to the
"event" inbox after at a specified time.
"""
event = eventTime, priority, message
heapq.heappush(self.eventQueue, event)
return event |
<|file_name|>SchedulingComponent.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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.
from ThreadedComponent import threadedcomponent, threadedadaptivecommscomponent
import heapq
import time
class SchedulingComponentMixin(object):
"""
SchedulingComponent() -> new SchedulingComponent
Base class for a threadedcomponent with an inbuilt scheduler, allowing a
component to block until a scheduled event is ready or a message is received
on an inbox.
"""
Inboxes = {"inbox" : "Standard inbox for receiving data from other components",
"control" : "Standard inbox for receiving control messages from other components",
"event" : "Scheduled events which are ready to be processed"}
def __init__(self, **argd):
super(SchedulingComponentMixin, self).__init__(**argd)
self.eventQueue = []
def scheduleRel(self, message, delay, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after a delay.
"""
return self.scheduleAbs(message, time.time() + delay, priority)
def scheduleAbs(self, message, eventTime, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after at a specified time.
"""
event = eventTime, priority, message
heapq.heappush(self.eventQueue, event)
return event
def cancelEvent(self, event):
<|fim_middle|>
def eventReady(self):
""" Returns true if there is an event ready to be processed """
if self.eventQueue:
eventTime = self.eventQueue[0][0]
if time.time() >= eventTime:
return True
return False
def pause(self):
"""
Sleep until there is either an event ready or a message is received on
an inbox
"""
if self.eventReady():
self.signalEvent()
else:
if self.eventQueue:
eventTime = self.eventQueue[0][0]
super(SchedulingComponentMixin, self).pause(eventTime - time.time())
if self.eventReady():
self.signalEvent()
else:
super(SchedulingComponentMixin, self).pause()
def signalEvent(self):
"""
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.heappop(self.eventQueue)
#print "Signalling, late by:", (time.time() - eventTime)
if not self.inqueues["event"].full():
self.inqueues["event"].put(message)
class SchedulingComponent(SchedulingComponentMixin, threadedcomponent):
def __init__(self, **argd):
super(SchedulingComponent, self).__init__(**argd)
class SchedulingAdaptiveCommsComponent(SchedulingComponentMixin,
threadedadaptivecommscomponent):
def __init__(self, **argd):
super(SchedulingAdaptiveCommsComponent, self).__init__(**argd)
<|fim▁end|> | """ Remove a scheduled event from the scheduler """
self.eventQueue.remove(event)
heapq.heapify(self.eventQueue) |
<|file_name|>SchedulingComponent.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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.
from ThreadedComponent import threadedcomponent, threadedadaptivecommscomponent
import heapq
import time
class SchedulingComponentMixin(object):
"""
SchedulingComponent() -> new SchedulingComponent
Base class for a threadedcomponent with an inbuilt scheduler, allowing a
component to block until a scheduled event is ready or a message is received
on an inbox.
"""
Inboxes = {"inbox" : "Standard inbox for receiving data from other components",
"control" : "Standard inbox for receiving control messages from other components",
"event" : "Scheduled events which are ready to be processed"}
def __init__(self, **argd):
super(SchedulingComponentMixin, self).__init__(**argd)
self.eventQueue = []
def scheduleRel(self, message, delay, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after a delay.
"""
return self.scheduleAbs(message, time.time() + delay, priority)
def scheduleAbs(self, message, eventTime, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after at a specified time.
"""
event = eventTime, priority, message
heapq.heappush(self.eventQueue, event)
return event
def cancelEvent(self, event):
""" Remove a scheduled event from the scheduler """
self.eventQueue.remove(event)
heapq.heapify(self.eventQueue)
def eventReady(self):
<|fim_middle|>
def pause(self):
"""
Sleep until there is either an event ready or a message is received on
an inbox
"""
if self.eventReady():
self.signalEvent()
else:
if self.eventQueue:
eventTime = self.eventQueue[0][0]
super(SchedulingComponentMixin, self).pause(eventTime - time.time())
if self.eventReady():
self.signalEvent()
else:
super(SchedulingComponentMixin, self).pause()
def signalEvent(self):
"""
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.heappop(self.eventQueue)
#print "Signalling, late by:", (time.time() - eventTime)
if not self.inqueues["event"].full():
self.inqueues["event"].put(message)
class SchedulingComponent(SchedulingComponentMixin, threadedcomponent):
def __init__(self, **argd):
super(SchedulingComponent, self).__init__(**argd)
class SchedulingAdaptiveCommsComponent(SchedulingComponentMixin,
threadedadaptivecommscomponent):
def __init__(self, **argd):
super(SchedulingAdaptiveCommsComponent, self).__init__(**argd)
<|fim▁end|> | """ Returns true if there is an event ready to be processed """
if self.eventQueue:
eventTime = self.eventQueue[0][0]
if time.time() >= eventTime:
return True
return False |
<|file_name|>SchedulingComponent.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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.
from ThreadedComponent import threadedcomponent, threadedadaptivecommscomponent
import heapq
import time
class SchedulingComponentMixin(object):
"""
SchedulingComponent() -> new SchedulingComponent
Base class for a threadedcomponent with an inbuilt scheduler, allowing a
component to block until a scheduled event is ready or a message is received
on an inbox.
"""
Inboxes = {"inbox" : "Standard inbox for receiving data from other components",
"control" : "Standard inbox for receiving control messages from other components",
"event" : "Scheduled events which are ready to be processed"}
def __init__(self, **argd):
super(SchedulingComponentMixin, self).__init__(**argd)
self.eventQueue = []
def scheduleRel(self, message, delay, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after a delay.
"""
return self.scheduleAbs(message, time.time() + delay, priority)
def scheduleAbs(self, message, eventTime, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after at a specified time.
"""
event = eventTime, priority, message
heapq.heappush(self.eventQueue, event)
return event
def cancelEvent(self, event):
""" Remove a scheduled event from the scheduler """
self.eventQueue.remove(event)
heapq.heapify(self.eventQueue)
def eventReady(self):
""" Returns true if there is an event ready to be processed """
if self.eventQueue:
eventTime = self.eventQueue[0][0]
if time.time() >= eventTime:
return True
return False
def pause(self):
<|fim_middle|>
def signalEvent(self):
"""
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.heappop(self.eventQueue)
#print "Signalling, late by:", (time.time() - eventTime)
if not self.inqueues["event"].full():
self.inqueues["event"].put(message)
class SchedulingComponent(SchedulingComponentMixin, threadedcomponent):
def __init__(self, **argd):
super(SchedulingComponent, self).__init__(**argd)
class SchedulingAdaptiveCommsComponent(SchedulingComponentMixin,
threadedadaptivecommscomponent):
def __init__(self, **argd):
super(SchedulingAdaptiveCommsComponent, self).__init__(**argd)
<|fim▁end|> | """
Sleep until there is either an event ready or a message is received on
an inbox
"""
if self.eventReady():
self.signalEvent()
else:
if self.eventQueue:
eventTime = self.eventQueue[0][0]
super(SchedulingComponentMixin, self).pause(eventTime - time.time())
if self.eventReady():
self.signalEvent()
else:
super(SchedulingComponentMixin, self).pause() |
<|file_name|>SchedulingComponent.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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.
from ThreadedComponent import threadedcomponent, threadedadaptivecommscomponent
import heapq
import time
class SchedulingComponentMixin(object):
"""
SchedulingComponent() -> new SchedulingComponent
Base class for a threadedcomponent with an inbuilt scheduler, allowing a
component to block until a scheduled event is ready or a message is received
on an inbox.
"""
Inboxes = {"inbox" : "Standard inbox for receiving data from other components",
"control" : "Standard inbox for receiving control messages from other components",
"event" : "Scheduled events which are ready to be processed"}
def __init__(self, **argd):
super(SchedulingComponentMixin, self).__init__(**argd)
self.eventQueue = []
def scheduleRel(self, message, delay, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after a delay.
"""
return self.scheduleAbs(message, time.time() + delay, priority)
def scheduleAbs(self, message, eventTime, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after at a specified time.
"""
event = eventTime, priority, message
heapq.heappush(self.eventQueue, event)
return event
def cancelEvent(self, event):
""" Remove a scheduled event from the scheduler """
self.eventQueue.remove(event)
heapq.heapify(self.eventQueue)
def eventReady(self):
""" Returns true if there is an event ready to be processed """
if self.eventQueue:
eventTime = self.eventQueue[0][0]
if time.time() >= eventTime:
return True
return False
def pause(self):
"""
Sleep until there is either an event ready or a message is received on
an inbox
"""
if self.eventReady():
self.signalEvent()
else:
if self.eventQueue:
eventTime = self.eventQueue[0][0]
super(SchedulingComponentMixin, self).pause(eventTime - time.time())
if self.eventReady():
self.signalEvent()
else:
super(SchedulingComponentMixin, self).pause()
def signalEvent(self):
<|fim_middle|>
class SchedulingComponent(SchedulingComponentMixin, threadedcomponent):
def __init__(self, **argd):
super(SchedulingComponent, self).__init__(**argd)
class SchedulingAdaptiveCommsComponent(SchedulingComponentMixin,
threadedadaptivecommscomponent):
def __init__(self, **argd):
super(SchedulingAdaptiveCommsComponent, self).__init__(**argd)
<|fim▁end|> | """
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.heappop(self.eventQueue)
#print "Signalling, late by:", (time.time() - eventTime)
if not self.inqueues["event"].full():
self.inqueues["event"].put(message) |
<|file_name|>SchedulingComponent.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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.
from ThreadedComponent import threadedcomponent, threadedadaptivecommscomponent
import heapq
import time
class SchedulingComponentMixin(object):
"""
SchedulingComponent() -> new SchedulingComponent
Base class for a threadedcomponent with an inbuilt scheduler, allowing a
component to block until a scheduled event is ready or a message is received
on an inbox.
"""
Inboxes = {"inbox" : "Standard inbox for receiving data from other components",
"control" : "Standard inbox for receiving control messages from other components",
"event" : "Scheduled events which are ready to be processed"}
def __init__(self, **argd):
super(SchedulingComponentMixin, self).__init__(**argd)
self.eventQueue = []
def scheduleRel(self, message, delay, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after a delay.
"""
return self.scheduleAbs(message, time.time() + delay, priority)
def scheduleAbs(self, message, eventTime, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after at a specified time.
"""
event = eventTime, priority, message
heapq.heappush(self.eventQueue, event)
return event
def cancelEvent(self, event):
""" Remove a scheduled event from the scheduler """
self.eventQueue.remove(event)
heapq.heapify(self.eventQueue)
def eventReady(self):
""" Returns true if there is an event ready to be processed """
if self.eventQueue:
eventTime = self.eventQueue[0][0]
if time.time() >= eventTime:
return True
return False
def pause(self):
"""
Sleep until there is either an event ready or a message is received on
an inbox
"""
if self.eventReady():
self.signalEvent()
else:
if self.eventQueue:
eventTime = self.eventQueue[0][0]
super(SchedulingComponentMixin, self).pause(eventTime - time.time())
if self.eventReady():
self.signalEvent()
else:
super(SchedulingComponentMixin, self).pause()
def signalEvent(self):
"""
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.heappop(self.eventQueue)
#print "Signalling, late by:", (time.time() - eventTime)
if not self.inqueues["event"].full():
self.inqueues["event"].put(message)
class SchedulingComponent(SchedulingComponentMixin, threadedcomponent):
<|fim_middle|>
class SchedulingAdaptiveCommsComponent(SchedulingComponentMixin,
threadedadaptivecommscomponent):
def __init__(self, **argd):
super(SchedulingAdaptiveCommsComponent, self).__init__(**argd)
<|fim▁end|> | def __init__(self, **argd):
super(SchedulingComponent, self).__init__(**argd) |
<|file_name|>SchedulingComponent.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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.
from ThreadedComponent import threadedcomponent, threadedadaptivecommscomponent
import heapq
import time
class SchedulingComponentMixin(object):
"""
SchedulingComponent() -> new SchedulingComponent
Base class for a threadedcomponent with an inbuilt scheduler, allowing a
component to block until a scheduled event is ready or a message is received
on an inbox.
"""
Inboxes = {"inbox" : "Standard inbox for receiving data from other components",
"control" : "Standard inbox for receiving control messages from other components",
"event" : "Scheduled events which are ready to be processed"}
def __init__(self, **argd):
super(SchedulingComponentMixin, self).__init__(**argd)
self.eventQueue = []
def scheduleRel(self, message, delay, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after a delay.
"""
return self.scheduleAbs(message, time.time() + delay, priority)
def scheduleAbs(self, message, eventTime, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after at a specified time.
"""
event = eventTime, priority, message
heapq.heappush(self.eventQueue, event)
return event
def cancelEvent(self, event):
""" Remove a scheduled event from the scheduler """
self.eventQueue.remove(event)
heapq.heapify(self.eventQueue)
def eventReady(self):
""" Returns true if there is an event ready to be processed """
if self.eventQueue:
eventTime = self.eventQueue[0][0]
if time.time() >= eventTime:
return True
return False
def pause(self):
"""
Sleep until there is either an event ready or a message is received on
an inbox
"""
if self.eventReady():
self.signalEvent()
else:
if self.eventQueue:
eventTime = self.eventQueue[0][0]
super(SchedulingComponentMixin, self).pause(eventTime - time.time())
if self.eventReady():
self.signalEvent()
else:
super(SchedulingComponentMixin, self).pause()
def signalEvent(self):
"""
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.heappop(self.eventQueue)
#print "Signalling, late by:", (time.time() - eventTime)
if not self.inqueues["event"].full():
self.inqueues["event"].put(message)
class SchedulingComponent(SchedulingComponentMixin, threadedcomponent):
def __init__(self, **argd):
<|fim_middle|>
class SchedulingAdaptiveCommsComponent(SchedulingComponentMixin,
threadedadaptivecommscomponent):
def __init__(self, **argd):
super(SchedulingAdaptiveCommsComponent, self).__init__(**argd)
<|fim▁end|> | super(SchedulingComponent, self).__init__(**argd) |
<|file_name|>SchedulingComponent.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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.
from ThreadedComponent import threadedcomponent, threadedadaptivecommscomponent
import heapq
import time
class SchedulingComponentMixin(object):
"""
SchedulingComponent() -> new SchedulingComponent
Base class for a threadedcomponent with an inbuilt scheduler, allowing a
component to block until a scheduled event is ready or a message is received
on an inbox.
"""
Inboxes = {"inbox" : "Standard inbox for receiving data from other components",
"control" : "Standard inbox for receiving control messages from other components",
"event" : "Scheduled events which are ready to be processed"}
def __init__(self, **argd):
super(SchedulingComponentMixin, self).__init__(**argd)
self.eventQueue = []
def scheduleRel(self, message, delay, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after a delay.
"""
return self.scheduleAbs(message, time.time() + delay, priority)
def scheduleAbs(self, message, eventTime, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after at a specified time.
"""
event = eventTime, priority, message
heapq.heappush(self.eventQueue, event)
return event
def cancelEvent(self, event):
""" Remove a scheduled event from the scheduler """
self.eventQueue.remove(event)
heapq.heapify(self.eventQueue)
def eventReady(self):
""" Returns true if there is an event ready to be processed """
if self.eventQueue:
eventTime = self.eventQueue[0][0]
if time.time() >= eventTime:
return True
return False
def pause(self):
"""
Sleep until there is either an event ready or a message is received on
an inbox
"""
if self.eventReady():
self.signalEvent()
else:
if self.eventQueue:
eventTime = self.eventQueue[0][0]
super(SchedulingComponentMixin, self).pause(eventTime - time.time())
if self.eventReady():
self.signalEvent()
else:
super(SchedulingComponentMixin, self).pause()
def signalEvent(self):
"""
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.heappop(self.eventQueue)
#print "Signalling, late by:", (time.time() - eventTime)
if not self.inqueues["event"].full():
self.inqueues["event"].put(message)
class SchedulingComponent(SchedulingComponentMixin, threadedcomponent):
def __init__(self, **argd):
super(SchedulingComponent, self).__init__(**argd)
class SchedulingAdaptiveCommsComponent(SchedulingComponentMixin,
threadedadaptivecommscomponent):
<|fim_middle|>
<|fim▁end|> | def __init__(self, **argd):
super(SchedulingAdaptiveCommsComponent, self).__init__(**argd) |
<|file_name|>SchedulingComponent.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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.
from ThreadedComponent import threadedcomponent, threadedadaptivecommscomponent
import heapq
import time
class SchedulingComponentMixin(object):
"""
SchedulingComponent() -> new SchedulingComponent
Base class for a threadedcomponent with an inbuilt scheduler, allowing a
component to block until a scheduled event is ready or a message is received
on an inbox.
"""
Inboxes = {"inbox" : "Standard inbox for receiving data from other components",
"control" : "Standard inbox for receiving control messages from other components",
"event" : "Scheduled events which are ready to be processed"}
def __init__(self, **argd):
super(SchedulingComponentMixin, self).__init__(**argd)
self.eventQueue = []
def scheduleRel(self, message, delay, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after a delay.
"""
return self.scheduleAbs(message, time.time() + delay, priority)
def scheduleAbs(self, message, eventTime, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after at a specified time.
"""
event = eventTime, priority, message
heapq.heappush(self.eventQueue, event)
return event
def cancelEvent(self, event):
""" Remove a scheduled event from the scheduler """
self.eventQueue.remove(event)
heapq.heapify(self.eventQueue)
def eventReady(self):
""" Returns true if there is an event ready to be processed """
if self.eventQueue:
eventTime = self.eventQueue[0][0]
if time.time() >= eventTime:
return True
return False
def pause(self):
"""
Sleep until there is either an event ready or a message is received on
an inbox
"""
if self.eventReady():
self.signalEvent()
else:
if self.eventQueue:
eventTime = self.eventQueue[0][0]
super(SchedulingComponentMixin, self).pause(eventTime - time.time())
if self.eventReady():
self.signalEvent()
else:
super(SchedulingComponentMixin, self).pause()
def signalEvent(self):
"""
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.heappop(self.eventQueue)
#print "Signalling, late by:", (time.time() - eventTime)
if not self.inqueues["event"].full():
self.inqueues["event"].put(message)
class SchedulingComponent(SchedulingComponentMixin, threadedcomponent):
def __init__(self, **argd):
super(SchedulingComponent, self).__init__(**argd)
class SchedulingAdaptiveCommsComponent(SchedulingComponentMixin,
threadedadaptivecommscomponent):
def __init__(self, **argd):
<|fim_middle|>
<|fim▁end|> | super(SchedulingAdaptiveCommsComponent, self).__init__(**argd) |
<|file_name|>SchedulingComponent.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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.
from ThreadedComponent import threadedcomponent, threadedadaptivecommscomponent
import heapq
import time
class SchedulingComponentMixin(object):
"""
SchedulingComponent() -> new SchedulingComponent
Base class for a threadedcomponent with an inbuilt scheduler, allowing a
component to block until a scheduled event is ready or a message is received
on an inbox.
"""
Inboxes = {"inbox" : "Standard inbox for receiving data from other components",
"control" : "Standard inbox for receiving control messages from other components",
"event" : "Scheduled events which are ready to be processed"}
def __init__(self, **argd):
super(SchedulingComponentMixin, self).__init__(**argd)
self.eventQueue = []
def scheduleRel(self, message, delay, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after a delay.
"""
return self.scheduleAbs(message, time.time() + delay, priority)
def scheduleAbs(self, message, eventTime, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after at a specified time.
"""
event = eventTime, priority, message
heapq.heappush(self.eventQueue, event)
return event
def cancelEvent(self, event):
""" Remove a scheduled event from the scheduler """
self.eventQueue.remove(event)
heapq.heapify(self.eventQueue)
def eventReady(self):
""" Returns true if there is an event ready to be processed """
if self.eventQueue:
<|fim_middle|>
return False
def pause(self):
"""
Sleep until there is either an event ready or a message is received on
an inbox
"""
if self.eventReady():
self.signalEvent()
else:
if self.eventQueue:
eventTime = self.eventQueue[0][0]
super(SchedulingComponentMixin, self).pause(eventTime - time.time())
if self.eventReady():
self.signalEvent()
else:
super(SchedulingComponentMixin, self).pause()
def signalEvent(self):
"""
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.heappop(self.eventQueue)
#print "Signalling, late by:", (time.time() - eventTime)
if not self.inqueues["event"].full():
self.inqueues["event"].put(message)
class SchedulingComponent(SchedulingComponentMixin, threadedcomponent):
def __init__(self, **argd):
super(SchedulingComponent, self).__init__(**argd)
class SchedulingAdaptiveCommsComponent(SchedulingComponentMixin,
threadedadaptivecommscomponent):
def __init__(self, **argd):
super(SchedulingAdaptiveCommsComponent, self).__init__(**argd)
<|fim▁end|> | eventTime = self.eventQueue[0][0]
if time.time() >= eventTime:
return True |
<|file_name|>SchedulingComponent.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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.
from ThreadedComponent import threadedcomponent, threadedadaptivecommscomponent
import heapq
import time
class SchedulingComponentMixin(object):
"""
SchedulingComponent() -> new SchedulingComponent
Base class for a threadedcomponent with an inbuilt scheduler, allowing a
component to block until a scheduled event is ready or a message is received
on an inbox.
"""
Inboxes = {"inbox" : "Standard inbox for receiving data from other components",
"control" : "Standard inbox for receiving control messages from other components",
"event" : "Scheduled events which are ready to be processed"}
def __init__(self, **argd):
super(SchedulingComponentMixin, self).__init__(**argd)
self.eventQueue = []
def scheduleRel(self, message, delay, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after a delay.
"""
return self.scheduleAbs(message, time.time() + delay, priority)
def scheduleAbs(self, message, eventTime, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after at a specified time.
"""
event = eventTime, priority, message
heapq.heappush(self.eventQueue, event)
return event
def cancelEvent(self, event):
""" Remove a scheduled event from the scheduler """
self.eventQueue.remove(event)
heapq.heapify(self.eventQueue)
def eventReady(self):
""" Returns true if there is an event ready to be processed """
if self.eventQueue:
eventTime = self.eventQueue[0][0]
if time.time() >= eventTime:
<|fim_middle|>
return False
def pause(self):
"""
Sleep until there is either an event ready or a message is received on
an inbox
"""
if self.eventReady():
self.signalEvent()
else:
if self.eventQueue:
eventTime = self.eventQueue[0][0]
super(SchedulingComponentMixin, self).pause(eventTime - time.time())
if self.eventReady():
self.signalEvent()
else:
super(SchedulingComponentMixin, self).pause()
def signalEvent(self):
"""
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.heappop(self.eventQueue)
#print "Signalling, late by:", (time.time() - eventTime)
if not self.inqueues["event"].full():
self.inqueues["event"].put(message)
class SchedulingComponent(SchedulingComponentMixin, threadedcomponent):
def __init__(self, **argd):
super(SchedulingComponent, self).__init__(**argd)
class SchedulingAdaptiveCommsComponent(SchedulingComponentMixin,
threadedadaptivecommscomponent):
def __init__(self, **argd):
super(SchedulingAdaptiveCommsComponent, self).__init__(**argd)
<|fim▁end|> | return True |
<|file_name|>SchedulingComponent.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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.
from ThreadedComponent import threadedcomponent, threadedadaptivecommscomponent
import heapq
import time
class SchedulingComponentMixin(object):
"""
SchedulingComponent() -> new SchedulingComponent
Base class for a threadedcomponent with an inbuilt scheduler, allowing a
component to block until a scheduled event is ready or a message is received
on an inbox.
"""
Inboxes = {"inbox" : "Standard inbox for receiving data from other components",
"control" : "Standard inbox for receiving control messages from other components",
"event" : "Scheduled events which are ready to be processed"}
def __init__(self, **argd):
super(SchedulingComponentMixin, self).__init__(**argd)
self.eventQueue = []
def scheduleRel(self, message, delay, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after a delay.
"""
return self.scheduleAbs(message, time.time() + delay, priority)
def scheduleAbs(self, message, eventTime, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after at a specified time.
"""
event = eventTime, priority, message
heapq.heappush(self.eventQueue, event)
return event
def cancelEvent(self, event):
""" Remove a scheduled event from the scheduler """
self.eventQueue.remove(event)
heapq.heapify(self.eventQueue)
def eventReady(self):
""" Returns true if there is an event ready to be processed """
if self.eventQueue:
eventTime = self.eventQueue[0][0]
if time.time() >= eventTime:
return True
return False
def pause(self):
"""
Sleep until there is either an event ready or a message is received on
an inbox
"""
if self.eventReady():
<|fim_middle|>
else:
if self.eventQueue:
eventTime = self.eventQueue[0][0]
super(SchedulingComponentMixin, self).pause(eventTime - time.time())
if self.eventReady():
self.signalEvent()
else:
super(SchedulingComponentMixin, self).pause()
def signalEvent(self):
"""
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.heappop(self.eventQueue)
#print "Signalling, late by:", (time.time() - eventTime)
if not self.inqueues["event"].full():
self.inqueues["event"].put(message)
class SchedulingComponent(SchedulingComponentMixin, threadedcomponent):
def __init__(self, **argd):
super(SchedulingComponent, self).__init__(**argd)
class SchedulingAdaptiveCommsComponent(SchedulingComponentMixin,
threadedadaptivecommscomponent):
def __init__(self, **argd):
super(SchedulingAdaptiveCommsComponent, self).__init__(**argd)
<|fim▁end|> | self.signalEvent() |
<|file_name|>SchedulingComponent.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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.
from ThreadedComponent import threadedcomponent, threadedadaptivecommscomponent
import heapq
import time
class SchedulingComponentMixin(object):
"""
SchedulingComponent() -> new SchedulingComponent
Base class for a threadedcomponent with an inbuilt scheduler, allowing a
component to block until a scheduled event is ready or a message is received
on an inbox.
"""
Inboxes = {"inbox" : "Standard inbox for receiving data from other components",
"control" : "Standard inbox for receiving control messages from other components",
"event" : "Scheduled events which are ready to be processed"}
def __init__(self, **argd):
super(SchedulingComponentMixin, self).__init__(**argd)
self.eventQueue = []
def scheduleRel(self, message, delay, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after a delay.
"""
return self.scheduleAbs(message, time.time() + delay, priority)
def scheduleAbs(self, message, eventTime, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after at a specified time.
"""
event = eventTime, priority, message
heapq.heappush(self.eventQueue, event)
return event
def cancelEvent(self, event):
""" Remove a scheduled event from the scheduler """
self.eventQueue.remove(event)
heapq.heapify(self.eventQueue)
def eventReady(self):
""" Returns true if there is an event ready to be processed """
if self.eventQueue:
eventTime = self.eventQueue[0][0]
if time.time() >= eventTime:
return True
return False
def pause(self):
"""
Sleep until there is either an event ready or a message is received on
an inbox
"""
if self.eventReady():
self.signalEvent()
else:
<|fim_middle|>
def signalEvent(self):
"""
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.heappop(self.eventQueue)
#print "Signalling, late by:", (time.time() - eventTime)
if not self.inqueues["event"].full():
self.inqueues["event"].put(message)
class SchedulingComponent(SchedulingComponentMixin, threadedcomponent):
def __init__(self, **argd):
super(SchedulingComponent, self).__init__(**argd)
class SchedulingAdaptiveCommsComponent(SchedulingComponentMixin,
threadedadaptivecommscomponent):
def __init__(self, **argd):
super(SchedulingAdaptiveCommsComponent, self).__init__(**argd)
<|fim▁end|> | if self.eventQueue:
eventTime = self.eventQueue[0][0]
super(SchedulingComponentMixin, self).pause(eventTime - time.time())
if self.eventReady():
self.signalEvent()
else:
super(SchedulingComponentMixin, self).pause() |
<|file_name|>SchedulingComponent.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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.
from ThreadedComponent import threadedcomponent, threadedadaptivecommscomponent
import heapq
import time
class SchedulingComponentMixin(object):
"""
SchedulingComponent() -> new SchedulingComponent
Base class for a threadedcomponent with an inbuilt scheduler, allowing a
component to block until a scheduled event is ready or a message is received
on an inbox.
"""
Inboxes = {"inbox" : "Standard inbox for receiving data from other components",
"control" : "Standard inbox for receiving control messages from other components",
"event" : "Scheduled events which are ready to be processed"}
def __init__(self, **argd):
super(SchedulingComponentMixin, self).__init__(**argd)
self.eventQueue = []
def scheduleRel(self, message, delay, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after a delay.
"""
return self.scheduleAbs(message, time.time() + delay, priority)
def scheduleAbs(self, message, eventTime, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after at a specified time.
"""
event = eventTime, priority, message
heapq.heappush(self.eventQueue, event)
return event
def cancelEvent(self, event):
""" Remove a scheduled event from the scheduler """
self.eventQueue.remove(event)
heapq.heapify(self.eventQueue)
def eventReady(self):
""" Returns true if there is an event ready to be processed """
if self.eventQueue:
eventTime = self.eventQueue[0][0]
if time.time() >= eventTime:
return True
return False
def pause(self):
"""
Sleep until there is either an event ready or a message is received on
an inbox
"""
if self.eventReady():
self.signalEvent()
else:
if self.eventQueue:
<|fim_middle|>
else:
super(SchedulingComponentMixin, self).pause()
def signalEvent(self):
"""
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.heappop(self.eventQueue)
#print "Signalling, late by:", (time.time() - eventTime)
if not self.inqueues["event"].full():
self.inqueues["event"].put(message)
class SchedulingComponent(SchedulingComponentMixin, threadedcomponent):
def __init__(self, **argd):
super(SchedulingComponent, self).__init__(**argd)
class SchedulingAdaptiveCommsComponent(SchedulingComponentMixin,
threadedadaptivecommscomponent):
def __init__(self, **argd):
super(SchedulingAdaptiveCommsComponent, self).__init__(**argd)
<|fim▁end|> | eventTime = self.eventQueue[0][0]
super(SchedulingComponentMixin, self).pause(eventTime - time.time())
if self.eventReady():
self.signalEvent() |
<|file_name|>SchedulingComponent.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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.
from ThreadedComponent import threadedcomponent, threadedadaptivecommscomponent
import heapq
import time
class SchedulingComponentMixin(object):
"""
SchedulingComponent() -> new SchedulingComponent
Base class for a threadedcomponent with an inbuilt scheduler, allowing a
component to block until a scheduled event is ready or a message is received
on an inbox.
"""
Inboxes = {"inbox" : "Standard inbox for receiving data from other components",
"control" : "Standard inbox for receiving control messages from other components",
"event" : "Scheduled events which are ready to be processed"}
def __init__(self, **argd):
super(SchedulingComponentMixin, self).__init__(**argd)
self.eventQueue = []
def scheduleRel(self, message, delay, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after a delay.
"""
return self.scheduleAbs(message, time.time() + delay, priority)
def scheduleAbs(self, message, eventTime, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after at a specified time.
"""
event = eventTime, priority, message
heapq.heappush(self.eventQueue, event)
return event
def cancelEvent(self, event):
""" Remove a scheduled event from the scheduler """
self.eventQueue.remove(event)
heapq.heapify(self.eventQueue)
def eventReady(self):
""" Returns true if there is an event ready to be processed """
if self.eventQueue:
eventTime = self.eventQueue[0][0]
if time.time() >= eventTime:
return True
return False
def pause(self):
"""
Sleep until there is either an event ready or a message is received on
an inbox
"""
if self.eventReady():
self.signalEvent()
else:
if self.eventQueue:
eventTime = self.eventQueue[0][0]
super(SchedulingComponentMixin, self).pause(eventTime - time.time())
if self.eventReady():
<|fim_middle|>
else:
super(SchedulingComponentMixin, self).pause()
def signalEvent(self):
"""
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.heappop(self.eventQueue)
#print "Signalling, late by:", (time.time() - eventTime)
if not self.inqueues["event"].full():
self.inqueues["event"].put(message)
class SchedulingComponent(SchedulingComponentMixin, threadedcomponent):
def __init__(self, **argd):
super(SchedulingComponent, self).__init__(**argd)
class SchedulingAdaptiveCommsComponent(SchedulingComponentMixin,
threadedadaptivecommscomponent):
def __init__(self, **argd):
super(SchedulingAdaptiveCommsComponent, self).__init__(**argd)
<|fim▁end|> | self.signalEvent() |
<|file_name|>SchedulingComponent.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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.
from ThreadedComponent import threadedcomponent, threadedadaptivecommscomponent
import heapq
import time
class SchedulingComponentMixin(object):
"""
SchedulingComponent() -> new SchedulingComponent
Base class for a threadedcomponent with an inbuilt scheduler, allowing a
component to block until a scheduled event is ready or a message is received
on an inbox.
"""
Inboxes = {"inbox" : "Standard inbox for receiving data from other components",
"control" : "Standard inbox for receiving control messages from other components",
"event" : "Scheduled events which are ready to be processed"}
def __init__(self, **argd):
super(SchedulingComponentMixin, self).__init__(**argd)
self.eventQueue = []
def scheduleRel(self, message, delay, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after a delay.
"""
return self.scheduleAbs(message, time.time() + delay, priority)
def scheduleAbs(self, message, eventTime, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after at a specified time.
"""
event = eventTime, priority, message
heapq.heappush(self.eventQueue, event)
return event
def cancelEvent(self, event):
""" Remove a scheduled event from the scheduler """
self.eventQueue.remove(event)
heapq.heapify(self.eventQueue)
def eventReady(self):
""" Returns true if there is an event ready to be processed """
if self.eventQueue:
eventTime = self.eventQueue[0][0]
if time.time() >= eventTime:
return True
return False
def pause(self):
"""
Sleep until there is either an event ready or a message is received on
an inbox
"""
if self.eventReady():
self.signalEvent()
else:
if self.eventQueue:
eventTime = self.eventQueue[0][0]
super(SchedulingComponentMixin, self).pause(eventTime - time.time())
if self.eventReady():
self.signalEvent()
else:
<|fim_middle|>
def signalEvent(self):
"""
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.heappop(self.eventQueue)
#print "Signalling, late by:", (time.time() - eventTime)
if not self.inqueues["event"].full():
self.inqueues["event"].put(message)
class SchedulingComponent(SchedulingComponentMixin, threadedcomponent):
def __init__(self, **argd):
super(SchedulingComponent, self).__init__(**argd)
class SchedulingAdaptiveCommsComponent(SchedulingComponentMixin,
threadedadaptivecommscomponent):
def __init__(self, **argd):
super(SchedulingAdaptiveCommsComponent, self).__init__(**argd)
<|fim▁end|> | super(SchedulingComponentMixin, self).pause() |
<|file_name|>SchedulingComponent.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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.
from ThreadedComponent import threadedcomponent, threadedadaptivecommscomponent
import heapq
import time
class SchedulingComponentMixin(object):
"""
SchedulingComponent() -> new SchedulingComponent
Base class for a threadedcomponent with an inbuilt scheduler, allowing a
component to block until a scheduled event is ready or a message is received
on an inbox.
"""
Inboxes = {"inbox" : "Standard inbox for receiving data from other components",
"control" : "Standard inbox for receiving control messages from other components",
"event" : "Scheduled events which are ready to be processed"}
def __init__(self, **argd):
super(SchedulingComponentMixin, self).__init__(**argd)
self.eventQueue = []
def scheduleRel(self, message, delay, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after a delay.
"""
return self.scheduleAbs(message, time.time() + delay, priority)
def scheduleAbs(self, message, eventTime, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after at a specified time.
"""
event = eventTime, priority, message
heapq.heappush(self.eventQueue, event)
return event
def cancelEvent(self, event):
""" Remove a scheduled event from the scheduler """
self.eventQueue.remove(event)
heapq.heapify(self.eventQueue)
def eventReady(self):
""" Returns true if there is an event ready to be processed """
if self.eventQueue:
eventTime = self.eventQueue[0][0]
if time.time() >= eventTime:
return True
return False
def pause(self):
"""
Sleep until there is either an event ready or a message is received on
an inbox
"""
if self.eventReady():
self.signalEvent()
else:
if self.eventQueue:
eventTime = self.eventQueue[0][0]
super(SchedulingComponentMixin, self).pause(eventTime - time.time())
if self.eventReady():
self.signalEvent()
else:
super(SchedulingComponentMixin, self).pause()
def signalEvent(self):
"""
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.heappop(self.eventQueue)
#print "Signalling, late by:", (time.time() - eventTime)
if not self.inqueues["event"].full():
<|fim_middle|>
class SchedulingComponent(SchedulingComponentMixin, threadedcomponent):
def __init__(self, **argd):
super(SchedulingComponent, self).__init__(**argd)
class SchedulingAdaptiveCommsComponent(SchedulingComponentMixin,
threadedadaptivecommscomponent):
def __init__(self, **argd):
super(SchedulingAdaptiveCommsComponent, self).__init__(**argd)
<|fim▁end|> | self.inqueues["event"].put(message) |
<|file_name|>SchedulingComponent.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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.
from ThreadedComponent import threadedcomponent, threadedadaptivecommscomponent
import heapq
import time
class SchedulingComponentMixin(object):
"""
SchedulingComponent() -> new SchedulingComponent
Base class for a threadedcomponent with an inbuilt scheduler, allowing a
component to block until a scheduled event is ready or a message is received
on an inbox.
"""
Inboxes = {"inbox" : "Standard inbox for receiving data from other components",
"control" : "Standard inbox for receiving control messages from other components",
"event" : "Scheduled events which are ready to be processed"}
def <|fim_middle|>(self, **argd):
super(SchedulingComponentMixin, self).__init__(**argd)
self.eventQueue = []
def scheduleRel(self, message, delay, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after a delay.
"""
return self.scheduleAbs(message, time.time() + delay, priority)
def scheduleAbs(self, message, eventTime, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after at a specified time.
"""
event = eventTime, priority, message
heapq.heappush(self.eventQueue, event)
return event
def cancelEvent(self, event):
""" Remove a scheduled event from the scheduler """
self.eventQueue.remove(event)
heapq.heapify(self.eventQueue)
def eventReady(self):
""" Returns true if there is an event ready to be processed """
if self.eventQueue:
eventTime = self.eventQueue[0][0]
if time.time() >= eventTime:
return True
return False
def pause(self):
"""
Sleep until there is either an event ready or a message is received on
an inbox
"""
if self.eventReady():
self.signalEvent()
else:
if self.eventQueue:
eventTime = self.eventQueue[0][0]
super(SchedulingComponentMixin, self).pause(eventTime - time.time())
if self.eventReady():
self.signalEvent()
else:
super(SchedulingComponentMixin, self).pause()
def signalEvent(self):
"""
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.heappop(self.eventQueue)
#print "Signalling, late by:", (time.time() - eventTime)
if not self.inqueues["event"].full():
self.inqueues["event"].put(message)
class SchedulingComponent(SchedulingComponentMixin, threadedcomponent):
def __init__(self, **argd):
super(SchedulingComponent, self).__init__(**argd)
class SchedulingAdaptiveCommsComponent(SchedulingComponentMixin,
threadedadaptivecommscomponent):
def __init__(self, **argd):
super(SchedulingAdaptiveCommsComponent, self).__init__(**argd)
<|fim▁end|> | __init__ |
<|file_name|>SchedulingComponent.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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.
from ThreadedComponent import threadedcomponent, threadedadaptivecommscomponent
import heapq
import time
class SchedulingComponentMixin(object):
"""
SchedulingComponent() -> new SchedulingComponent
Base class for a threadedcomponent with an inbuilt scheduler, allowing a
component to block until a scheduled event is ready or a message is received
on an inbox.
"""
Inboxes = {"inbox" : "Standard inbox for receiving data from other components",
"control" : "Standard inbox for receiving control messages from other components",
"event" : "Scheduled events which are ready to be processed"}
def __init__(self, **argd):
super(SchedulingComponentMixin, self).__init__(**argd)
self.eventQueue = []
def <|fim_middle|>(self, message, delay, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after a delay.
"""
return self.scheduleAbs(message, time.time() + delay, priority)
def scheduleAbs(self, message, eventTime, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after at a specified time.
"""
event = eventTime, priority, message
heapq.heappush(self.eventQueue, event)
return event
def cancelEvent(self, event):
""" Remove a scheduled event from the scheduler """
self.eventQueue.remove(event)
heapq.heapify(self.eventQueue)
def eventReady(self):
""" Returns true if there is an event ready to be processed """
if self.eventQueue:
eventTime = self.eventQueue[0][0]
if time.time() >= eventTime:
return True
return False
def pause(self):
"""
Sleep until there is either an event ready or a message is received on
an inbox
"""
if self.eventReady():
self.signalEvent()
else:
if self.eventQueue:
eventTime = self.eventQueue[0][0]
super(SchedulingComponentMixin, self).pause(eventTime - time.time())
if self.eventReady():
self.signalEvent()
else:
super(SchedulingComponentMixin, self).pause()
def signalEvent(self):
"""
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.heappop(self.eventQueue)
#print "Signalling, late by:", (time.time() - eventTime)
if not self.inqueues["event"].full():
self.inqueues["event"].put(message)
class SchedulingComponent(SchedulingComponentMixin, threadedcomponent):
def __init__(self, **argd):
super(SchedulingComponent, self).__init__(**argd)
class SchedulingAdaptiveCommsComponent(SchedulingComponentMixin,
threadedadaptivecommscomponent):
def __init__(self, **argd):
super(SchedulingAdaptiveCommsComponent, self).__init__(**argd)
<|fim▁end|> | scheduleRel |
<|file_name|>SchedulingComponent.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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.
from ThreadedComponent import threadedcomponent, threadedadaptivecommscomponent
import heapq
import time
class SchedulingComponentMixin(object):
"""
SchedulingComponent() -> new SchedulingComponent
Base class for a threadedcomponent with an inbuilt scheduler, allowing a
component to block until a scheduled event is ready or a message is received
on an inbox.
"""
Inboxes = {"inbox" : "Standard inbox for receiving data from other components",
"control" : "Standard inbox for receiving control messages from other components",
"event" : "Scheduled events which are ready to be processed"}
def __init__(self, **argd):
super(SchedulingComponentMixin, self).__init__(**argd)
self.eventQueue = []
def scheduleRel(self, message, delay, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after a delay.
"""
return self.scheduleAbs(message, time.time() + delay, priority)
def <|fim_middle|>(self, message, eventTime, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after at a specified time.
"""
event = eventTime, priority, message
heapq.heappush(self.eventQueue, event)
return event
def cancelEvent(self, event):
""" Remove a scheduled event from the scheduler """
self.eventQueue.remove(event)
heapq.heapify(self.eventQueue)
def eventReady(self):
""" Returns true if there is an event ready to be processed """
if self.eventQueue:
eventTime = self.eventQueue[0][0]
if time.time() >= eventTime:
return True
return False
def pause(self):
"""
Sleep until there is either an event ready or a message is received on
an inbox
"""
if self.eventReady():
self.signalEvent()
else:
if self.eventQueue:
eventTime = self.eventQueue[0][0]
super(SchedulingComponentMixin, self).pause(eventTime - time.time())
if self.eventReady():
self.signalEvent()
else:
super(SchedulingComponentMixin, self).pause()
def signalEvent(self):
"""
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.heappop(self.eventQueue)
#print "Signalling, late by:", (time.time() - eventTime)
if not self.inqueues["event"].full():
self.inqueues["event"].put(message)
class SchedulingComponent(SchedulingComponentMixin, threadedcomponent):
def __init__(self, **argd):
super(SchedulingComponent, self).__init__(**argd)
class SchedulingAdaptiveCommsComponent(SchedulingComponentMixin,
threadedadaptivecommscomponent):
def __init__(self, **argd):
super(SchedulingAdaptiveCommsComponent, self).__init__(**argd)
<|fim▁end|> | scheduleAbs |
<|file_name|>SchedulingComponent.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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.
from ThreadedComponent import threadedcomponent, threadedadaptivecommscomponent
import heapq
import time
class SchedulingComponentMixin(object):
"""
SchedulingComponent() -> new SchedulingComponent
Base class for a threadedcomponent with an inbuilt scheduler, allowing a
component to block until a scheduled event is ready or a message is received
on an inbox.
"""
Inboxes = {"inbox" : "Standard inbox for receiving data from other components",
"control" : "Standard inbox for receiving control messages from other components",
"event" : "Scheduled events which are ready to be processed"}
def __init__(self, **argd):
super(SchedulingComponentMixin, self).__init__(**argd)
self.eventQueue = []
def scheduleRel(self, message, delay, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after a delay.
"""
return self.scheduleAbs(message, time.time() + delay, priority)
def scheduleAbs(self, message, eventTime, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after at a specified time.
"""
event = eventTime, priority, message
heapq.heappush(self.eventQueue, event)
return event
def <|fim_middle|>(self, event):
""" Remove a scheduled event from the scheduler """
self.eventQueue.remove(event)
heapq.heapify(self.eventQueue)
def eventReady(self):
""" Returns true if there is an event ready to be processed """
if self.eventQueue:
eventTime = self.eventQueue[0][0]
if time.time() >= eventTime:
return True
return False
def pause(self):
"""
Sleep until there is either an event ready or a message is received on
an inbox
"""
if self.eventReady():
self.signalEvent()
else:
if self.eventQueue:
eventTime = self.eventQueue[0][0]
super(SchedulingComponentMixin, self).pause(eventTime - time.time())
if self.eventReady():
self.signalEvent()
else:
super(SchedulingComponentMixin, self).pause()
def signalEvent(self):
"""
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.heappop(self.eventQueue)
#print "Signalling, late by:", (time.time() - eventTime)
if not self.inqueues["event"].full():
self.inqueues["event"].put(message)
class SchedulingComponent(SchedulingComponentMixin, threadedcomponent):
def __init__(self, **argd):
super(SchedulingComponent, self).__init__(**argd)
class SchedulingAdaptiveCommsComponent(SchedulingComponentMixin,
threadedadaptivecommscomponent):
def __init__(self, **argd):
super(SchedulingAdaptiveCommsComponent, self).__init__(**argd)
<|fim▁end|> | cancelEvent |
<|file_name|>SchedulingComponent.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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.
from ThreadedComponent import threadedcomponent, threadedadaptivecommscomponent
import heapq
import time
class SchedulingComponentMixin(object):
"""
SchedulingComponent() -> new SchedulingComponent
Base class for a threadedcomponent with an inbuilt scheduler, allowing a
component to block until a scheduled event is ready or a message is received
on an inbox.
"""
Inboxes = {"inbox" : "Standard inbox for receiving data from other components",
"control" : "Standard inbox for receiving control messages from other components",
"event" : "Scheduled events which are ready to be processed"}
def __init__(self, **argd):
super(SchedulingComponentMixin, self).__init__(**argd)
self.eventQueue = []
def scheduleRel(self, message, delay, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after a delay.
"""
return self.scheduleAbs(message, time.time() + delay, priority)
def scheduleAbs(self, message, eventTime, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after at a specified time.
"""
event = eventTime, priority, message
heapq.heappush(self.eventQueue, event)
return event
def cancelEvent(self, event):
""" Remove a scheduled event from the scheduler """
self.eventQueue.remove(event)
heapq.heapify(self.eventQueue)
def <|fim_middle|>(self):
""" Returns true if there is an event ready to be processed """
if self.eventQueue:
eventTime = self.eventQueue[0][0]
if time.time() >= eventTime:
return True
return False
def pause(self):
"""
Sleep until there is either an event ready or a message is received on
an inbox
"""
if self.eventReady():
self.signalEvent()
else:
if self.eventQueue:
eventTime = self.eventQueue[0][0]
super(SchedulingComponentMixin, self).pause(eventTime - time.time())
if self.eventReady():
self.signalEvent()
else:
super(SchedulingComponentMixin, self).pause()
def signalEvent(self):
"""
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.heappop(self.eventQueue)
#print "Signalling, late by:", (time.time() - eventTime)
if not self.inqueues["event"].full():
self.inqueues["event"].put(message)
class SchedulingComponent(SchedulingComponentMixin, threadedcomponent):
def __init__(self, **argd):
super(SchedulingComponent, self).__init__(**argd)
class SchedulingAdaptiveCommsComponent(SchedulingComponentMixin,
threadedadaptivecommscomponent):
def __init__(self, **argd):
super(SchedulingAdaptiveCommsComponent, self).__init__(**argd)
<|fim▁end|> | eventReady |
<|file_name|>SchedulingComponent.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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.
from ThreadedComponent import threadedcomponent, threadedadaptivecommscomponent
import heapq
import time
class SchedulingComponentMixin(object):
"""
SchedulingComponent() -> new SchedulingComponent
Base class for a threadedcomponent with an inbuilt scheduler, allowing a
component to block until a scheduled event is ready or a message is received
on an inbox.
"""
Inboxes = {"inbox" : "Standard inbox for receiving data from other components",
"control" : "Standard inbox for receiving control messages from other components",
"event" : "Scheduled events which are ready to be processed"}
def __init__(self, **argd):
super(SchedulingComponentMixin, self).__init__(**argd)
self.eventQueue = []
def scheduleRel(self, message, delay, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after a delay.
"""
return self.scheduleAbs(message, time.time() + delay, priority)
def scheduleAbs(self, message, eventTime, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after at a specified time.
"""
event = eventTime, priority, message
heapq.heappush(self.eventQueue, event)
return event
def cancelEvent(self, event):
""" Remove a scheduled event from the scheduler """
self.eventQueue.remove(event)
heapq.heapify(self.eventQueue)
def eventReady(self):
""" Returns true if there is an event ready to be processed """
if self.eventQueue:
eventTime = self.eventQueue[0][0]
if time.time() >= eventTime:
return True
return False
def <|fim_middle|>(self):
"""
Sleep until there is either an event ready or a message is received on
an inbox
"""
if self.eventReady():
self.signalEvent()
else:
if self.eventQueue:
eventTime = self.eventQueue[0][0]
super(SchedulingComponentMixin, self).pause(eventTime - time.time())
if self.eventReady():
self.signalEvent()
else:
super(SchedulingComponentMixin, self).pause()
def signalEvent(self):
"""
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.heappop(self.eventQueue)
#print "Signalling, late by:", (time.time() - eventTime)
if not self.inqueues["event"].full():
self.inqueues["event"].put(message)
class SchedulingComponent(SchedulingComponentMixin, threadedcomponent):
def __init__(self, **argd):
super(SchedulingComponent, self).__init__(**argd)
class SchedulingAdaptiveCommsComponent(SchedulingComponentMixin,
threadedadaptivecommscomponent):
def __init__(self, **argd):
super(SchedulingAdaptiveCommsComponent, self).__init__(**argd)
<|fim▁end|> | pause |
<|file_name|>SchedulingComponent.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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.
from ThreadedComponent import threadedcomponent, threadedadaptivecommscomponent
import heapq
import time
class SchedulingComponentMixin(object):
"""
SchedulingComponent() -> new SchedulingComponent
Base class for a threadedcomponent with an inbuilt scheduler, allowing a
component to block until a scheduled event is ready or a message is received
on an inbox.
"""
Inboxes = {"inbox" : "Standard inbox for receiving data from other components",
"control" : "Standard inbox for receiving control messages from other components",
"event" : "Scheduled events which are ready to be processed"}
def __init__(self, **argd):
super(SchedulingComponentMixin, self).__init__(**argd)
self.eventQueue = []
def scheduleRel(self, message, delay, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after a delay.
"""
return self.scheduleAbs(message, time.time() + delay, priority)
def scheduleAbs(self, message, eventTime, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after at a specified time.
"""
event = eventTime, priority, message
heapq.heappush(self.eventQueue, event)
return event
def cancelEvent(self, event):
""" Remove a scheduled event from the scheduler """
self.eventQueue.remove(event)
heapq.heapify(self.eventQueue)
def eventReady(self):
""" Returns true if there is an event ready to be processed """
if self.eventQueue:
eventTime = self.eventQueue[0][0]
if time.time() >= eventTime:
return True
return False
def pause(self):
"""
Sleep until there is either an event ready or a message is received on
an inbox
"""
if self.eventReady():
self.signalEvent()
else:
if self.eventQueue:
eventTime = self.eventQueue[0][0]
super(SchedulingComponentMixin, self).pause(eventTime - time.time())
if self.eventReady():
self.signalEvent()
else:
super(SchedulingComponentMixin, self).pause()
def <|fim_middle|>(self):
"""
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.heappop(self.eventQueue)
#print "Signalling, late by:", (time.time() - eventTime)
if not self.inqueues["event"].full():
self.inqueues["event"].put(message)
class SchedulingComponent(SchedulingComponentMixin, threadedcomponent):
def __init__(self, **argd):
super(SchedulingComponent, self).__init__(**argd)
class SchedulingAdaptiveCommsComponent(SchedulingComponentMixin,
threadedadaptivecommscomponent):
def __init__(self, **argd):
super(SchedulingAdaptiveCommsComponent, self).__init__(**argd)
<|fim▁end|> | signalEvent |
<|file_name|>SchedulingComponent.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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.
from ThreadedComponent import threadedcomponent, threadedadaptivecommscomponent
import heapq
import time
class SchedulingComponentMixin(object):
"""
SchedulingComponent() -> new SchedulingComponent
Base class for a threadedcomponent with an inbuilt scheduler, allowing a
component to block until a scheduled event is ready or a message is received
on an inbox.
"""
Inboxes = {"inbox" : "Standard inbox for receiving data from other components",
"control" : "Standard inbox for receiving control messages from other components",
"event" : "Scheduled events which are ready to be processed"}
def __init__(self, **argd):
super(SchedulingComponentMixin, self).__init__(**argd)
self.eventQueue = []
def scheduleRel(self, message, delay, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after a delay.
"""
return self.scheduleAbs(message, time.time() + delay, priority)
def scheduleAbs(self, message, eventTime, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after at a specified time.
"""
event = eventTime, priority, message
heapq.heappush(self.eventQueue, event)
return event
def cancelEvent(self, event):
""" Remove a scheduled event from the scheduler """
self.eventQueue.remove(event)
heapq.heapify(self.eventQueue)
def eventReady(self):
""" Returns true if there is an event ready to be processed """
if self.eventQueue:
eventTime = self.eventQueue[0][0]
if time.time() >= eventTime:
return True
return False
def pause(self):
"""
Sleep until there is either an event ready or a message is received on
an inbox
"""
if self.eventReady():
self.signalEvent()
else:
if self.eventQueue:
eventTime = self.eventQueue[0][0]
super(SchedulingComponentMixin, self).pause(eventTime - time.time())
if self.eventReady():
self.signalEvent()
else:
super(SchedulingComponentMixin, self).pause()
def signalEvent(self):
"""
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.heappop(self.eventQueue)
#print "Signalling, late by:", (time.time() - eventTime)
if not self.inqueues["event"].full():
self.inqueues["event"].put(message)
class SchedulingComponent(SchedulingComponentMixin, threadedcomponent):
def <|fim_middle|>(self, **argd):
super(SchedulingComponent, self).__init__(**argd)
class SchedulingAdaptiveCommsComponent(SchedulingComponentMixin,
threadedadaptivecommscomponent):
def __init__(self, **argd):
super(SchedulingAdaptiveCommsComponent, self).__init__(**argd)
<|fim▁end|> | __init__ |
<|file_name|>SchedulingComponent.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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.
from ThreadedComponent import threadedcomponent, threadedadaptivecommscomponent
import heapq
import time
class SchedulingComponentMixin(object):
"""
SchedulingComponent() -> new SchedulingComponent
Base class for a threadedcomponent with an inbuilt scheduler, allowing a
component to block until a scheduled event is ready or a message is received
on an inbox.
"""
Inboxes = {"inbox" : "Standard inbox for receiving data from other components",
"control" : "Standard inbox for receiving control messages from other components",
"event" : "Scheduled events which are ready to be processed"}
def __init__(self, **argd):
super(SchedulingComponentMixin, self).__init__(**argd)
self.eventQueue = []
def scheduleRel(self, message, delay, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after a delay.
"""
return self.scheduleAbs(message, time.time() + delay, priority)
def scheduleAbs(self, message, eventTime, priority=1):
"""
Schedule an event to wake the component and send a message to the
"event" inbox after at a specified time.
"""
event = eventTime, priority, message
heapq.heappush(self.eventQueue, event)
return event
def cancelEvent(self, event):
""" Remove a scheduled event from the scheduler """
self.eventQueue.remove(event)
heapq.heapify(self.eventQueue)
def eventReady(self):
""" Returns true if there is an event ready to be processed """
if self.eventQueue:
eventTime = self.eventQueue[0][0]
if time.time() >= eventTime:
return True
return False
def pause(self):
"""
Sleep until there is either an event ready or a message is received on
an inbox
"""
if self.eventReady():
self.signalEvent()
else:
if self.eventQueue:
eventTime = self.eventQueue[0][0]
super(SchedulingComponentMixin, self).pause(eventTime - time.time())
if self.eventReady():
self.signalEvent()
else:
super(SchedulingComponentMixin, self).pause()
def signalEvent(self):
"""
Put the event message of the earliest scheduled event onto the
component's "event" inbox and remove it from the scheduler.
"""
eventTime, priority, message = heapq.heappop(self.eventQueue)
#print "Signalling, late by:", (time.time() - eventTime)
if not self.inqueues["event"].full():
self.inqueues["event"].put(message)
class SchedulingComponent(SchedulingComponentMixin, threadedcomponent):
def __init__(self, **argd):
super(SchedulingComponent, self).__init__(**argd)
class SchedulingAdaptiveCommsComponent(SchedulingComponentMixin,
threadedadaptivecommscomponent):
def <|fim_middle|>(self, **argd):
super(SchedulingAdaptiveCommsComponent, self).__init__(**argd)
<|fim▁end|> | __init__ |
<|file_name|>json.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import
import json
class JSONRenderer:<|fim▁hole|> """
def render(self, mystery):
return json.dumps(mystery.encode(), indent=4)<|fim▁end|> | """
Renders a mystery as JSON |
<|file_name|>json.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import
import json
class JSONRenderer:
<|fim_middle|>
<|fim▁end|> | """
Renders a mystery as JSON
"""
def render(self, mystery):
return json.dumps(mystery.encode(), indent=4) |
<|file_name|>json.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import
import json
class JSONRenderer:
"""
Renders a mystery as JSON
"""
def render(self, mystery):
<|fim_middle|>
<|fim▁end|> | return json.dumps(mystery.encode(), indent=4) |
<|file_name|>json.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import
import json
class JSONRenderer:
"""
Renders a mystery as JSON
"""
def <|fim_middle|>(self, mystery):
return json.dumps(mystery.encode(), indent=4)
<|fim▁end|> | render |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|> | default_app_config = "gallery.apps.GalleryConfig" |
<|file_name|>Squares.py<|end_file_name|><|fim▁begin|>#David Hickox
#Feb 15 17
#Squares (counter update)
#descriptions, description, much descripticve
#variables
# limit, where it stops
# num, sentry variable
#creates array if needbe
#array = [[0 for x in range(h)] for y in range(w)]
#imports date time and curency handeling because i hate string formating (this takes the place of #$%.2f"%)
import locale
locale.setlocale( locale.LC_ALL, '' )
#use locale.currency() for currency formating
print("Welcome to the (insert name here bumbblefack) Program\n")
limit = float(input("How many squares do you want? "))
num = 1
print("number\tnumber^2")
while num <= limit:
#prints the number and squares it then seperates by a tab
print (num,num**2,sep='\t')
#increments
num += 1
<|fim▁hole|><|fim▁end|> |
input("\nPress Enter to Exit") |
<|file_name|>finddata.py<|end_file_name|><|fim▁begin|>import pathlib<|fim▁hole|>__all__ = ['sample', 'sampleTxt', 'sampleBin']
this = pathlib.Path(__file__)
datadir = this.parent.parent / 'data'
loader = importlib.machinery.SourceFileLoader('sample', str(datadir / 'sample.py'))
sample = loader.load_module()
sampleTxt = datadir / 'sample.txt'
sampleBin = datadir / 'sample.bin'<|fim▁end|> | import importlib
import sys
|
<|file_name|>behaviors.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
from __future__ import print_function
import sys
import re
from utils import CDNEngine
from utils import request
if sys.version_info >= (3, 0):
import subprocess as commands
import urllib.parse as urlparse
else:
import commands
import urlparse
def detect(hostname):
"""
Performs CDN detection thanks to information disclosure from server error.
Parameters
----------
hostname : str
Hostname to assess
"""
print('[+] Error server detection\n')
hostname = urlparse.urlparse(hostname).netloc
regexp = re.compile('\\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\\b')
out = commands.getoutput("host " + hostname)
addresses = regexp.finditer(out)
for addr in addresses:
res = request.do('http://' + addr.group())<|fim▁hole|><|fim▁end|> | if res is not None and res.status_code == 500:
CDNEngine.find(res.text.lower()) |
<|file_name|>behaviors.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
from __future__ import print_function
import sys
import re
from utils import CDNEngine
from utils import request
if sys.version_info >= (3, 0):
import subprocess as commands
import urllib.parse as urlparse
else:
import commands
import urlparse
def detect(hostname):
<|fim_middle|>
<|fim▁end|> | """
Performs CDN detection thanks to information disclosure from server error.
Parameters
----------
hostname : str
Hostname to assess
"""
print('[+] Error server detection\n')
hostname = urlparse.urlparse(hostname).netloc
regexp = re.compile('\\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\\b')
out = commands.getoutput("host " + hostname)
addresses = regexp.finditer(out)
for addr in addresses:
res = request.do('http://' + addr.group())
if res is not None and res.status_code == 500:
CDNEngine.find(res.text.lower()) |
<|file_name|>behaviors.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
from __future__ import print_function
import sys
import re
from utils import CDNEngine
from utils import request
if sys.version_info >= (3, 0):
<|fim_middle|>
else:
import commands
import urlparse
def detect(hostname):
"""
Performs CDN detection thanks to information disclosure from server error.
Parameters
----------
hostname : str
Hostname to assess
"""
print('[+] Error server detection\n')
hostname = urlparse.urlparse(hostname).netloc
regexp = re.compile('\\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\\b')
out = commands.getoutput("host " + hostname)
addresses = regexp.finditer(out)
for addr in addresses:
res = request.do('http://' + addr.group())
if res is not None and res.status_code == 500:
CDNEngine.find(res.text.lower())
<|fim▁end|> | import subprocess as commands
import urllib.parse as urlparse |
<|file_name|>behaviors.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
from __future__ import print_function
import sys
import re
from utils import CDNEngine
from utils import request
if sys.version_info >= (3, 0):
import subprocess as commands
import urllib.parse as urlparse
else:
<|fim_middle|>
def detect(hostname):
"""
Performs CDN detection thanks to information disclosure from server error.
Parameters
----------
hostname : str
Hostname to assess
"""
print('[+] Error server detection\n')
hostname = urlparse.urlparse(hostname).netloc
regexp = re.compile('\\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\\b')
out = commands.getoutput("host " + hostname)
addresses = regexp.finditer(out)
for addr in addresses:
res = request.do('http://' + addr.group())
if res is not None and res.status_code == 500:
CDNEngine.find(res.text.lower())
<|fim▁end|> | import commands
import urlparse |
<|file_name|>behaviors.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
from __future__ import print_function
import sys
import re
from utils import CDNEngine
from utils import request
if sys.version_info >= (3, 0):
import subprocess as commands
import urllib.parse as urlparse
else:
import commands
import urlparse
def detect(hostname):
"""
Performs CDN detection thanks to information disclosure from server error.
Parameters
----------
hostname : str
Hostname to assess
"""
print('[+] Error server detection\n')
hostname = urlparse.urlparse(hostname).netloc
regexp = re.compile('\\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\\b')
out = commands.getoutput("host " + hostname)
addresses = regexp.finditer(out)
for addr in addresses:
res = request.do('http://' + addr.group())
if res is not None and res.status_code == 500:
<|fim_middle|>
<|fim▁end|> | CDNEngine.find(res.text.lower()) |
<|file_name|>behaviors.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
from __future__ import print_function
import sys
import re
from utils import CDNEngine
from utils import request
if sys.version_info >= (3, 0):
import subprocess as commands
import urllib.parse as urlparse
else:
import commands
import urlparse
def <|fim_middle|>(hostname):
"""
Performs CDN detection thanks to information disclosure from server error.
Parameters
----------
hostname : str
Hostname to assess
"""
print('[+] Error server detection\n')
hostname = urlparse.urlparse(hostname).netloc
regexp = re.compile('\\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\\b')
out = commands.getoutput("host " + hostname)
addresses = regexp.finditer(out)
for addr in addresses:
res = request.do('http://' + addr.group())
if res is not None and res.status_code == 500:
CDNEngine.find(res.text.lower())
<|fim▁end|> | detect |
<|file_name|>banner.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
<|fim▁hole|> print '[*] swarm starting at '+time.strftime(timeformat,time.localtime())
print ''
def end_banner():
print ''
print '[*] swarm shutting down at '+time.strftime(timeformat,time.localtime())
print ''<|fim▁end|> | timeformat='%H:%M:%S'
def begin_banner():
print '' |
<|file_name|>banner.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
timeformat='%H:%M:%S'
def begin_banner():
<|fim_middle|>
def end_banner():
print ''
print '[*] swarm shutting down at '+time.strftime(timeformat,time.localtime())
print ''<|fim▁end|> | print ''
print '[*] swarm starting at '+time.strftime(timeformat,time.localtime())
print '' |
<|file_name|>banner.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
timeformat='%H:%M:%S'
def begin_banner():
print ''
print '[*] swarm starting at '+time.strftime(timeformat,time.localtime())
print ''
def end_banner():
<|fim_middle|>
<|fim▁end|> | print ''
print '[*] swarm shutting down at '+time.strftime(timeformat,time.localtime())
print '' |
<|file_name|>banner.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
timeformat='%H:%M:%S'
def <|fim_middle|>():
print ''
print '[*] swarm starting at '+time.strftime(timeformat,time.localtime())
print ''
def end_banner():
print ''
print '[*] swarm shutting down at '+time.strftime(timeformat,time.localtime())
print ''<|fim▁end|> | begin_banner |
<|file_name|>banner.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
timeformat='%H:%M:%S'
def begin_banner():
print ''
print '[*] swarm starting at '+time.strftime(timeformat,time.localtime())
print ''
def <|fim_middle|>():
print ''
print '[*] swarm shutting down at '+time.strftime(timeformat,time.localtime())
print ''<|fim▁end|> | end_banner |
<|file_name|>generate_make.py<|end_file_name|><|fim▁begin|>"""
``editquality generate_make -h``
::
Code-generate Makefile from template and configuration
:Usage:
generate_make -h | --help
generate_make
[--config=<path>]
[--main=<filename>]
[--output=<path>]
[--templates=<path>]
[--debug]
:Options:
--config=<path> Directory to search for configuration files
[default: config/]
--main=<filename> Override to use a main template other than the
default [default: Makefile.j2]
--output=<path> Where to write the Makefile output.
[default: <stdout>]
--templates=<path> Directory to search for input templates.
[default: templates/]
--debug Print debug logging
"""
# TODO:
# * make API calls to learn things
# * ores/config has dict merge
# * survey dependency solvers
# https://github.com/ninja-build/ninja/wiki/List-of-generators-producing-ninja-build-files
# ** Still considering: scons, doit, drake, ninja, meson
# ** Don't like so far: waf
# * Where can we store information about samples?
# Original population rates; how we've distorted them.
import logging
import os.path
import sys
import docopt
from .. import config
from ..codegen import generate
logger = logging.getLogger(__name__)
def main(argv=None):
args = docopt.docopt(__doc__, argv=argv)
logging.basicConfig(
level=logging.DEBUG if args['--debug'] else logging.WARNING,
format='%(asctime)s %(levelname)s:%(name)s -- %(message)s'
)
config_path = args["--config"]
output_f = sys.stdout \
if args["--output"] == "<stdout>" \
else open(args["--output"], "w")
templates_path = args["--templates"]
main_template_path = args["--main"]<|fim▁hole|> # Join a filename to the default templates dir.
main_template_path = os.path.join(templates_path, main_template_path)
with open(main_template_path, "r") as f:
main_template = f.read()
variables = config.load_config(config_path)
output = generate.generate(variables, templates_path, main_template)
output_f.write(output)<|fim▁end|> | if not os.path.isabs(main_template_path): |
<|file_name|>generate_make.py<|end_file_name|><|fim▁begin|>"""
``editquality generate_make -h``
::
Code-generate Makefile from template and configuration
:Usage:
generate_make -h | --help
generate_make
[--config=<path>]
[--main=<filename>]
[--output=<path>]
[--templates=<path>]
[--debug]
:Options:
--config=<path> Directory to search for configuration files
[default: config/]
--main=<filename> Override to use a main template other than the
default [default: Makefile.j2]
--output=<path> Where to write the Makefile output.
[default: <stdout>]
--templates=<path> Directory to search for input templates.
[default: templates/]
--debug Print debug logging
"""
# TODO:
# * make API calls to learn things
# * ores/config has dict merge
# * survey dependency solvers
# https://github.com/ninja-build/ninja/wiki/List-of-generators-producing-ninja-build-files
# ** Still considering: scons, doit, drake, ninja, meson
# ** Don't like so far: waf
# * Where can we store information about samples?
# Original population rates; how we've distorted them.
import logging
import os.path
import sys
import docopt
from .. import config
from ..codegen import generate
logger = logging.getLogger(__name__)
def main(argv=None):
<|fim_middle|>
<|fim▁end|> | args = docopt.docopt(__doc__, argv=argv)
logging.basicConfig(
level=logging.DEBUG if args['--debug'] else logging.WARNING,
format='%(asctime)s %(levelname)s:%(name)s -- %(message)s'
)
config_path = args["--config"]
output_f = sys.stdout \
if args["--output"] == "<stdout>" \
else open(args["--output"], "w")
templates_path = args["--templates"]
main_template_path = args["--main"]
if not os.path.isabs(main_template_path):
# Join a filename to the default templates dir.
main_template_path = os.path.join(templates_path, main_template_path)
with open(main_template_path, "r") as f:
main_template = f.read()
variables = config.load_config(config_path)
output = generate.generate(variables, templates_path, main_template)
output_f.write(output) |
<|file_name|>generate_make.py<|end_file_name|><|fim▁begin|>"""
``editquality generate_make -h``
::
Code-generate Makefile from template and configuration
:Usage:
generate_make -h | --help
generate_make
[--config=<path>]
[--main=<filename>]
[--output=<path>]
[--templates=<path>]
[--debug]
:Options:
--config=<path> Directory to search for configuration files
[default: config/]
--main=<filename> Override to use a main template other than the
default [default: Makefile.j2]
--output=<path> Where to write the Makefile output.
[default: <stdout>]
--templates=<path> Directory to search for input templates.
[default: templates/]
--debug Print debug logging
"""
# TODO:
# * make API calls to learn things
# * ores/config has dict merge
# * survey dependency solvers
# https://github.com/ninja-build/ninja/wiki/List-of-generators-producing-ninja-build-files
# ** Still considering: scons, doit, drake, ninja, meson
# ** Don't like so far: waf
# * Where can we store information about samples?
# Original population rates; how we've distorted them.
import logging
import os.path
import sys
import docopt
from .. import config
from ..codegen import generate
logger = logging.getLogger(__name__)
def main(argv=None):
args = docopt.docopt(__doc__, argv=argv)
logging.basicConfig(
level=logging.DEBUG if args['--debug'] else logging.WARNING,
format='%(asctime)s %(levelname)s:%(name)s -- %(message)s'
)
config_path = args["--config"]
output_f = sys.stdout \
if args["--output"] == "<stdout>" \
else open(args["--output"], "w")
templates_path = args["--templates"]
main_template_path = args["--main"]
if not os.path.isabs(main_template_path):
# Join a filename to the default templates dir.
<|fim_middle|>
with open(main_template_path, "r") as f:
main_template = f.read()
variables = config.load_config(config_path)
output = generate.generate(variables, templates_path, main_template)
output_f.write(output)
<|fim▁end|> | main_template_path = os.path.join(templates_path, main_template_path) |
<|file_name|>generate_make.py<|end_file_name|><|fim▁begin|>"""
``editquality generate_make -h``
::
Code-generate Makefile from template and configuration
:Usage:
generate_make -h | --help
generate_make
[--config=<path>]
[--main=<filename>]
[--output=<path>]
[--templates=<path>]
[--debug]
:Options:
--config=<path> Directory to search for configuration files
[default: config/]
--main=<filename> Override to use a main template other than the
default [default: Makefile.j2]
--output=<path> Where to write the Makefile output.
[default: <stdout>]
--templates=<path> Directory to search for input templates.
[default: templates/]
--debug Print debug logging
"""
# TODO:
# * make API calls to learn things
# * ores/config has dict merge
# * survey dependency solvers
# https://github.com/ninja-build/ninja/wiki/List-of-generators-producing-ninja-build-files
# ** Still considering: scons, doit, drake, ninja, meson
# ** Don't like so far: waf
# * Where can we store information about samples?
# Original population rates; how we've distorted them.
import logging
import os.path
import sys
import docopt
from .. import config
from ..codegen import generate
logger = logging.getLogger(__name__)
def <|fim_middle|>(argv=None):
args = docopt.docopt(__doc__, argv=argv)
logging.basicConfig(
level=logging.DEBUG if args['--debug'] else logging.WARNING,
format='%(asctime)s %(levelname)s:%(name)s -- %(message)s'
)
config_path = args["--config"]
output_f = sys.stdout \
if args["--output"] == "<stdout>" \
else open(args["--output"], "w")
templates_path = args["--templates"]
main_template_path = args["--main"]
if not os.path.isabs(main_template_path):
# Join a filename to the default templates dir.
main_template_path = os.path.join(templates_path, main_template_path)
with open(main_template_path, "r") as f:
main_template = f.read()
variables = config.load_config(config_path)
output = generate.generate(variables, templates_path, main_template)
output_f.write(output)
<|fim▁end|> | main |
<|file_name|>time.py<|end_file_name|><|fim▁begin|>from .game import Board
for i in range(10):
Board.all()<|fim▁hole|><|fim▁end|> | print(i) |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))<|fim▁hole|> _progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()<|fim▁end|> | if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename): |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
<|fim_middle|>
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024)) |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
<|fim_middle|>
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG) |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
<|fim_middle|>
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | print(text)
logging.debug(text) |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
<|fim_middle|>
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | print('\033[31m{}\033[0m'.format(text))
logging.warning(text) |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
<|fim_middle|>
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | with open(config_path) as config_file:
return json.load(config_file) |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
<|fim_middle|>
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
<|fim_middle|>
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command)) |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
<|fim_middle|>
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1] |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
<|fim_middle|>
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
<|fim_middle|>
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
<|fim_middle|>
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | _create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
<|fim_middle|>
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | if not os.path.isdir(new_dir):
os.makedirs(new_dir) |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
<|fim_middle|>
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | return _get_hash(filename_a) == _get_hash(filename_b) |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
<|fim_middle|>
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest() |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
<|fim_middle|>
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | _create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name))) |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
<|fim_middle|>
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file) |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
<|fim_middle|>
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename)) |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
<|fim_middle|>
if __name__ == "__main__":
_main()
<|fim▁end|> | return datetime.datetime.now().strftime('%Y%m%d_%H%M%S') |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
<|fim_middle|>
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir) |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
<|fim_middle|>
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | raise SystemExit('failed to execute: {}'.format(command)) |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
<|fim_middle|>
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | _progress_warning('multiple modify times: {}'.format(modify_times)) |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
<|fim_middle|>
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir) |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
<|fim_middle|>
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
<|fim_middle|>
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | _progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
<|fim_middle|>
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | os.makedirs(new_dir) |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
<|fim_middle|>
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | _progress('deleting {}'.format(base_output_file))
os.remove(base_output_file) |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
<|fim_middle|>
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename)) |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
<|fim_middle|>
<|fim▁end|> | _main() |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def <|fim_middle|>():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | _main |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def <|fim_middle|>():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | _init_logging |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def <|fim_middle|>(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | _progress |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def <|fim_middle|>(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | _progress_warning |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def <|fim_middle|>(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | _load_config |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def <|fim_middle|>(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | _download_gtfs |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def <|fim_middle|>(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | _execute_command |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def <|fim_middle|>(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | _get_modify_date |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def <|fim_middle|>(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | _get_modify_times |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def <|fim_middle|>(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | _get_q_dir |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def <|fim_middle|>(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | _rename_gtfs_zip |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def <|fim_middle|>(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | _create_dir |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def <|fim_middle|>(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | _compare_files |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip)
gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def <|fim_middle|>(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()
<|fim▁end|> | _get_hash |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.