prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>TurtleCommands.py<|end_file_name|><|fim▁begin|>__author__ = 'Alex'
from Movement import Movement
class BaseCommand:
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'unknown'
self.m = movement
def execute(selfself):<|fim_middle|>
class Forward(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'forward'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Reverse(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'reverse'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Left(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'left'
self.m = movement
def execute(self):
self.m.turnDegrees(-90)
class Right(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'right'
self.m = movement
def execute(self):
self.m.turnDegrees(90)
<|fim▁end|> | pass |
<|file_name|>TurtleCommands.py<|end_file_name|><|fim▁begin|>__author__ = 'Alex'
from Movement import Movement
class BaseCommand:
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'unknown'
self.m = movement
def execute(selfself):pass
class Forward(BaseCommand):
<|fim_middle|>
class Reverse(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'reverse'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Left(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'left'
self.m = movement
def execute(self):
self.m.turnDegrees(-90)
class Right(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'right'
self.m = movement
def execute(self):
self.m.turnDegrees(90)
<|fim▁end|> | def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'forward'
self.m = movement
def execute(self):
self.m.moveCM(10) |
<|file_name|>TurtleCommands.py<|end_file_name|><|fim▁begin|>__author__ = 'Alex'
from Movement import Movement
class BaseCommand:
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'unknown'
self.m = movement
def execute(selfself):pass
class Forward(BaseCommand):
def __init__(self, movement):
<|fim_middle|>
def execute(self):
self.m.moveCM(10)
class Reverse(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'reverse'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Left(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'left'
self.m = movement
def execute(self):
self.m.turnDegrees(-90)
class Right(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'right'
self.m = movement
def execute(self):
self.m.turnDegrees(90)
<|fim▁end|> | assert isinstance(movement, Movement)
self.name = 'forward'
self.m = movement |
<|file_name|>TurtleCommands.py<|end_file_name|><|fim▁begin|>__author__ = 'Alex'
from Movement import Movement
class BaseCommand:
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'unknown'
self.m = movement
def execute(selfself):pass
class Forward(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'forward'
self.m = movement
def execute(self):
<|fim_middle|>
class Reverse(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'reverse'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Left(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'left'
self.m = movement
def execute(self):
self.m.turnDegrees(-90)
class Right(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'right'
self.m = movement
def execute(self):
self.m.turnDegrees(90)
<|fim▁end|> | self.m.moveCM(10) |
<|file_name|>TurtleCommands.py<|end_file_name|><|fim▁begin|>__author__ = 'Alex'
from Movement import Movement
class BaseCommand:
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'unknown'
self.m = movement
def execute(selfself):pass
class Forward(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'forward'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Reverse(BaseCommand):
<|fim_middle|>
class Left(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'left'
self.m = movement
def execute(self):
self.m.turnDegrees(-90)
class Right(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'right'
self.m = movement
def execute(self):
self.m.turnDegrees(90)
<|fim▁end|> | def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'reverse'
self.m = movement
def execute(self):
self.m.moveCM(10) |
<|file_name|>TurtleCommands.py<|end_file_name|><|fim▁begin|>__author__ = 'Alex'
from Movement import Movement
class BaseCommand:
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'unknown'
self.m = movement
def execute(selfself):pass
class Forward(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'forward'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Reverse(BaseCommand):
def __init__(self, movement):
<|fim_middle|>
def execute(self):
self.m.moveCM(10)
class Left(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'left'
self.m = movement
def execute(self):
self.m.turnDegrees(-90)
class Right(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'right'
self.m = movement
def execute(self):
self.m.turnDegrees(90)
<|fim▁end|> | assert isinstance(movement, Movement)
self.name = 'reverse'
self.m = movement |
<|file_name|>TurtleCommands.py<|end_file_name|><|fim▁begin|>__author__ = 'Alex'
from Movement import Movement
class BaseCommand:
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'unknown'
self.m = movement
def execute(selfself):pass
class Forward(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'forward'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Reverse(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'reverse'
self.m = movement
def execute(self):
<|fim_middle|>
class Left(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'left'
self.m = movement
def execute(self):
self.m.turnDegrees(-90)
class Right(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'right'
self.m = movement
def execute(self):
self.m.turnDegrees(90)
<|fim▁end|> | self.m.moveCM(10) |
<|file_name|>TurtleCommands.py<|end_file_name|><|fim▁begin|>__author__ = 'Alex'
from Movement import Movement
class BaseCommand:
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'unknown'
self.m = movement
def execute(selfself):pass
class Forward(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'forward'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Reverse(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'reverse'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Left(BaseCommand):
<|fim_middle|>
class Right(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'right'
self.m = movement
def execute(self):
self.m.turnDegrees(90)
<|fim▁end|> | def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'left'
self.m = movement
def execute(self):
self.m.turnDegrees(-90) |
<|file_name|>TurtleCommands.py<|end_file_name|><|fim▁begin|>__author__ = 'Alex'
from Movement import Movement
class BaseCommand:
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'unknown'
self.m = movement
def execute(selfself):pass
class Forward(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'forward'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Reverse(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'reverse'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Left(BaseCommand):
def __init__(self, movement):
<|fim_middle|>
def execute(self):
self.m.turnDegrees(-90)
class Right(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'right'
self.m = movement
def execute(self):
self.m.turnDegrees(90)
<|fim▁end|> | assert isinstance(movement, Movement)
self.name = 'left'
self.m = movement |
<|file_name|>TurtleCommands.py<|end_file_name|><|fim▁begin|>__author__ = 'Alex'
from Movement import Movement
class BaseCommand:
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'unknown'
self.m = movement
def execute(selfself):pass
class Forward(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'forward'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Reverse(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'reverse'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Left(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'left'
self.m = movement
def execute(self):
<|fim_middle|>
class Right(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'right'
self.m = movement
def execute(self):
self.m.turnDegrees(90)
<|fim▁end|> | self.m.turnDegrees(-90) |
<|file_name|>TurtleCommands.py<|end_file_name|><|fim▁begin|>__author__ = 'Alex'
from Movement import Movement
class BaseCommand:
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'unknown'
self.m = movement
def execute(selfself):pass
class Forward(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'forward'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Reverse(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'reverse'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Left(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'left'
self.m = movement
def execute(self):
self.m.turnDegrees(-90)
class Right(BaseCommand):
<|fim_middle|>
<|fim▁end|> | def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'right'
self.m = movement
def execute(self):
self.m.turnDegrees(90) |
<|file_name|>TurtleCommands.py<|end_file_name|><|fim▁begin|>__author__ = 'Alex'
from Movement import Movement
class BaseCommand:
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'unknown'
self.m = movement
def execute(selfself):pass
class Forward(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'forward'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Reverse(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'reverse'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Left(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'left'
self.m = movement
def execute(self):
self.m.turnDegrees(-90)
class Right(BaseCommand):
def __init__(self, movement):
<|fim_middle|>
def execute(self):
self.m.turnDegrees(90)
<|fim▁end|> | assert isinstance(movement, Movement)
self.name = 'right'
self.m = movement |
<|file_name|>TurtleCommands.py<|end_file_name|><|fim▁begin|>__author__ = 'Alex'
from Movement import Movement
class BaseCommand:
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'unknown'
self.m = movement
def execute(selfself):pass
class Forward(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'forward'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Reverse(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'reverse'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Left(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'left'
self.m = movement
def execute(self):
self.m.turnDegrees(-90)
class Right(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'right'
self.m = movement
def execute(self):
<|fim_middle|>
<|fim▁end|> | self.m.turnDegrees(90) |
<|file_name|>TurtleCommands.py<|end_file_name|><|fim▁begin|>__author__ = 'Alex'
from Movement import Movement
class BaseCommand:
def <|fim_middle|>(self, movement):
assert isinstance(movement, Movement)
self.name = 'unknown'
self.m = movement
def execute(selfself):pass
class Forward(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'forward'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Reverse(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'reverse'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Left(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'left'
self.m = movement
def execute(self):
self.m.turnDegrees(-90)
class Right(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'right'
self.m = movement
def execute(self):
self.m.turnDegrees(90)
<|fim▁end|> | __init__ |
<|file_name|>TurtleCommands.py<|end_file_name|><|fim▁begin|>__author__ = 'Alex'
from Movement import Movement
class BaseCommand:
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'unknown'
self.m = movement
def <|fim_middle|>(selfself):pass
class Forward(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'forward'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Reverse(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'reverse'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Left(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'left'
self.m = movement
def execute(self):
self.m.turnDegrees(-90)
class Right(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'right'
self.m = movement
def execute(self):
self.m.turnDegrees(90)
<|fim▁end|> | execute |
<|file_name|>TurtleCommands.py<|end_file_name|><|fim▁begin|>__author__ = 'Alex'
from Movement import Movement
class BaseCommand:
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'unknown'
self.m = movement
def execute(selfself):pass
class Forward(BaseCommand):
def <|fim_middle|>(self, movement):
assert isinstance(movement, Movement)
self.name = 'forward'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Reverse(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'reverse'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Left(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'left'
self.m = movement
def execute(self):
self.m.turnDegrees(-90)
class Right(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'right'
self.m = movement
def execute(self):
self.m.turnDegrees(90)
<|fim▁end|> | __init__ |
<|file_name|>TurtleCommands.py<|end_file_name|><|fim▁begin|>__author__ = 'Alex'
from Movement import Movement
class BaseCommand:
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'unknown'
self.m = movement
def execute(selfself):pass
class Forward(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'forward'
self.m = movement
def <|fim_middle|>(self):
self.m.moveCM(10)
class Reverse(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'reverse'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Left(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'left'
self.m = movement
def execute(self):
self.m.turnDegrees(-90)
class Right(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'right'
self.m = movement
def execute(self):
self.m.turnDegrees(90)
<|fim▁end|> | execute |
<|file_name|>TurtleCommands.py<|end_file_name|><|fim▁begin|>__author__ = 'Alex'
from Movement import Movement
class BaseCommand:
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'unknown'
self.m = movement
def execute(selfself):pass
class Forward(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'forward'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Reverse(BaseCommand):
def <|fim_middle|>(self, movement):
assert isinstance(movement, Movement)
self.name = 'reverse'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Left(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'left'
self.m = movement
def execute(self):
self.m.turnDegrees(-90)
class Right(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'right'
self.m = movement
def execute(self):
self.m.turnDegrees(90)
<|fim▁end|> | __init__ |
<|file_name|>TurtleCommands.py<|end_file_name|><|fim▁begin|>__author__ = 'Alex'
from Movement import Movement
class BaseCommand:
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'unknown'
self.m = movement
def execute(selfself):pass
class Forward(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'forward'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Reverse(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'reverse'
self.m = movement
def <|fim_middle|>(self):
self.m.moveCM(10)
class Left(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'left'
self.m = movement
def execute(self):
self.m.turnDegrees(-90)
class Right(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'right'
self.m = movement
def execute(self):
self.m.turnDegrees(90)
<|fim▁end|> | execute |
<|file_name|>TurtleCommands.py<|end_file_name|><|fim▁begin|>__author__ = 'Alex'
from Movement import Movement
class BaseCommand:
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'unknown'
self.m = movement
def execute(selfself):pass
class Forward(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'forward'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Reverse(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'reverse'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Left(BaseCommand):
def <|fim_middle|>(self, movement):
assert isinstance(movement, Movement)
self.name = 'left'
self.m = movement
def execute(self):
self.m.turnDegrees(-90)
class Right(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'right'
self.m = movement
def execute(self):
self.m.turnDegrees(90)
<|fim▁end|> | __init__ |
<|file_name|>TurtleCommands.py<|end_file_name|><|fim▁begin|>__author__ = 'Alex'
from Movement import Movement
class BaseCommand:
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'unknown'
self.m = movement
def execute(selfself):pass
class Forward(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'forward'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Reverse(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'reverse'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Left(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'left'
self.m = movement
def <|fim_middle|>(self):
self.m.turnDegrees(-90)
class Right(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'right'
self.m = movement
def execute(self):
self.m.turnDegrees(90)
<|fim▁end|> | execute |
<|file_name|>TurtleCommands.py<|end_file_name|><|fim▁begin|>__author__ = 'Alex'
from Movement import Movement
class BaseCommand:
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'unknown'
self.m = movement
def execute(selfself):pass
class Forward(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'forward'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Reverse(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'reverse'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Left(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'left'
self.m = movement
def execute(self):
self.m.turnDegrees(-90)
class Right(BaseCommand):
def <|fim_middle|>(self, movement):
assert isinstance(movement, Movement)
self.name = 'right'
self.m = movement
def execute(self):
self.m.turnDegrees(90)
<|fim▁end|> | __init__ |
<|file_name|>TurtleCommands.py<|end_file_name|><|fim▁begin|>__author__ = 'Alex'
from Movement import Movement
class BaseCommand:
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'unknown'
self.m = movement
def execute(selfself):pass
class Forward(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'forward'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Reverse(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'reverse'
self.m = movement
def execute(self):
self.m.moveCM(10)
class Left(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'left'
self.m = movement
def execute(self):
self.m.turnDegrees(-90)
class Right(BaseCommand):
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'right'
self.m = movement
def <|fim_middle|>(self):
self.m.turnDegrees(90)
<|fim▁end|> | execute |
<|file_name|>grove_electricity_sensor.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# GrovePi Example for using the Grove Electricity Sensor (http://www.seeedstudio.com/wiki/Grove_-_Electricity_Sensor)
#
# The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi
#
# Have a question about this example? Ask on the forums here: http://forum.dexterindustries.com/c/grovepi
#
'''
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2015 Dexter Industries<|fim▁hole|>in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''
import time
import grovepi
# Connect the Grove Electricity Sensor to analog port A0
# SIG,NC,NC,GND
sensor = 0
grovepi.pinMode(sensor,"INPUT")
# Vcc of the grove interface is normally 5v
grove_vcc = 5
while True:
try:
# Get sensor value
sensor_value = grovepi.analogRead(sensor)
# Calculate amplitude current (mA)
amplitude_current = (float)(sensor_value / 1024 * grove_vcc / 800 * 2000000)
# Calculate effective value (mA)
effective_value = amplitude_current / 1.414
# minimum_current = 1 / 1024 * grove_vcc / 800 * 2000000 / 1.414 = 8.6(mA)
# Only for sinusoidal alternating current
print("sensor_value", sensor_value)
print("The amplitude of the current is", amplitude_current, "mA")
print("The effective value of the current is", effective_value, "mA")
time.sleep(1)
except IOError:
print ("Error")<|fim▁end|> |
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal |
<|file_name|>construct_erc2-chromatin15state-all_files.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
import sys
import os
output_dir = "erc2-chromatin15state-all-files"
if not os.path.exists(output_dir):
sys.stderr.write("Creating dir [%s]...\n" % (output_dir))
os.makedirs(output_dir)
prefix = "/home/cbreeze/for_Alex"
suffix = "_15_coreMarks_mnemonics.bed"
marks = [ '1_TssA',
'2_TssAFlnk',
'3_TxFlnk',
'4_Tx',
'5_TxWk',
'6_EnhG',
'7_Enh',
'8_ZNF/Rpts',
'9_Het',
'10_TssBiv',
'11_BivFlnk',
'12_EnhBiv',
'13_ReprPC',
'14_ReprPCWk',
'15_Quies' ]
all = [ 'E001',
'E002',
'E003',
'E004',
'E005',
'E006',
'E007',
'E008',
'E009',
'E010',
'E011',
'E012',
'E013',
'E014',
'E015',
'E016',
'E017',
'E018',
'E019',
'E020',
'E021',
'E022',
'E023',
'E024',
'E025',
'E026',
'E027',
'E028',
'E029',
'E030',
'E031',
'E032',
'E033',
'E034',
'E035',
'E036',
'E037',
'E038',
'E039',
'E040',
'E041',
'E042',
'E043',
'E044',
'E045',
'E046',
'E047',
'E048',
'E049',
'E050',
'E051',
'E052',
'E053',
'E054',
'E055',
'E056',
'E057',
'E058',
'E059',
'E061',
'E062',
'E063',
'E065',
'E066',
'E067',
'E068',
'E069',
'E070',
'E071',
'E072',
'E073',
'E074',
'E075',
'E076',
'E077',
'E078',
'E079',
'E080',
'E081',
'E082',
'E083',
'E084',
'E085',
'E086',
'E087',
'E088',
'E089',
'E090',
'E091',
'E092',
'E093',
'E094',
'E095',
'E096',
'E097',
'E098',
'E099',
'E100',
'E101',
'E102',
'E103',
'E104',
'E105',
'E106',
'E107',
'E108',
'E109',<|fim▁hole|> 'E114',
'E115',
'E116',
'E117',
'E118',
'E119',
'E120',
'E121',
'E122',
'E123',
'E124',
'E125',
'E126',
'E127',
'E128',
'E129' ]
# prefix, suffix, marks, all
for sample in all:
fns = {}
fhs = {}
# set up output file handles for all combinations of per-sample and marks
for mark in marks:
fns[mark] = os.path.join(output_dir, "%s_%s.bed" % (sample, mark.replace('/', '-')))
sys.stderr.write("Setting up output handle to [%s]...\n" % (fns[mark]))
fhs[mark] = open(fns[mark], "w")
# split per-sample mnemonics to per-sample, per-mark file
psm_fn = "%s/%s%s" % (prefix, sample, suffix)
sys.stderr.write("Reading PSM [%s]...\n" % (psm_fn))
with open(psm_fn, "r") as psm_fh:
for line in psm_fh:
(chr, start, stop, state_call) = line.strip().split('\t')
fhs[state_call].write('\t'.join([chr, start, stop]) + '\n')
# close handles
for mark in marks:
sys.stderr.write("Closing output handle to [%s]...\n" % (fns[mark]))
fhs[mark].close()
fns[mark] = None
fhs[mark] = None<|fim▁end|> | 'E110',
'E111',
'E112',
'E113', |
<|file_name|>construct_erc2-chromatin15state-all_files.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
import sys
import os
output_dir = "erc2-chromatin15state-all-files"
if not os.path.exists(output_dir):
<|fim_middle|>
prefix = "/home/cbreeze/for_Alex"
suffix = "_15_coreMarks_mnemonics.bed"
marks = [ '1_TssA',
'2_TssAFlnk',
'3_TxFlnk',
'4_Tx',
'5_TxWk',
'6_EnhG',
'7_Enh',
'8_ZNF/Rpts',
'9_Het',
'10_TssBiv',
'11_BivFlnk',
'12_EnhBiv',
'13_ReprPC',
'14_ReprPCWk',
'15_Quies' ]
all = [ 'E001',
'E002',
'E003',
'E004',
'E005',
'E006',
'E007',
'E008',
'E009',
'E010',
'E011',
'E012',
'E013',
'E014',
'E015',
'E016',
'E017',
'E018',
'E019',
'E020',
'E021',
'E022',
'E023',
'E024',
'E025',
'E026',
'E027',
'E028',
'E029',
'E030',
'E031',
'E032',
'E033',
'E034',
'E035',
'E036',
'E037',
'E038',
'E039',
'E040',
'E041',
'E042',
'E043',
'E044',
'E045',
'E046',
'E047',
'E048',
'E049',
'E050',
'E051',
'E052',
'E053',
'E054',
'E055',
'E056',
'E057',
'E058',
'E059',
'E061',
'E062',
'E063',
'E065',
'E066',
'E067',
'E068',
'E069',
'E070',
'E071',
'E072',
'E073',
'E074',
'E075',
'E076',
'E077',
'E078',
'E079',
'E080',
'E081',
'E082',
'E083',
'E084',
'E085',
'E086',
'E087',
'E088',
'E089',
'E090',
'E091',
'E092',
'E093',
'E094',
'E095',
'E096',
'E097',
'E098',
'E099',
'E100',
'E101',
'E102',
'E103',
'E104',
'E105',
'E106',
'E107',
'E108',
'E109',
'E110',
'E111',
'E112',
'E113',
'E114',
'E115',
'E116',
'E117',
'E118',
'E119',
'E120',
'E121',
'E122',
'E123',
'E124',
'E125',
'E126',
'E127',
'E128',
'E129' ]
# prefix, suffix, marks, all
for sample in all:
fns = {}
fhs = {}
# set up output file handles for all combinations of per-sample and marks
for mark in marks:
fns[mark] = os.path.join(output_dir, "%s_%s.bed" % (sample, mark.replace('/', '-')))
sys.stderr.write("Setting up output handle to [%s]...\n" % (fns[mark]))
fhs[mark] = open(fns[mark], "w")
# split per-sample mnemonics to per-sample, per-mark file
psm_fn = "%s/%s%s" % (prefix, sample, suffix)
sys.stderr.write("Reading PSM [%s]...\n" % (psm_fn))
with open(psm_fn, "r") as psm_fh:
for line in psm_fh:
(chr, start, stop, state_call) = line.strip().split('\t')
fhs[state_call].write('\t'.join([chr, start, stop]) + '\n')
# close handles
for mark in marks:
sys.stderr.write("Closing output handle to [%s]...\n" % (fns[mark]))
fhs[mark].close()
fns[mark] = None
fhs[mark] = None<|fim▁end|> | sys.stderr.write("Creating dir [%s]...\n" % (output_dir))
os.makedirs(output_dir) |
<|file_name|>mailgun.py<|end_file_name|><|fim▁begin|><|fim▁hole|> data={"from": "Mailgun Sandbox <[email protected]>",
"to": "nick <[email protected]>",
"subject": "Hello nick",
"text": "Congratulations nick, you just sent an email with Mailgun! You are truly awesome! You can see a record of this email in your logs: https://mailgun.com/cp/log . You can send up to 300 emails/day from this sandbox server. Next, you should add your own domain so you can send 10,000 emails/month for free."})
# cURL command to send mail aith API key
# curl -s --user 'api:key-679dc79b890e700f11f001a6bf86f4a1' \
# https://api.mailgun.net/v3/mail.pdxpixel.com/messages \
# -F from='Excited User <[email protected]>' \
# -F [email protected] \
# -F subject='Hello' \
# -F text='Testing some Mailgun awesomness!'<|fim▁end|> | def send_simple_message():
return requests.post(
"https://api.mailgun.net/v3/sandbox049ff464a4d54974bb0143935f9577ef.mailgun.org/messages",
auth=("api", "key-679dc79b890e700f11f001a6bf86f4a1"), |
<|file_name|>mailgun.py<|end_file_name|><|fim▁begin|>def send_simple_message():
<|fim_middle|>
# cURL command to send mail aith API key
# curl -s --user 'api:key-679dc79b890e700f11f001a6bf86f4a1' \
# https://api.mailgun.net/v3/mail.pdxpixel.com/messages \
# -F from='Excited User <[email protected]>' \
# -F [email protected] \
# -F subject='Hello' \
# -F text='Testing some Mailgun awesomness!'
<|fim▁end|> | return requests.post(
"https://api.mailgun.net/v3/sandbox049ff464a4d54974bb0143935f9577ef.mailgun.org/messages",
auth=("api", "key-679dc79b890e700f11f001a6bf86f4a1"),
data={"from": "Mailgun Sandbox <[email protected]>",
"to": "nick <[email protected]>",
"subject": "Hello nick",
"text": "Congratulations nick, you just sent an email with Mailgun! You are truly awesome! You can see a record of this email in your logs: https://mailgun.com/cp/log . You can send up to 300 emails/day from this sandbox server. Next, you should add your own domain so you can send 10,000 emails/month for free."}) |
<|file_name|>mailgun.py<|end_file_name|><|fim▁begin|>def <|fim_middle|>():
return requests.post(
"https://api.mailgun.net/v3/sandbox049ff464a4d54974bb0143935f9577ef.mailgun.org/messages",
auth=("api", "key-679dc79b890e700f11f001a6bf86f4a1"),
data={"from": "Mailgun Sandbox <[email protected]>",
"to": "nick <[email protected]>",
"subject": "Hello nick",
"text": "Congratulations nick, you just sent an email with Mailgun! You are truly awesome! You can see a record of this email in your logs: https://mailgun.com/cp/log . You can send up to 300 emails/day from this sandbox server. Next, you should add your own domain so you can send 10,000 emails/month for free."})
# cURL command to send mail aith API key
# curl -s --user 'api:key-679dc79b890e700f11f001a6bf86f4a1' \
# https://api.mailgun.net/v3/mail.pdxpixel.com/messages \
# -F from='Excited User <[email protected]>' \
# -F [email protected] \
# -F subject='Hello' \
# -F text='Testing some Mailgun awesomness!'
<|fim▁end|> | send_simple_message |
<|file_name|>cmss.py<|end_file_name|><|fim▁begin|>import win32pipe
import win32console
import win32process
import time
import win32con
import codecs
import ctypes
user32 = ctypes.windll.user32
CONQUE_WINDOWS_VK = {
'3' : win32con.VK_CANCEL,
'8' : win32con.VK_BACK,
'9' : win32con.VK_TAB,
'12' : win32con.VK_CLEAR,
'13' : win32con.VK_RETURN,
'17' : win32con.VK_CONTROL,
'20' : win32con.VK_CAPITAL,
'27' : win32con.VK_ESCAPE,
'28' : win32con.VK_CONVERT,
'35' : win32con.VK_END,
'36' : win32con.VK_HOME,
'37' : win32con.VK_LEFT,
'38' : win32con.VK_UP,
'39' : win32con.VK_RIGHT,
'40' : win32con.VK_DOWN,
'45' : win32con.VK_INSERT,
'46' : win32con.VK_DELETE,
'47' : win32con.VK_HELP
}
def make_input_key(c, control_key_state=None):
kc = win32console.PyINPUT_RECORDType (win32console.KEY_EVENT)
kc.KeyDown = True
kc.RepeatCount = 1
cnum = ord(c)
if cnum == 3:
pid_list = win32console.GetConsoleProcessList()
win32console.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, 0)
return
else:
kc.Char = unicode(c)
if str(cnum) in CONQUE_WINDOWS_VK:
kc.VirtualKeyCode = CONQUE_WINDOWS_VK[str(cnum)]
else:
kc.VirtualKeyCode = ctypes.windll.user32.VkKeyScanA(cnum)
#kc.VirtualKeyCode = ctypes.windll.user32.VkKeyScanA(cnum+96)
#kc.ControlKeyState = win32con.LEFT_CTRL_PRESSED
return kc
#win32console.AttachConsole()
coord = win32console.PyCOORDType
con_stdout = win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE)
con_stdin = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE)
flags = win32process.NORMAL_PRIORITY_CLASS
si = win32process.STARTUPINFO()
si.dwFlags |= win32con.STARTF_USESHOWWINDOW
(handle1, handle2, i1, i2) = win32process.CreateProcess(None, "cmd.exe", None, None, 0, flags, None, '.', si)
time.sleep(1)
#size = con_stdout.GetConsoleScreenBufferInfo()['Window']
# with codecs.open("log.txt", "w", "utf8") as f:
# for i in xrange(0, size.Bottom):
# f.write(con_stdout.ReadConsoleOutputCharacter(size.Right+1, coord(0, i)))
# f.write("\n")
import socket
<|fim▁hole|>PORT = 5554
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(1)
(sc, scname) = s.accept()
while True:
msg = sc.recv(1)
if ord(msg) == 0:
break
keys = [make_input_key(msg)]
if keys:
con_stdin.WriteConsoleInput(keys)
win32process.TerminateProcess(handle1, 0)<|fim▁end|> |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = "127.0.0.1"
|
<|file_name|>cmss.py<|end_file_name|><|fim▁begin|>import win32pipe
import win32console
import win32process
import time
import win32con
import codecs
import ctypes
user32 = ctypes.windll.user32
CONQUE_WINDOWS_VK = {
'3' : win32con.VK_CANCEL,
'8' : win32con.VK_BACK,
'9' : win32con.VK_TAB,
'12' : win32con.VK_CLEAR,
'13' : win32con.VK_RETURN,
'17' : win32con.VK_CONTROL,
'20' : win32con.VK_CAPITAL,
'27' : win32con.VK_ESCAPE,
'28' : win32con.VK_CONVERT,
'35' : win32con.VK_END,
'36' : win32con.VK_HOME,
'37' : win32con.VK_LEFT,
'38' : win32con.VK_UP,
'39' : win32con.VK_RIGHT,
'40' : win32con.VK_DOWN,
'45' : win32con.VK_INSERT,
'46' : win32con.VK_DELETE,
'47' : win32con.VK_HELP
}
def make_input_key(c, control_key_state=None):
<|fim_middle|>
#win32console.AttachConsole()
coord = win32console.PyCOORDType
con_stdout = win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE)
con_stdin = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE)
flags = win32process.NORMAL_PRIORITY_CLASS
si = win32process.STARTUPINFO()
si.dwFlags |= win32con.STARTF_USESHOWWINDOW
(handle1, handle2, i1, i2) = win32process.CreateProcess(None, "cmd.exe", None, None, 0, flags, None, '.', si)
time.sleep(1)
#size = con_stdout.GetConsoleScreenBufferInfo()['Window']
# with codecs.open("log.txt", "w", "utf8") as f:
# for i in xrange(0, size.Bottom):
# f.write(con_stdout.ReadConsoleOutputCharacter(size.Right+1, coord(0, i)))
# f.write("\n")
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = "127.0.0.1"
PORT = 5554
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(1)
(sc, scname) = s.accept()
while True:
msg = sc.recv(1)
if ord(msg) == 0:
break
keys = [make_input_key(msg)]
if keys:
con_stdin.WriteConsoleInput(keys)
win32process.TerminateProcess(handle1, 0)<|fim▁end|> | kc = win32console.PyINPUT_RECORDType (win32console.KEY_EVENT)
kc.KeyDown = True
kc.RepeatCount = 1
cnum = ord(c)
if cnum == 3:
pid_list = win32console.GetConsoleProcessList()
win32console.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, 0)
return
else:
kc.Char = unicode(c)
if str(cnum) in CONQUE_WINDOWS_VK:
kc.VirtualKeyCode = CONQUE_WINDOWS_VK[str(cnum)]
else:
kc.VirtualKeyCode = ctypes.windll.user32.VkKeyScanA(cnum)
#kc.VirtualKeyCode = ctypes.windll.user32.VkKeyScanA(cnum+96)
#kc.ControlKeyState = win32con.LEFT_CTRL_PRESSED
return kc |
<|file_name|>cmss.py<|end_file_name|><|fim▁begin|>import win32pipe
import win32console
import win32process
import time
import win32con
import codecs
import ctypes
user32 = ctypes.windll.user32
CONQUE_WINDOWS_VK = {
'3' : win32con.VK_CANCEL,
'8' : win32con.VK_BACK,
'9' : win32con.VK_TAB,
'12' : win32con.VK_CLEAR,
'13' : win32con.VK_RETURN,
'17' : win32con.VK_CONTROL,
'20' : win32con.VK_CAPITAL,
'27' : win32con.VK_ESCAPE,
'28' : win32con.VK_CONVERT,
'35' : win32con.VK_END,
'36' : win32con.VK_HOME,
'37' : win32con.VK_LEFT,
'38' : win32con.VK_UP,
'39' : win32con.VK_RIGHT,
'40' : win32con.VK_DOWN,
'45' : win32con.VK_INSERT,
'46' : win32con.VK_DELETE,
'47' : win32con.VK_HELP
}
def make_input_key(c, control_key_state=None):
kc = win32console.PyINPUT_RECORDType (win32console.KEY_EVENT)
kc.KeyDown = True
kc.RepeatCount = 1
cnum = ord(c)
if cnum == 3:
<|fim_middle|>
else:
kc.Char = unicode(c)
if str(cnum) in CONQUE_WINDOWS_VK:
kc.VirtualKeyCode = CONQUE_WINDOWS_VK[str(cnum)]
else:
kc.VirtualKeyCode = ctypes.windll.user32.VkKeyScanA(cnum)
#kc.VirtualKeyCode = ctypes.windll.user32.VkKeyScanA(cnum+96)
#kc.ControlKeyState = win32con.LEFT_CTRL_PRESSED
return kc
#win32console.AttachConsole()
coord = win32console.PyCOORDType
con_stdout = win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE)
con_stdin = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE)
flags = win32process.NORMAL_PRIORITY_CLASS
si = win32process.STARTUPINFO()
si.dwFlags |= win32con.STARTF_USESHOWWINDOW
(handle1, handle2, i1, i2) = win32process.CreateProcess(None, "cmd.exe", None, None, 0, flags, None, '.', si)
time.sleep(1)
#size = con_stdout.GetConsoleScreenBufferInfo()['Window']
# with codecs.open("log.txt", "w", "utf8") as f:
# for i in xrange(0, size.Bottom):
# f.write(con_stdout.ReadConsoleOutputCharacter(size.Right+1, coord(0, i)))
# f.write("\n")
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = "127.0.0.1"
PORT = 5554
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(1)
(sc, scname) = s.accept()
while True:
msg = sc.recv(1)
if ord(msg) == 0:
break
keys = [make_input_key(msg)]
if keys:
con_stdin.WriteConsoleInput(keys)
win32process.TerminateProcess(handle1, 0)<|fim▁end|> | pid_list = win32console.GetConsoleProcessList()
win32console.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, 0)
return |
<|file_name|>cmss.py<|end_file_name|><|fim▁begin|>import win32pipe
import win32console
import win32process
import time
import win32con
import codecs
import ctypes
user32 = ctypes.windll.user32
CONQUE_WINDOWS_VK = {
'3' : win32con.VK_CANCEL,
'8' : win32con.VK_BACK,
'9' : win32con.VK_TAB,
'12' : win32con.VK_CLEAR,
'13' : win32con.VK_RETURN,
'17' : win32con.VK_CONTROL,
'20' : win32con.VK_CAPITAL,
'27' : win32con.VK_ESCAPE,
'28' : win32con.VK_CONVERT,
'35' : win32con.VK_END,
'36' : win32con.VK_HOME,
'37' : win32con.VK_LEFT,
'38' : win32con.VK_UP,
'39' : win32con.VK_RIGHT,
'40' : win32con.VK_DOWN,
'45' : win32con.VK_INSERT,
'46' : win32con.VK_DELETE,
'47' : win32con.VK_HELP
}
def make_input_key(c, control_key_state=None):
kc = win32console.PyINPUT_RECORDType (win32console.KEY_EVENT)
kc.KeyDown = True
kc.RepeatCount = 1
cnum = ord(c)
if cnum == 3:
pid_list = win32console.GetConsoleProcessList()
win32console.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, 0)
return
else:
<|fim_middle|>
return kc
#win32console.AttachConsole()
coord = win32console.PyCOORDType
con_stdout = win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE)
con_stdin = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE)
flags = win32process.NORMAL_PRIORITY_CLASS
si = win32process.STARTUPINFO()
si.dwFlags |= win32con.STARTF_USESHOWWINDOW
(handle1, handle2, i1, i2) = win32process.CreateProcess(None, "cmd.exe", None, None, 0, flags, None, '.', si)
time.sleep(1)
#size = con_stdout.GetConsoleScreenBufferInfo()['Window']
# with codecs.open("log.txt", "w", "utf8") as f:
# for i in xrange(0, size.Bottom):
# f.write(con_stdout.ReadConsoleOutputCharacter(size.Right+1, coord(0, i)))
# f.write("\n")
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = "127.0.0.1"
PORT = 5554
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(1)
(sc, scname) = s.accept()
while True:
msg = sc.recv(1)
if ord(msg) == 0:
break
keys = [make_input_key(msg)]
if keys:
con_stdin.WriteConsoleInput(keys)
win32process.TerminateProcess(handle1, 0)<|fim▁end|> | kc.Char = unicode(c)
if str(cnum) in CONQUE_WINDOWS_VK:
kc.VirtualKeyCode = CONQUE_WINDOWS_VK[str(cnum)]
else:
kc.VirtualKeyCode = ctypes.windll.user32.VkKeyScanA(cnum)
#kc.VirtualKeyCode = ctypes.windll.user32.VkKeyScanA(cnum+96)
#kc.ControlKeyState = win32con.LEFT_CTRL_PRESSED
|
<|file_name|>cmss.py<|end_file_name|><|fim▁begin|>import win32pipe
import win32console
import win32process
import time
import win32con
import codecs
import ctypes
user32 = ctypes.windll.user32
CONQUE_WINDOWS_VK = {
'3' : win32con.VK_CANCEL,
'8' : win32con.VK_BACK,
'9' : win32con.VK_TAB,
'12' : win32con.VK_CLEAR,
'13' : win32con.VK_RETURN,
'17' : win32con.VK_CONTROL,
'20' : win32con.VK_CAPITAL,
'27' : win32con.VK_ESCAPE,
'28' : win32con.VK_CONVERT,
'35' : win32con.VK_END,
'36' : win32con.VK_HOME,
'37' : win32con.VK_LEFT,
'38' : win32con.VK_UP,
'39' : win32con.VK_RIGHT,
'40' : win32con.VK_DOWN,
'45' : win32con.VK_INSERT,
'46' : win32con.VK_DELETE,
'47' : win32con.VK_HELP
}
def make_input_key(c, control_key_state=None):
kc = win32console.PyINPUT_RECORDType (win32console.KEY_EVENT)
kc.KeyDown = True
kc.RepeatCount = 1
cnum = ord(c)
if cnum == 3:
pid_list = win32console.GetConsoleProcessList()
win32console.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, 0)
return
else:
kc.Char = unicode(c)
if str(cnum) in CONQUE_WINDOWS_VK:
<|fim_middle|>
else:
kc.VirtualKeyCode = ctypes.windll.user32.VkKeyScanA(cnum)
#kc.VirtualKeyCode = ctypes.windll.user32.VkKeyScanA(cnum+96)
#kc.ControlKeyState = win32con.LEFT_CTRL_PRESSED
return kc
#win32console.AttachConsole()
coord = win32console.PyCOORDType
con_stdout = win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE)
con_stdin = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE)
flags = win32process.NORMAL_PRIORITY_CLASS
si = win32process.STARTUPINFO()
si.dwFlags |= win32con.STARTF_USESHOWWINDOW
(handle1, handle2, i1, i2) = win32process.CreateProcess(None, "cmd.exe", None, None, 0, flags, None, '.', si)
time.sleep(1)
#size = con_stdout.GetConsoleScreenBufferInfo()['Window']
# with codecs.open("log.txt", "w", "utf8") as f:
# for i in xrange(0, size.Bottom):
# f.write(con_stdout.ReadConsoleOutputCharacter(size.Right+1, coord(0, i)))
# f.write("\n")
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = "127.0.0.1"
PORT = 5554
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(1)
(sc, scname) = s.accept()
while True:
msg = sc.recv(1)
if ord(msg) == 0:
break
keys = [make_input_key(msg)]
if keys:
con_stdin.WriteConsoleInput(keys)
win32process.TerminateProcess(handle1, 0)<|fim▁end|> | kc.VirtualKeyCode = CONQUE_WINDOWS_VK[str(cnum)] |
<|file_name|>cmss.py<|end_file_name|><|fim▁begin|>import win32pipe
import win32console
import win32process
import time
import win32con
import codecs
import ctypes
user32 = ctypes.windll.user32
CONQUE_WINDOWS_VK = {
'3' : win32con.VK_CANCEL,
'8' : win32con.VK_BACK,
'9' : win32con.VK_TAB,
'12' : win32con.VK_CLEAR,
'13' : win32con.VK_RETURN,
'17' : win32con.VK_CONTROL,
'20' : win32con.VK_CAPITAL,
'27' : win32con.VK_ESCAPE,
'28' : win32con.VK_CONVERT,
'35' : win32con.VK_END,
'36' : win32con.VK_HOME,
'37' : win32con.VK_LEFT,
'38' : win32con.VK_UP,
'39' : win32con.VK_RIGHT,
'40' : win32con.VK_DOWN,
'45' : win32con.VK_INSERT,
'46' : win32con.VK_DELETE,
'47' : win32con.VK_HELP
}
def make_input_key(c, control_key_state=None):
kc = win32console.PyINPUT_RECORDType (win32console.KEY_EVENT)
kc.KeyDown = True
kc.RepeatCount = 1
cnum = ord(c)
if cnum == 3:
pid_list = win32console.GetConsoleProcessList()
win32console.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, 0)
return
else:
kc.Char = unicode(c)
if str(cnum) in CONQUE_WINDOWS_VK:
kc.VirtualKeyCode = CONQUE_WINDOWS_VK[str(cnum)]
else:
<|fim_middle|>
return kc
#win32console.AttachConsole()
coord = win32console.PyCOORDType
con_stdout = win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE)
con_stdin = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE)
flags = win32process.NORMAL_PRIORITY_CLASS
si = win32process.STARTUPINFO()
si.dwFlags |= win32con.STARTF_USESHOWWINDOW
(handle1, handle2, i1, i2) = win32process.CreateProcess(None, "cmd.exe", None, None, 0, flags, None, '.', si)
time.sleep(1)
#size = con_stdout.GetConsoleScreenBufferInfo()['Window']
# with codecs.open("log.txt", "w", "utf8") as f:
# for i in xrange(0, size.Bottom):
# f.write(con_stdout.ReadConsoleOutputCharacter(size.Right+1, coord(0, i)))
# f.write("\n")
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = "127.0.0.1"
PORT = 5554
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(1)
(sc, scname) = s.accept()
while True:
msg = sc.recv(1)
if ord(msg) == 0:
break
keys = [make_input_key(msg)]
if keys:
con_stdin.WriteConsoleInput(keys)
win32process.TerminateProcess(handle1, 0)<|fim▁end|> | kc.VirtualKeyCode = ctypes.windll.user32.VkKeyScanA(cnum)
#kc.VirtualKeyCode = ctypes.windll.user32.VkKeyScanA(cnum+96)
#kc.ControlKeyState = win32con.LEFT_CTRL_PRESSED
|
<|file_name|>cmss.py<|end_file_name|><|fim▁begin|>import win32pipe
import win32console
import win32process
import time
import win32con
import codecs
import ctypes
user32 = ctypes.windll.user32
CONQUE_WINDOWS_VK = {
'3' : win32con.VK_CANCEL,
'8' : win32con.VK_BACK,
'9' : win32con.VK_TAB,
'12' : win32con.VK_CLEAR,
'13' : win32con.VK_RETURN,
'17' : win32con.VK_CONTROL,
'20' : win32con.VK_CAPITAL,
'27' : win32con.VK_ESCAPE,
'28' : win32con.VK_CONVERT,
'35' : win32con.VK_END,
'36' : win32con.VK_HOME,
'37' : win32con.VK_LEFT,
'38' : win32con.VK_UP,
'39' : win32con.VK_RIGHT,
'40' : win32con.VK_DOWN,
'45' : win32con.VK_INSERT,
'46' : win32con.VK_DELETE,
'47' : win32con.VK_HELP
}
def make_input_key(c, control_key_state=None):
kc = win32console.PyINPUT_RECORDType (win32console.KEY_EVENT)
kc.KeyDown = True
kc.RepeatCount = 1
cnum = ord(c)
if cnum == 3:
pid_list = win32console.GetConsoleProcessList()
win32console.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, 0)
return
else:
kc.Char = unicode(c)
if str(cnum) in CONQUE_WINDOWS_VK:
kc.VirtualKeyCode = CONQUE_WINDOWS_VK[str(cnum)]
else:
kc.VirtualKeyCode = ctypes.windll.user32.VkKeyScanA(cnum)
#kc.VirtualKeyCode = ctypes.windll.user32.VkKeyScanA(cnum+96)
#kc.ControlKeyState = win32con.LEFT_CTRL_PRESSED
return kc
#win32console.AttachConsole()
coord = win32console.PyCOORDType
con_stdout = win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE)
con_stdin = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE)
flags = win32process.NORMAL_PRIORITY_CLASS
si = win32process.STARTUPINFO()
si.dwFlags |= win32con.STARTF_USESHOWWINDOW
(handle1, handle2, i1, i2) = win32process.CreateProcess(None, "cmd.exe", None, None, 0, flags, None, '.', si)
time.sleep(1)
#size = con_stdout.GetConsoleScreenBufferInfo()['Window']
# with codecs.open("log.txt", "w", "utf8") as f:
# for i in xrange(0, size.Bottom):
# f.write(con_stdout.ReadConsoleOutputCharacter(size.Right+1, coord(0, i)))
# f.write("\n")
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = "127.0.0.1"
PORT = 5554
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(1)
(sc, scname) = s.accept()
while True:
msg = sc.recv(1)
if ord(msg) == 0:
<|fim_middle|>
keys = [make_input_key(msg)]
if keys:
con_stdin.WriteConsoleInput(keys)
win32process.TerminateProcess(handle1, 0)<|fim▁end|> | break |
<|file_name|>cmss.py<|end_file_name|><|fim▁begin|>import win32pipe
import win32console
import win32process
import time
import win32con
import codecs
import ctypes
user32 = ctypes.windll.user32
CONQUE_WINDOWS_VK = {
'3' : win32con.VK_CANCEL,
'8' : win32con.VK_BACK,
'9' : win32con.VK_TAB,
'12' : win32con.VK_CLEAR,
'13' : win32con.VK_RETURN,
'17' : win32con.VK_CONTROL,
'20' : win32con.VK_CAPITAL,
'27' : win32con.VK_ESCAPE,
'28' : win32con.VK_CONVERT,
'35' : win32con.VK_END,
'36' : win32con.VK_HOME,
'37' : win32con.VK_LEFT,
'38' : win32con.VK_UP,
'39' : win32con.VK_RIGHT,
'40' : win32con.VK_DOWN,
'45' : win32con.VK_INSERT,
'46' : win32con.VK_DELETE,
'47' : win32con.VK_HELP
}
def make_input_key(c, control_key_state=None):
kc = win32console.PyINPUT_RECORDType (win32console.KEY_EVENT)
kc.KeyDown = True
kc.RepeatCount = 1
cnum = ord(c)
if cnum == 3:
pid_list = win32console.GetConsoleProcessList()
win32console.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, 0)
return
else:
kc.Char = unicode(c)
if str(cnum) in CONQUE_WINDOWS_VK:
kc.VirtualKeyCode = CONQUE_WINDOWS_VK[str(cnum)]
else:
kc.VirtualKeyCode = ctypes.windll.user32.VkKeyScanA(cnum)
#kc.VirtualKeyCode = ctypes.windll.user32.VkKeyScanA(cnum+96)
#kc.ControlKeyState = win32con.LEFT_CTRL_PRESSED
return kc
#win32console.AttachConsole()
coord = win32console.PyCOORDType
con_stdout = win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE)
con_stdin = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE)
flags = win32process.NORMAL_PRIORITY_CLASS
si = win32process.STARTUPINFO()
si.dwFlags |= win32con.STARTF_USESHOWWINDOW
(handle1, handle2, i1, i2) = win32process.CreateProcess(None, "cmd.exe", None, None, 0, flags, None, '.', si)
time.sleep(1)
#size = con_stdout.GetConsoleScreenBufferInfo()['Window']
# with codecs.open("log.txt", "w", "utf8") as f:
# for i in xrange(0, size.Bottom):
# f.write(con_stdout.ReadConsoleOutputCharacter(size.Right+1, coord(0, i)))
# f.write("\n")
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = "127.0.0.1"
PORT = 5554
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(1)
(sc, scname) = s.accept()
while True:
msg = sc.recv(1)
if ord(msg) == 0:
break
keys = [make_input_key(msg)]
if keys:
<|fim_middle|>
win32process.TerminateProcess(handle1, 0)<|fim▁end|> | con_stdin.WriteConsoleInput(keys) |
<|file_name|>cmss.py<|end_file_name|><|fim▁begin|>import win32pipe
import win32console
import win32process
import time
import win32con
import codecs
import ctypes
user32 = ctypes.windll.user32
CONQUE_WINDOWS_VK = {
'3' : win32con.VK_CANCEL,
'8' : win32con.VK_BACK,
'9' : win32con.VK_TAB,
'12' : win32con.VK_CLEAR,
'13' : win32con.VK_RETURN,
'17' : win32con.VK_CONTROL,
'20' : win32con.VK_CAPITAL,
'27' : win32con.VK_ESCAPE,
'28' : win32con.VK_CONVERT,
'35' : win32con.VK_END,
'36' : win32con.VK_HOME,
'37' : win32con.VK_LEFT,
'38' : win32con.VK_UP,
'39' : win32con.VK_RIGHT,
'40' : win32con.VK_DOWN,
'45' : win32con.VK_INSERT,
'46' : win32con.VK_DELETE,
'47' : win32con.VK_HELP
}
def <|fim_middle|>(c, control_key_state=None):
kc = win32console.PyINPUT_RECORDType (win32console.KEY_EVENT)
kc.KeyDown = True
kc.RepeatCount = 1
cnum = ord(c)
if cnum == 3:
pid_list = win32console.GetConsoleProcessList()
win32console.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, 0)
return
else:
kc.Char = unicode(c)
if str(cnum) in CONQUE_WINDOWS_VK:
kc.VirtualKeyCode = CONQUE_WINDOWS_VK[str(cnum)]
else:
kc.VirtualKeyCode = ctypes.windll.user32.VkKeyScanA(cnum)
#kc.VirtualKeyCode = ctypes.windll.user32.VkKeyScanA(cnum+96)
#kc.ControlKeyState = win32con.LEFT_CTRL_PRESSED
return kc
#win32console.AttachConsole()
coord = win32console.PyCOORDType
con_stdout = win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE)
con_stdin = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE)
flags = win32process.NORMAL_PRIORITY_CLASS
si = win32process.STARTUPINFO()
si.dwFlags |= win32con.STARTF_USESHOWWINDOW
(handle1, handle2, i1, i2) = win32process.CreateProcess(None, "cmd.exe", None, None, 0, flags, None, '.', si)
time.sleep(1)
#size = con_stdout.GetConsoleScreenBufferInfo()['Window']
# with codecs.open("log.txt", "w", "utf8") as f:
# for i in xrange(0, size.Bottom):
# f.write(con_stdout.ReadConsoleOutputCharacter(size.Right+1, coord(0, i)))
# f.write("\n")
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = "127.0.0.1"
PORT = 5554
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(1)
(sc, scname) = s.accept()
while True:
msg = sc.recv(1)
if ord(msg) == 0:
break
keys = [make_input_key(msg)]
if keys:
con_stdin.WriteConsoleInput(keys)
win32process.TerminateProcess(handle1, 0)<|fim▁end|> | make_input_key |
<|file_name|>test_compact_csv_reader.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals
from django.utils import six
import pytest
from nicedjango.utils.compact_csv import CsvReader
@pytest.fixture
def stream():
csv = b'''"a\xc2\x96b\\"c'd\\re\\nf,g\\\\",1,NULL,""\n'''.decode('utf-8')
return six.StringIO(csv)
def test_reader_raw(stream):
r = CsvReader(stream, replacements=(), preserve_quotes=True, symbols=(),
replace_digits=False)
assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', 'NULL', '""']]
def test_reader_none(stream):
r = CsvReader(stream, replacements=(), preserve_quotes=True,
replace_digits=False)
assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', None, '""']]
def test_reader_quotes(stream):
r = CsvReader(stream, replacements=(), replace_digits=False)
assert list(r) == [['''a\x96b\\"c'd\\re\\nf,g\\\\''', '1', None, '']]
def test_reader_replace(stream):
r = CsvReader(stream, replace_digits=False)
assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', '1', None, '']]
def test_reader_replace_digit(stream):<|fim▁hole|> r = CsvReader(stream)
assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', 1, None, '']]<|fim▁end|> | |
<|file_name|>test_compact_csv_reader.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals
from django.utils import six
import pytest
from nicedjango.utils.compact_csv import CsvReader
@pytest.fixture
def stream():
<|fim_middle|>
def test_reader_raw(stream):
r = CsvReader(stream, replacements=(), preserve_quotes=True, symbols=(),
replace_digits=False)
assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', 'NULL', '""']]
def test_reader_none(stream):
r = CsvReader(stream, replacements=(), preserve_quotes=True,
replace_digits=False)
assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', None, '""']]
def test_reader_quotes(stream):
r = CsvReader(stream, replacements=(), replace_digits=False)
assert list(r) == [['''a\x96b\\"c'd\\re\\nf,g\\\\''', '1', None, '']]
def test_reader_replace(stream):
r = CsvReader(stream, replace_digits=False)
assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', '1', None, '']]
def test_reader_replace_digit(stream):
r = CsvReader(stream)
assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', 1, None, '']]
<|fim▁end|> | csv = b'''"a\xc2\x96b\\"c'd\\re\\nf,g\\\\",1,NULL,""\n'''.decode('utf-8')
return six.StringIO(csv) |
<|file_name|>test_compact_csv_reader.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals
from django.utils import six
import pytest
from nicedjango.utils.compact_csv import CsvReader
@pytest.fixture
def stream():
csv = b'''"a\xc2\x96b\\"c'd\\re\\nf,g\\\\",1,NULL,""\n'''.decode('utf-8')
return six.StringIO(csv)
def test_reader_raw(stream):
<|fim_middle|>
def test_reader_none(stream):
r = CsvReader(stream, replacements=(), preserve_quotes=True,
replace_digits=False)
assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', None, '""']]
def test_reader_quotes(stream):
r = CsvReader(stream, replacements=(), replace_digits=False)
assert list(r) == [['''a\x96b\\"c'd\\re\\nf,g\\\\''', '1', None, '']]
def test_reader_replace(stream):
r = CsvReader(stream, replace_digits=False)
assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', '1', None, '']]
def test_reader_replace_digit(stream):
r = CsvReader(stream)
assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', 1, None, '']]
<|fim▁end|> | r = CsvReader(stream, replacements=(), preserve_quotes=True, symbols=(),
replace_digits=False)
assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', 'NULL', '""']] |
<|file_name|>test_compact_csv_reader.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals
from django.utils import six
import pytest
from nicedjango.utils.compact_csv import CsvReader
@pytest.fixture
def stream():
csv = b'''"a\xc2\x96b\\"c'd\\re\\nf,g\\\\",1,NULL,""\n'''.decode('utf-8')
return six.StringIO(csv)
def test_reader_raw(stream):
r = CsvReader(stream, replacements=(), preserve_quotes=True, symbols=(),
replace_digits=False)
assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', 'NULL', '""']]
def test_reader_none(stream):
<|fim_middle|>
def test_reader_quotes(stream):
r = CsvReader(stream, replacements=(), replace_digits=False)
assert list(r) == [['''a\x96b\\"c'd\\re\\nf,g\\\\''', '1', None, '']]
def test_reader_replace(stream):
r = CsvReader(stream, replace_digits=False)
assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', '1', None, '']]
def test_reader_replace_digit(stream):
r = CsvReader(stream)
assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', 1, None, '']]
<|fim▁end|> | r = CsvReader(stream, replacements=(), preserve_quotes=True,
replace_digits=False)
assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', None, '""']] |
<|file_name|>test_compact_csv_reader.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals
from django.utils import six
import pytest
from nicedjango.utils.compact_csv import CsvReader
@pytest.fixture
def stream():
csv = b'''"a\xc2\x96b\\"c'd\\re\\nf,g\\\\",1,NULL,""\n'''.decode('utf-8')
return six.StringIO(csv)
def test_reader_raw(stream):
r = CsvReader(stream, replacements=(), preserve_quotes=True, symbols=(),
replace_digits=False)
assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', 'NULL', '""']]
def test_reader_none(stream):
r = CsvReader(stream, replacements=(), preserve_quotes=True,
replace_digits=False)
assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', None, '""']]
def test_reader_quotes(stream):
<|fim_middle|>
def test_reader_replace(stream):
r = CsvReader(stream, replace_digits=False)
assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', '1', None, '']]
def test_reader_replace_digit(stream):
r = CsvReader(stream)
assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', 1, None, '']]
<|fim▁end|> | r = CsvReader(stream, replacements=(), replace_digits=False)
assert list(r) == [['''a\x96b\\"c'd\\re\\nf,g\\\\''', '1', None, '']] |
<|file_name|>test_compact_csv_reader.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals
from django.utils import six
import pytest
from nicedjango.utils.compact_csv import CsvReader
@pytest.fixture
def stream():
csv = b'''"a\xc2\x96b\\"c'd\\re\\nf,g\\\\",1,NULL,""\n'''.decode('utf-8')
return six.StringIO(csv)
def test_reader_raw(stream):
r = CsvReader(stream, replacements=(), preserve_quotes=True, symbols=(),
replace_digits=False)
assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', 'NULL', '""']]
def test_reader_none(stream):
r = CsvReader(stream, replacements=(), preserve_quotes=True,
replace_digits=False)
assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', None, '""']]
def test_reader_quotes(stream):
r = CsvReader(stream, replacements=(), replace_digits=False)
assert list(r) == [['''a\x96b\\"c'd\\re\\nf,g\\\\''', '1', None, '']]
def test_reader_replace(stream):
<|fim_middle|>
def test_reader_replace_digit(stream):
r = CsvReader(stream)
assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', 1, None, '']]
<|fim▁end|> | r = CsvReader(stream, replace_digits=False)
assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', '1', None, '']] |
<|file_name|>test_compact_csv_reader.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals
from django.utils import six
import pytest
from nicedjango.utils.compact_csv import CsvReader
@pytest.fixture
def stream():
csv = b'''"a\xc2\x96b\\"c'd\\re\\nf,g\\\\",1,NULL,""\n'''.decode('utf-8')
return six.StringIO(csv)
def test_reader_raw(stream):
r = CsvReader(stream, replacements=(), preserve_quotes=True, symbols=(),
replace_digits=False)
assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', 'NULL', '""']]
def test_reader_none(stream):
r = CsvReader(stream, replacements=(), preserve_quotes=True,
replace_digits=False)
assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', None, '""']]
def test_reader_quotes(stream):
r = CsvReader(stream, replacements=(), replace_digits=False)
assert list(r) == [['''a\x96b\\"c'd\\re\\nf,g\\\\''', '1', None, '']]
def test_reader_replace(stream):
r = CsvReader(stream, replace_digits=False)
assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', '1', None, '']]
def test_reader_replace_digit(stream):
<|fim_middle|>
<|fim▁end|> | r = CsvReader(stream)
assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', 1, None, '']] |
<|file_name|>test_compact_csv_reader.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals
from django.utils import six
import pytest
from nicedjango.utils.compact_csv import CsvReader
@pytest.fixture
def <|fim_middle|>():
csv = b'''"a\xc2\x96b\\"c'd\\re\\nf,g\\\\",1,NULL,""\n'''.decode('utf-8')
return six.StringIO(csv)
def test_reader_raw(stream):
r = CsvReader(stream, replacements=(), preserve_quotes=True, symbols=(),
replace_digits=False)
assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', 'NULL', '""']]
def test_reader_none(stream):
r = CsvReader(stream, replacements=(), preserve_quotes=True,
replace_digits=False)
assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', None, '""']]
def test_reader_quotes(stream):
r = CsvReader(stream, replacements=(), replace_digits=False)
assert list(r) == [['''a\x96b\\"c'd\\re\\nf,g\\\\''', '1', None, '']]
def test_reader_replace(stream):
r = CsvReader(stream, replace_digits=False)
assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', '1', None, '']]
def test_reader_replace_digit(stream):
r = CsvReader(stream)
assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', 1, None, '']]
<|fim▁end|> | stream |
<|file_name|>test_compact_csv_reader.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals
from django.utils import six
import pytest
from nicedjango.utils.compact_csv import CsvReader
@pytest.fixture
def stream():
csv = b'''"a\xc2\x96b\\"c'd\\re\\nf,g\\\\",1,NULL,""\n'''.decode('utf-8')
return six.StringIO(csv)
def <|fim_middle|>(stream):
r = CsvReader(stream, replacements=(), preserve_quotes=True, symbols=(),
replace_digits=False)
assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', 'NULL', '""']]
def test_reader_none(stream):
r = CsvReader(stream, replacements=(), preserve_quotes=True,
replace_digits=False)
assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', None, '""']]
def test_reader_quotes(stream):
r = CsvReader(stream, replacements=(), replace_digits=False)
assert list(r) == [['''a\x96b\\"c'd\\re\\nf,g\\\\''', '1', None, '']]
def test_reader_replace(stream):
r = CsvReader(stream, replace_digits=False)
assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', '1', None, '']]
def test_reader_replace_digit(stream):
r = CsvReader(stream)
assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', 1, None, '']]
<|fim▁end|> | test_reader_raw |
<|file_name|>test_compact_csv_reader.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals
from django.utils import six
import pytest
from nicedjango.utils.compact_csv import CsvReader
@pytest.fixture
def stream():
csv = b'''"a\xc2\x96b\\"c'd\\re\\nf,g\\\\",1,NULL,""\n'''.decode('utf-8')
return six.StringIO(csv)
def test_reader_raw(stream):
r = CsvReader(stream, replacements=(), preserve_quotes=True, symbols=(),
replace_digits=False)
assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', 'NULL', '""']]
def <|fim_middle|>(stream):
r = CsvReader(stream, replacements=(), preserve_quotes=True,
replace_digits=False)
assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', None, '""']]
def test_reader_quotes(stream):
r = CsvReader(stream, replacements=(), replace_digits=False)
assert list(r) == [['''a\x96b\\"c'd\\re\\nf,g\\\\''', '1', None, '']]
def test_reader_replace(stream):
r = CsvReader(stream, replace_digits=False)
assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', '1', None, '']]
def test_reader_replace_digit(stream):
r = CsvReader(stream)
assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', 1, None, '']]
<|fim▁end|> | test_reader_none |
<|file_name|>test_compact_csv_reader.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals
from django.utils import six
import pytest
from nicedjango.utils.compact_csv import CsvReader
@pytest.fixture
def stream():
csv = b'''"a\xc2\x96b\\"c'd\\re\\nf,g\\\\",1,NULL,""\n'''.decode('utf-8')
return six.StringIO(csv)
def test_reader_raw(stream):
r = CsvReader(stream, replacements=(), preserve_quotes=True, symbols=(),
replace_digits=False)
assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', 'NULL', '""']]
def test_reader_none(stream):
r = CsvReader(stream, replacements=(), preserve_quotes=True,
replace_digits=False)
assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', None, '""']]
def <|fim_middle|>(stream):
r = CsvReader(stream, replacements=(), replace_digits=False)
assert list(r) == [['''a\x96b\\"c'd\\re\\nf,g\\\\''', '1', None, '']]
def test_reader_replace(stream):
r = CsvReader(stream, replace_digits=False)
assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', '1', None, '']]
def test_reader_replace_digit(stream):
r = CsvReader(stream)
assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', 1, None, '']]
<|fim▁end|> | test_reader_quotes |
<|file_name|>test_compact_csv_reader.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals
from django.utils import six
import pytest
from nicedjango.utils.compact_csv import CsvReader
@pytest.fixture
def stream():
csv = b'''"a\xc2\x96b\\"c'd\\re\\nf,g\\\\",1,NULL,""\n'''.decode('utf-8')
return six.StringIO(csv)
def test_reader_raw(stream):
r = CsvReader(stream, replacements=(), preserve_quotes=True, symbols=(),
replace_digits=False)
assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', 'NULL', '""']]
def test_reader_none(stream):
r = CsvReader(stream, replacements=(), preserve_quotes=True,
replace_digits=False)
assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', None, '""']]
def test_reader_quotes(stream):
r = CsvReader(stream, replacements=(), replace_digits=False)
assert list(r) == [['''a\x96b\\"c'd\\re\\nf,g\\\\''', '1', None, '']]
def <|fim_middle|>(stream):
r = CsvReader(stream, replace_digits=False)
assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', '1', None, '']]
def test_reader_replace_digit(stream):
r = CsvReader(stream)
assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', 1, None, '']]
<|fim▁end|> | test_reader_replace |
<|file_name|>test_compact_csv_reader.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals
from django.utils import six
import pytest
from nicedjango.utils.compact_csv import CsvReader
@pytest.fixture
def stream():
csv = b'''"a\xc2\x96b\\"c'd\\re\\nf,g\\\\",1,NULL,""\n'''.decode('utf-8')
return six.StringIO(csv)
def test_reader_raw(stream):
r = CsvReader(stream, replacements=(), preserve_quotes=True, symbols=(),
replace_digits=False)
assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', 'NULL', '""']]
def test_reader_none(stream):
r = CsvReader(stream, replacements=(), preserve_quotes=True,
replace_digits=False)
assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', None, '""']]
def test_reader_quotes(stream):
r = CsvReader(stream, replacements=(), replace_digits=False)
assert list(r) == [['''a\x96b\\"c'd\\re\\nf,g\\\\''', '1', None, '']]
def test_reader_replace(stream):
r = CsvReader(stream, replace_digits=False)
assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', '1', None, '']]
def <|fim_middle|>(stream):
r = CsvReader(stream)
assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', 1, None, '']]
<|fim▁end|> | test_reader_replace_digit |
<|file_name|>spa.py<|end_file_name|><|fim▁begin|>from urllib.request import urlopen
from urllib.parse import urlparse, parse_qs
from socket import error as SocketError
import errno
from bs4 import BeautifulSoup
MAX_PAGES_TO_SEARCH = 3
def parse_news(item):
'''Parse news item
return is a tuple(id, title, url)
'''
url = 'http://www.spa.gov.sa' + item['href']
url_parsed = urlparse(url)
qs = parse_qs(url_parsed[4])
id = qs['newsid'][0]
title = item.h2.contents[0]
title = " ".join(title.split())
item_parsed = (id, title, url)
return item_parsed
def retrieve_news(person=0, royal=0, cabinet=0, last_id=-1):
'''Retrieve news for person or royal
person 1= king, 2= crown prince and 3= deputy crown prince
if royal is = 1 news will be retriveved
if last_id not definend it will return the max
return list of news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url)...]
'''
all_news = []
found = False
page = 1
while (page <= MAX_PAGES_TO_SEARCH and not found):
url = ("http://www.spa.gov.sa/ajax/listnews.php?sticky={}&cat=0&cabine"
"t={}&royal={}&lang=ar&pg={}".format(person, cabinet, royal, page))
try:
html = urlopen(url)
soup = BeautifulSoup(html, "html.parser")
news = soup.find_all("a", class_="aNewsTitle")
for item in news:
item_parsed = parse_news(item)
if item_parsed[0] <= str(last_id):
found = True
break
all_news.append(item_parsed)
except SocketError as e:
if e.errno != errno.ECONNRESET:
raise
pass
page = page + 1
return all_news
def retrieve_detail(item):
'''Retrive detaill for news item
return is tuple (id, title, url, text)
'''
url = item[2]
html = urlopen(url)
soup = BeautifulSoup(html, 'html.parser')
detail = soup.find(class_='divNewsDetailsText')
detail = detail.get_text()
_list = list(item)
_list.insert(3, detail)
item = tuple(_list)
return item
def royal_order(last_id=-1):
'''Retrive royal orders
if last_id not defiend it will return the max
return list of royal orders tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
orders = []
_news = retrieve_news(royal=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
orders.append(_detail)
return orders
def cabinet_decision(last_id=-1):
'''Retrive cabinet decisions
if last_id not defiend it will return the max
return list of cabinet decisions tuples up to MAX_PAGES_TO_SEARCH (page=10)<|fim▁hole|> '''
decisions = []
_news = retrieve_news(cabinet=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
decisions.append(_detail)
return decisions
def arrival_news(person, last_id=-1):
'''Retrive only arrival news for person
if last_id not defiend it will return the max
return list of arrival news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, location)...]
'''
arrival_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يصل إلى' in item[1]:
_list = list(item)
_list.insert(3, (item[1].split('يصل إلى'))[1].split('قادماً من')[0])
item = tuple(_list)
arrival_news.append(item)
return arrival_news
def leave_news(person, last_id=-1):
'''Retrive only leave news for person
if last_id not defiend it will return the max
return list of leave news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, locationFromTo)...]
'''
leave_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يغادر' in item[1]:
_list = list(item)
_list.insert(3, item[1].split('يغادر')[1])
item = tuple(_list)
leave_news.append(item)
return leave_news
if __name__ == "__main__":
# just for testing
news = cabinet_decision()
print(news)<|fim▁end|> | [(id, title, url, text)...] |
<|file_name|>spa.py<|end_file_name|><|fim▁begin|>from urllib.request import urlopen
from urllib.parse import urlparse, parse_qs
from socket import error as SocketError
import errno
from bs4 import BeautifulSoup
MAX_PAGES_TO_SEARCH = 3
def parse_news(item):
<|fim_middle|>
def retrieve_news(person=0, royal=0, cabinet=0, last_id=-1):
'''Retrieve news for person or royal
person 1= king, 2= crown prince and 3= deputy crown prince
if royal is = 1 news will be retriveved
if last_id not definend it will return the max
return list of news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url)...]
'''
all_news = []
found = False
page = 1
while (page <= MAX_PAGES_TO_SEARCH and not found):
url = ("http://www.spa.gov.sa/ajax/listnews.php?sticky={}&cat=0&cabine"
"t={}&royal={}&lang=ar&pg={}".format(person, cabinet, royal, page))
try:
html = urlopen(url)
soup = BeautifulSoup(html, "html.parser")
news = soup.find_all("a", class_="aNewsTitle")
for item in news:
item_parsed = parse_news(item)
if item_parsed[0] <= str(last_id):
found = True
break
all_news.append(item_parsed)
except SocketError as e:
if e.errno != errno.ECONNRESET:
raise
pass
page = page + 1
return all_news
def retrieve_detail(item):
'''Retrive detaill for news item
return is tuple (id, title, url, text)
'''
url = item[2]
html = urlopen(url)
soup = BeautifulSoup(html, 'html.parser')
detail = soup.find(class_='divNewsDetailsText')
detail = detail.get_text()
_list = list(item)
_list.insert(3, detail)
item = tuple(_list)
return item
def royal_order(last_id=-1):
'''Retrive royal orders
if last_id not defiend it will return the max
return list of royal orders tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
orders = []
_news = retrieve_news(royal=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
orders.append(_detail)
return orders
def cabinet_decision(last_id=-1):
'''Retrive cabinet decisions
if last_id not defiend it will return the max
return list of cabinet decisions tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
decisions = []
_news = retrieve_news(cabinet=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
decisions.append(_detail)
return decisions
def arrival_news(person, last_id=-1):
'''Retrive only arrival news for person
if last_id not defiend it will return the max
return list of arrival news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, location)...]
'''
arrival_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يصل إلى' in item[1]:
_list = list(item)
_list.insert(3, (item[1].split('يصل إلى'))[1].split('قادماً من')[0])
item = tuple(_list)
arrival_news.append(item)
return arrival_news
def leave_news(person, last_id=-1):
'''Retrive only leave news for person
if last_id not defiend it will return the max
return list of leave news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, locationFromTo)...]
'''
leave_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يغادر' in item[1]:
_list = list(item)
_list.insert(3, item[1].split('يغادر')[1])
item = tuple(_list)
leave_news.append(item)
return leave_news
if __name__ == "__main__":
# just for testing
news = cabinet_decision()
print(news)
<|fim▁end|> | '''Parse news item
return is a tuple(id, title, url)
'''
url = 'http://www.spa.gov.sa' + item['href']
url_parsed = urlparse(url)
qs = parse_qs(url_parsed[4])
id = qs['newsid'][0]
title = item.h2.contents[0]
title = " ".join(title.split())
item_parsed = (id, title, url)
return item_parsed |
<|file_name|>spa.py<|end_file_name|><|fim▁begin|>from urllib.request import urlopen
from urllib.parse import urlparse, parse_qs
from socket import error as SocketError
import errno
from bs4 import BeautifulSoup
MAX_PAGES_TO_SEARCH = 3
def parse_news(item):
'''Parse news item
return is a tuple(id, title, url)
'''
url = 'http://www.spa.gov.sa' + item['href']
url_parsed = urlparse(url)
qs = parse_qs(url_parsed[4])
id = qs['newsid'][0]
title = item.h2.contents[0]
title = " ".join(title.split())
item_parsed = (id, title, url)
return item_parsed
def retrieve_news(person=0, royal=0, cabinet=0, last_id=-1):
<|fim_middle|>
def retrieve_detail(item):
'''Retrive detaill for news item
return is tuple (id, title, url, text)
'''
url = item[2]
html = urlopen(url)
soup = BeautifulSoup(html, 'html.parser')
detail = soup.find(class_='divNewsDetailsText')
detail = detail.get_text()
_list = list(item)
_list.insert(3, detail)
item = tuple(_list)
return item
def royal_order(last_id=-1):
'''Retrive royal orders
if last_id not defiend it will return the max
return list of royal orders tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
orders = []
_news = retrieve_news(royal=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
orders.append(_detail)
return orders
def cabinet_decision(last_id=-1):
'''Retrive cabinet decisions
if last_id not defiend it will return the max
return list of cabinet decisions tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
decisions = []
_news = retrieve_news(cabinet=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
decisions.append(_detail)
return decisions
def arrival_news(person, last_id=-1):
'''Retrive only arrival news for person
if last_id not defiend it will return the max
return list of arrival news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, location)...]
'''
arrival_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يصل إلى' in item[1]:
_list = list(item)
_list.insert(3, (item[1].split('يصل إلى'))[1].split('قادماً من')[0])
item = tuple(_list)
arrival_news.append(item)
return arrival_news
def leave_news(person, last_id=-1):
'''Retrive only leave news for person
if last_id not defiend it will return the max
return list of leave news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, locationFromTo)...]
'''
leave_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يغادر' in item[1]:
_list = list(item)
_list.insert(3, item[1].split('يغادر')[1])
item = tuple(_list)
leave_news.append(item)
return leave_news
if __name__ == "__main__":
# just for testing
news = cabinet_decision()
print(news)
<|fim▁end|> | '''Retrieve news for person or royal
person 1= king, 2= crown prince and 3= deputy crown prince
if royal is = 1 news will be retriveved
if last_id not definend it will return the max
return list of news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url)...]
'''
all_news = []
found = False
page = 1
while (page <= MAX_PAGES_TO_SEARCH and not found):
url = ("http://www.spa.gov.sa/ajax/listnews.php?sticky={}&cat=0&cabine"
"t={}&royal={}&lang=ar&pg={}".format(person, cabinet, royal, page))
try:
html = urlopen(url)
soup = BeautifulSoup(html, "html.parser")
news = soup.find_all("a", class_="aNewsTitle")
for item in news:
item_parsed = parse_news(item)
if item_parsed[0] <= str(last_id):
found = True
break
all_news.append(item_parsed)
except SocketError as e:
if e.errno != errno.ECONNRESET:
raise
pass
page = page + 1
return all_news |
<|file_name|>spa.py<|end_file_name|><|fim▁begin|>from urllib.request import urlopen
from urllib.parse import urlparse, parse_qs
from socket import error as SocketError
import errno
from bs4 import BeautifulSoup
MAX_PAGES_TO_SEARCH = 3
def parse_news(item):
'''Parse news item
return is a tuple(id, title, url)
'''
url = 'http://www.spa.gov.sa' + item['href']
url_parsed = urlparse(url)
qs = parse_qs(url_parsed[4])
id = qs['newsid'][0]
title = item.h2.contents[0]
title = " ".join(title.split())
item_parsed = (id, title, url)
return item_parsed
def retrieve_news(person=0, royal=0, cabinet=0, last_id=-1):
'''Retrieve news for person or royal
person 1= king, 2= crown prince and 3= deputy crown prince
if royal is = 1 news will be retriveved
if last_id not definend it will return the max
return list of news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url)...]
'''
all_news = []
found = False
page = 1
while (page <= MAX_PAGES_TO_SEARCH and not found):
url = ("http://www.spa.gov.sa/ajax/listnews.php?sticky={}&cat=0&cabine"
"t={}&royal={}&lang=ar&pg={}".format(person, cabinet, royal, page))
try:
html = urlopen(url)
soup = BeautifulSoup(html, "html.parser")
news = soup.find_all("a", class_="aNewsTitle")
for item in news:
item_parsed = parse_news(item)
if item_parsed[0] <= str(last_id):
found = True
break
all_news.append(item_parsed)
except SocketError as e:
if e.errno != errno.ECONNRESET:
raise
pass
page = page + 1
return all_news
def retrieve_detail(item):
<|fim_middle|>
def royal_order(last_id=-1):
'''Retrive royal orders
if last_id not defiend it will return the max
return list of royal orders tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
orders = []
_news = retrieve_news(royal=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
orders.append(_detail)
return orders
def cabinet_decision(last_id=-1):
'''Retrive cabinet decisions
if last_id not defiend it will return the max
return list of cabinet decisions tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
decisions = []
_news = retrieve_news(cabinet=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
decisions.append(_detail)
return decisions
def arrival_news(person, last_id=-1):
'''Retrive only arrival news for person
if last_id not defiend it will return the max
return list of arrival news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, location)...]
'''
arrival_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يصل إلى' in item[1]:
_list = list(item)
_list.insert(3, (item[1].split('يصل إلى'))[1].split('قادماً من')[0])
item = tuple(_list)
arrival_news.append(item)
return arrival_news
def leave_news(person, last_id=-1):
'''Retrive only leave news for person
if last_id not defiend it will return the max
return list of leave news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, locationFromTo)...]
'''
leave_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يغادر' in item[1]:
_list = list(item)
_list.insert(3, item[1].split('يغادر')[1])
item = tuple(_list)
leave_news.append(item)
return leave_news
if __name__ == "__main__":
# just for testing
news = cabinet_decision()
print(news)
<|fim▁end|> | '''Retrive detaill for news item
return is tuple (id, title, url, text)
'''
url = item[2]
html = urlopen(url)
soup = BeautifulSoup(html, 'html.parser')
detail = soup.find(class_='divNewsDetailsText')
detail = detail.get_text()
_list = list(item)
_list.insert(3, detail)
item = tuple(_list)
return item |
<|file_name|>spa.py<|end_file_name|><|fim▁begin|>from urllib.request import urlopen
from urllib.parse import urlparse, parse_qs
from socket import error as SocketError
import errno
from bs4 import BeautifulSoup
MAX_PAGES_TO_SEARCH = 3
def parse_news(item):
'''Parse news item
return is a tuple(id, title, url)
'''
url = 'http://www.spa.gov.sa' + item['href']
url_parsed = urlparse(url)
qs = parse_qs(url_parsed[4])
id = qs['newsid'][0]
title = item.h2.contents[0]
title = " ".join(title.split())
item_parsed = (id, title, url)
return item_parsed
def retrieve_news(person=0, royal=0, cabinet=0, last_id=-1):
'''Retrieve news for person or royal
person 1= king, 2= crown prince and 3= deputy crown prince
if royal is = 1 news will be retriveved
if last_id not definend it will return the max
return list of news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url)...]
'''
all_news = []
found = False
page = 1
while (page <= MAX_PAGES_TO_SEARCH and not found):
url = ("http://www.spa.gov.sa/ajax/listnews.php?sticky={}&cat=0&cabine"
"t={}&royal={}&lang=ar&pg={}".format(person, cabinet, royal, page))
try:
html = urlopen(url)
soup = BeautifulSoup(html, "html.parser")
news = soup.find_all("a", class_="aNewsTitle")
for item in news:
item_parsed = parse_news(item)
if item_parsed[0] <= str(last_id):
found = True
break
all_news.append(item_parsed)
except SocketError as e:
if e.errno != errno.ECONNRESET:
raise
pass
page = page + 1
return all_news
def retrieve_detail(item):
'''Retrive detaill for news item
return is tuple (id, title, url, text)
'''
url = item[2]
html = urlopen(url)
soup = BeautifulSoup(html, 'html.parser')
detail = soup.find(class_='divNewsDetailsText')
detail = detail.get_text()
_list = list(item)
_list.insert(3, detail)
item = tuple(_list)
return item
def royal_order(last_id=-1):
<|fim_middle|>
def cabinet_decision(last_id=-1):
'''Retrive cabinet decisions
if last_id not defiend it will return the max
return list of cabinet decisions tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
decisions = []
_news = retrieve_news(cabinet=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
decisions.append(_detail)
return decisions
def arrival_news(person, last_id=-1):
'''Retrive only arrival news for person
if last_id not defiend it will return the max
return list of arrival news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, location)...]
'''
arrival_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يصل إلى' in item[1]:
_list = list(item)
_list.insert(3, (item[1].split('يصل إلى'))[1].split('قادماً من')[0])
item = tuple(_list)
arrival_news.append(item)
return arrival_news
def leave_news(person, last_id=-1):
'''Retrive only leave news for person
if last_id not defiend it will return the max
return list of leave news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, locationFromTo)...]
'''
leave_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يغادر' in item[1]:
_list = list(item)
_list.insert(3, item[1].split('يغادر')[1])
item = tuple(_list)
leave_news.append(item)
return leave_news
if __name__ == "__main__":
# just for testing
news = cabinet_decision()
print(news)
<|fim▁end|> | '''Retrive royal orders
if last_id not defiend it will return the max
return list of royal orders tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
orders = []
_news = retrieve_news(royal=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
orders.append(_detail)
return orders |
<|file_name|>spa.py<|end_file_name|><|fim▁begin|>from urllib.request import urlopen
from urllib.parse import urlparse, parse_qs
from socket import error as SocketError
import errno
from bs4 import BeautifulSoup
MAX_PAGES_TO_SEARCH = 3
def parse_news(item):
'''Parse news item
return is a tuple(id, title, url)
'''
url = 'http://www.spa.gov.sa' + item['href']
url_parsed = urlparse(url)
qs = parse_qs(url_parsed[4])
id = qs['newsid'][0]
title = item.h2.contents[0]
title = " ".join(title.split())
item_parsed = (id, title, url)
return item_parsed
def retrieve_news(person=0, royal=0, cabinet=0, last_id=-1):
'''Retrieve news for person or royal
person 1= king, 2= crown prince and 3= deputy crown prince
if royal is = 1 news will be retriveved
if last_id not definend it will return the max
return list of news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url)...]
'''
all_news = []
found = False
page = 1
while (page <= MAX_PAGES_TO_SEARCH and not found):
url = ("http://www.spa.gov.sa/ajax/listnews.php?sticky={}&cat=0&cabine"
"t={}&royal={}&lang=ar&pg={}".format(person, cabinet, royal, page))
try:
html = urlopen(url)
soup = BeautifulSoup(html, "html.parser")
news = soup.find_all("a", class_="aNewsTitle")
for item in news:
item_parsed = parse_news(item)
if item_parsed[0] <= str(last_id):
found = True
break
all_news.append(item_parsed)
except SocketError as e:
if e.errno != errno.ECONNRESET:
raise
pass
page = page + 1
return all_news
def retrieve_detail(item):
'''Retrive detaill for news item
return is tuple (id, title, url, text)
'''
url = item[2]
html = urlopen(url)
soup = BeautifulSoup(html, 'html.parser')
detail = soup.find(class_='divNewsDetailsText')
detail = detail.get_text()
_list = list(item)
_list.insert(3, detail)
item = tuple(_list)
return item
def royal_order(last_id=-1):
'''Retrive royal orders
if last_id not defiend it will return the max
return list of royal orders tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
orders = []
_news = retrieve_news(royal=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
orders.append(_detail)
return orders
def cabinet_decision(last_id=-1):
<|fim_middle|>
def arrival_news(person, last_id=-1):
'''Retrive only arrival news for person
if last_id not defiend it will return the max
return list of arrival news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, location)...]
'''
arrival_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يصل إلى' in item[1]:
_list = list(item)
_list.insert(3, (item[1].split('يصل إلى'))[1].split('قادماً من')[0])
item = tuple(_list)
arrival_news.append(item)
return arrival_news
def leave_news(person, last_id=-1):
'''Retrive only leave news for person
if last_id not defiend it will return the max
return list of leave news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, locationFromTo)...]
'''
leave_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يغادر' in item[1]:
_list = list(item)
_list.insert(3, item[1].split('يغادر')[1])
item = tuple(_list)
leave_news.append(item)
return leave_news
if __name__ == "__main__":
# just for testing
news = cabinet_decision()
print(news)
<|fim▁end|> | '''Retrive cabinet decisions
if last_id not defiend it will return the max
return list of cabinet decisions tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
decisions = []
_news = retrieve_news(cabinet=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
decisions.append(_detail)
return decisions |
<|file_name|>spa.py<|end_file_name|><|fim▁begin|>from urllib.request import urlopen
from urllib.parse import urlparse, parse_qs
from socket import error as SocketError
import errno
from bs4 import BeautifulSoup
MAX_PAGES_TO_SEARCH = 3
def parse_news(item):
'''Parse news item
return is a tuple(id, title, url)
'''
url = 'http://www.spa.gov.sa' + item['href']
url_parsed = urlparse(url)
qs = parse_qs(url_parsed[4])
id = qs['newsid'][0]
title = item.h2.contents[0]
title = " ".join(title.split())
item_parsed = (id, title, url)
return item_parsed
def retrieve_news(person=0, royal=0, cabinet=0, last_id=-1):
'''Retrieve news for person or royal
person 1= king, 2= crown prince and 3= deputy crown prince
if royal is = 1 news will be retriveved
if last_id not definend it will return the max
return list of news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url)...]
'''
all_news = []
found = False
page = 1
while (page <= MAX_PAGES_TO_SEARCH and not found):
url = ("http://www.spa.gov.sa/ajax/listnews.php?sticky={}&cat=0&cabine"
"t={}&royal={}&lang=ar&pg={}".format(person, cabinet, royal, page))
try:
html = urlopen(url)
soup = BeautifulSoup(html, "html.parser")
news = soup.find_all("a", class_="aNewsTitle")
for item in news:
item_parsed = parse_news(item)
if item_parsed[0] <= str(last_id):
found = True
break
all_news.append(item_parsed)
except SocketError as e:
if e.errno != errno.ECONNRESET:
raise
pass
page = page + 1
return all_news
def retrieve_detail(item):
'''Retrive detaill for news item
return is tuple (id, title, url, text)
'''
url = item[2]
html = urlopen(url)
soup = BeautifulSoup(html, 'html.parser')
detail = soup.find(class_='divNewsDetailsText')
detail = detail.get_text()
_list = list(item)
_list.insert(3, detail)
item = tuple(_list)
return item
def royal_order(last_id=-1):
'''Retrive royal orders
if last_id not defiend it will return the max
return list of royal orders tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
orders = []
_news = retrieve_news(royal=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
orders.append(_detail)
return orders
def cabinet_decision(last_id=-1):
'''Retrive cabinet decisions
if last_id not defiend it will return the max
return list of cabinet decisions tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
decisions = []
_news = retrieve_news(cabinet=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
decisions.append(_detail)
return decisions
def arrival_news(person, last_id=-1):
<|fim_middle|>
rson, last_id=-1):
'''Retrive only leave news for person
if last_id not defiend it will return the max
return list of leave news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, locationFromTo)...]
'''
leave_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يغادر' in item[1]:
_list = list(item)
_list.insert(3, item[1].split('يغادر')[1])
item = tuple(_list)
leave_news.append(item)
return leave_news
if __name__ == "__main__":
# just for testing
news = cabinet_decision()
print(news)
<|fim▁end|> | '''Retrive only arrival news for person
if last_id not defiend it will return the max
return list of arrival news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, location)...]
'''
arrival_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يصل إلى' in item[1]:
_list = list(item)
_list.insert(3, (item[1].split('يصل إلى'))[1].split('قادماً من')[0])
item = tuple(_list)
arrival_news.append(item)
return arrival_news
def leave_news(pe |
<|file_name|>spa.py<|end_file_name|><|fim▁begin|>from urllib.request import urlopen
from urllib.parse import urlparse, parse_qs
from socket import error as SocketError
import errno
from bs4 import BeautifulSoup
MAX_PAGES_TO_SEARCH = 3
def parse_news(item):
'''Parse news item
return is a tuple(id, title, url)
'''
url = 'http://www.spa.gov.sa' + item['href']
url_parsed = urlparse(url)
qs = parse_qs(url_parsed[4])
id = qs['newsid'][0]
title = item.h2.contents[0]
title = " ".join(title.split())
item_parsed = (id, title, url)
return item_parsed
def retrieve_news(person=0, royal=0, cabinet=0, last_id=-1):
'''Retrieve news for person or royal
person 1= king, 2= crown prince and 3= deputy crown prince
if royal is = 1 news will be retriveved
if last_id not definend it will return the max
return list of news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url)...]
'''
all_news = []
found = False
page = 1
while (page <= MAX_PAGES_TO_SEARCH and not found):
url = ("http://www.spa.gov.sa/ajax/listnews.php?sticky={}&cat=0&cabine"
"t={}&royal={}&lang=ar&pg={}".format(person, cabinet, royal, page))
try:
html = urlopen(url)
soup = BeautifulSoup(html, "html.parser")
news = soup.find_all("a", class_="aNewsTitle")
for item in news:
item_parsed = parse_news(item)
if item_parsed[0] <= str(last_id):
found = True
break
all_news.append(item_parsed)
except SocketError as e:
if e.errno != errno.ECONNRESET:
raise
pass
page = page + 1
return all_news
def retrieve_detail(item):
'''Retrive detaill for news item
return is tuple (id, title, url, text)
'''
url = item[2]
html = urlopen(url)
soup = BeautifulSoup(html, 'html.parser')
detail = soup.find(class_='divNewsDetailsText')
detail = detail.get_text()
_list = list(item)
_list.insert(3, detail)
item = tuple(_list)
return item
def royal_order(last_id=-1):
'''Retrive royal orders
if last_id not defiend it will return the max
return list of royal orders tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
orders = []
_news = retrieve_news(royal=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
orders.append(_detail)
return orders
def cabinet_decision(last_id=-1):
'''Retrive cabinet decisions
if last_id not defiend it will return the max
return list of cabinet decisions tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
decisions = []
_news = retrieve_news(cabinet=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
decisions.append(_detail)
return decisions
def arrival_news(person, last_id=-1):
'''Retrive only arrival news for person
if last_id not defiend it will return the max
return list of arrival news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, location)...]
'''
arrival_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يصل إلى' in item[1]:
_list = list(item)
_list.insert(3, (item[1].split('يصل إلى'))[1].split('قادماً من')[0])
item = tuple(_list)
arrival_news.append(item)
return arrival_news
def leave_news(person, last_id=-1):
'''Retrive only leav<|fim_middle|>
# just for testing
news = cabinet_decision()
print(news)
<|fim▁end|> | e news for person
if last_id not defiend it will return the max
return list of leave news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, locationFromTo)...]
'''
leave_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يغادر' in item[1]:
_list = list(item)
_list.insert(3, item[1].split('يغادر')[1])
item = tuple(_list)
leave_news.append(item)
return leave_news
if __name__ == "__main__":
|
<|file_name|>spa.py<|end_file_name|><|fim▁begin|>from urllib.request import urlopen
from urllib.parse import urlparse, parse_qs
from socket import error as SocketError
import errno
from bs4 import BeautifulSoup
MAX_PAGES_TO_SEARCH = 3
def parse_news(item):
'''Parse news item
return is a tuple(id, title, url)
'''
url = 'http://www.spa.gov.sa' + item['href']
url_parsed = urlparse(url)
qs = parse_qs(url_parsed[4])
id = qs['newsid'][0]
title = item.h2.contents[0]
title = " ".join(title.split())
item_parsed = (id, title, url)
return item_parsed
def retrieve_news(person=0, royal=0, cabinet=0, last_id=-1):
'''Retrieve news for person or royal
person 1= king, 2= crown prince and 3= deputy crown prince
if royal is = 1 news will be retriveved
if last_id not definend it will return the max
return list of news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url)...]
'''
all_news = []
found = False
page = 1
while (page <= MAX_PAGES_TO_SEARCH and not found):
url = ("http://www.spa.gov.sa/ajax/listnews.php?sticky={}&cat=0&cabine"
"t={}&royal={}&lang=ar&pg={}".format(person, cabinet, royal, page))
try:
html = urlopen(url)
soup = BeautifulSoup(html, "html.parser")
news = soup.find_all("a", class_="aNewsTitle")
for item in news:
item_parsed = parse_news(item)
if item_parsed[0] <= str(last_id):
<|fim_middle|>
all_news.append(item_parsed)
except SocketError as e:
if e.errno != errno.ECONNRESET:
raise
pass
page = page + 1
return all_news
def retrieve_detail(item):
'''Retrive detaill for news item
return is tuple (id, title, url, text)
'''
url = item[2]
html = urlopen(url)
soup = BeautifulSoup(html, 'html.parser')
detail = soup.find(class_='divNewsDetailsText')
detail = detail.get_text()
_list = list(item)
_list.insert(3, detail)
item = tuple(_list)
return item
def royal_order(last_id=-1):
'''Retrive royal orders
if last_id not defiend it will return the max
return list of royal orders tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
orders = []
_news = retrieve_news(royal=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
orders.append(_detail)
return orders
def cabinet_decision(last_id=-1):
'''Retrive cabinet decisions
if last_id not defiend it will return the max
return list of cabinet decisions tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
decisions = []
_news = retrieve_news(cabinet=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
decisions.append(_detail)
return decisions
def arrival_news(person, last_id=-1):
'''Retrive only arrival news for person
if last_id not defiend it will return the max
return list of arrival news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, location)...]
'''
arrival_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يصل إلى' in item[1]:
_list = list(item)
_list.insert(3, (item[1].split('يصل إلى'))[1].split('قادماً من')[0])
item = tuple(_list)
arrival_news.append(item)
return arrival_news
def leave_news(person, last_id=-1):
'''Retrive only leave news for person
if last_id not defiend it will return the max
return list of leave news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, locationFromTo)...]
'''
leave_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يغادر' in item[1]:
_list = list(item)
_list.insert(3, item[1].split('يغادر')[1])
item = tuple(_list)
leave_news.append(item)
return leave_news
if __name__ == "__main__":
# just for testing
news = cabinet_decision()
print(news)
<|fim▁end|> | found = True
break |
<|file_name|>spa.py<|end_file_name|><|fim▁begin|>from urllib.request import urlopen
from urllib.parse import urlparse, parse_qs
from socket import error as SocketError
import errno
from bs4 import BeautifulSoup
MAX_PAGES_TO_SEARCH = 3
def parse_news(item):
'''Parse news item
return is a tuple(id, title, url)
'''
url = 'http://www.spa.gov.sa' + item['href']
url_parsed = urlparse(url)
qs = parse_qs(url_parsed[4])
id = qs['newsid'][0]
title = item.h2.contents[0]
title = " ".join(title.split())
item_parsed = (id, title, url)
return item_parsed
def retrieve_news(person=0, royal=0, cabinet=0, last_id=-1):
'''Retrieve news for person or royal
person 1= king, 2= crown prince and 3= deputy crown prince
if royal is = 1 news will be retriveved
if last_id not definend it will return the max
return list of news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url)...]
'''
all_news = []
found = False
page = 1
while (page <= MAX_PAGES_TO_SEARCH and not found):
url = ("http://www.spa.gov.sa/ajax/listnews.php?sticky={}&cat=0&cabine"
"t={}&royal={}&lang=ar&pg={}".format(person, cabinet, royal, page))
try:
html = urlopen(url)
soup = BeautifulSoup(html, "html.parser")
news = soup.find_all("a", class_="aNewsTitle")
for item in news:
item_parsed = parse_news(item)
if item_parsed[0] <= str(last_id):
found = True
break
all_news.append(item_parsed)
except SocketError as e:
if e.errno != errno.ECONNRESET:
<|fim_middle|>
pass
page = page + 1
return all_news
def retrieve_detail(item):
'''Retrive detaill for news item
return is tuple (id, title, url, text)
'''
url = item[2]
html = urlopen(url)
soup = BeautifulSoup(html, 'html.parser')
detail = soup.find(class_='divNewsDetailsText')
detail = detail.get_text()
_list = list(item)
_list.insert(3, detail)
item = tuple(_list)
return item
def royal_order(last_id=-1):
'''Retrive royal orders
if last_id not defiend it will return the max
return list of royal orders tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
orders = []
_news = retrieve_news(royal=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
orders.append(_detail)
return orders
def cabinet_decision(last_id=-1):
'''Retrive cabinet decisions
if last_id not defiend it will return the max
return list of cabinet decisions tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
decisions = []
_news = retrieve_news(cabinet=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
decisions.append(_detail)
return decisions
def arrival_news(person, last_id=-1):
'''Retrive only arrival news for person
if last_id not defiend it will return the max
return list of arrival news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, location)...]
'''
arrival_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يصل إلى' in item[1]:
_list = list(item)
_list.insert(3, (item[1].split('يصل إلى'))[1].split('قادماً من')[0])
item = tuple(_list)
arrival_news.append(item)
return arrival_news
def leave_news(person, last_id=-1):
'''Retrive only leave news for person
if last_id not defiend it will return the max
return list of leave news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, locationFromTo)...]
'''
leave_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يغادر' in item[1]:
_list = list(item)
_list.insert(3, item[1].split('يغادر')[1])
item = tuple(_list)
leave_news.append(item)
return leave_news
if __name__ == "__main__":
# just for testing
news = cabinet_decision()
print(news)
<|fim▁end|> | raise |
<|file_name|>spa.py<|end_file_name|><|fim▁begin|>from urllib.request import urlopen
from urllib.parse import urlparse, parse_qs
from socket import error as SocketError
import errno
from bs4 import BeautifulSoup
MAX_PAGES_TO_SEARCH = 3
def parse_news(item):
'''Parse news item
return is a tuple(id, title, url)
'''
url = 'http://www.spa.gov.sa' + item['href']
url_parsed = urlparse(url)
qs = parse_qs(url_parsed[4])
id = qs['newsid'][0]
title = item.h2.contents[0]
title = " ".join(title.split())
item_parsed = (id, title, url)
return item_parsed
def retrieve_news(person=0, royal=0, cabinet=0, last_id=-1):
'''Retrieve news for person or royal
person 1= king, 2= crown prince and 3= deputy crown prince
if royal is = 1 news will be retriveved
if last_id not definend it will return the max
return list of news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url)...]
'''
all_news = []
found = False
page = 1
while (page <= MAX_PAGES_TO_SEARCH and not found):
url = ("http://www.spa.gov.sa/ajax/listnews.php?sticky={}&cat=0&cabine"
"t={}&royal={}&lang=ar&pg={}".format(person, cabinet, royal, page))
try:
html = urlopen(url)
soup = BeautifulSoup(html, "html.parser")
news = soup.find_all("a", class_="aNewsTitle")
for item in news:
item_parsed = parse_news(item)
if item_parsed[0] <= str(last_id):
found = True
break
all_news.append(item_parsed)
except SocketError as e:
if e.errno != errno.ECONNRESET:
raise
pass
page = page + 1
return all_news
def retrieve_detail(item):
'''Retrive detaill for news item
return is tuple (id, title, url, text)
'''
url = item[2]
html = urlopen(url)
soup = BeautifulSoup(html, 'html.parser')
detail = soup.find(class_='divNewsDetailsText')
detail = detail.get_text()
_list = list(item)
_list.insert(3, detail)
item = tuple(_list)
return item
def royal_order(last_id=-1):
'''Retrive royal orders
if last_id not defiend it will return the max
return list of royal orders tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
orders = []
_news = retrieve_news(royal=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
orders.append(_detail)
return orders
def cabinet_decision(last_id=-1):
'''Retrive cabinet decisions
if last_id not defiend it will return the max
return list of cabinet decisions tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
decisions = []
_news = retrieve_news(cabinet=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
decisions.append(_detail)
return decisions
def arrival_news(person, last_id=-1):
'''Retrive only arrival news for person
if last_id not defiend it will return the max
return list of arrival news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, location)...]
'''
arrival_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يصل إلى' in item[1]:
_list <|fim_middle|>
news
def leave_news(person, last_id=-1):
'''Retrive only leave news for person
if last_id not defiend it will return the max
return list of leave news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, locationFromTo)...]
'''
leave_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يغادر' in item[1]:
_list = list(item)
_list.insert(3, item[1].split('يغادر')[1])
item = tuple(_list)
leave_news.append(item)
return leave_news
if __name__ == "__main__":
# just for testing
news = cabinet_decision()
print(news)
<|fim▁end|> | = list(item)
_list.insert(3, (item[1].split('يصل إلى'))[1].split('قادماً من')[0])
item = tuple(_list)
arrival_news.append(item)
return arrival_ |
<|file_name|>spa.py<|end_file_name|><|fim▁begin|>from urllib.request import urlopen
from urllib.parse import urlparse, parse_qs
from socket import error as SocketError
import errno
from bs4 import BeautifulSoup
MAX_PAGES_TO_SEARCH = 3
def parse_news(item):
'''Parse news item
return is a tuple(id, title, url)
'''
url = 'http://www.spa.gov.sa' + item['href']
url_parsed = urlparse(url)
qs = parse_qs(url_parsed[4])
id = qs['newsid'][0]
title = item.h2.contents[0]
title = " ".join(title.split())
item_parsed = (id, title, url)
return item_parsed
def retrieve_news(person=0, royal=0, cabinet=0, last_id=-1):
'''Retrieve news for person or royal
person 1= king, 2= crown prince and 3= deputy crown prince
if royal is = 1 news will be retriveved
if last_id not definend it will return the max
return list of news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url)...]
'''
all_news = []
found = False
page = 1
while (page <= MAX_PAGES_TO_SEARCH and not found):
url = ("http://www.spa.gov.sa/ajax/listnews.php?sticky={}&cat=0&cabine"
"t={}&royal={}&lang=ar&pg={}".format(person, cabinet, royal, page))
try:
html = urlopen(url)
soup = BeautifulSoup(html, "html.parser")
news = soup.find_all("a", class_="aNewsTitle")
for item in news:
item_parsed = parse_news(item)
if item_parsed[0] <= str(last_id):
found = True
break
all_news.append(item_parsed)
except SocketError as e:
if e.errno != errno.ECONNRESET:
raise
pass
page = page + 1
return all_news
def retrieve_detail(item):
'''Retrive detaill for news item
return is tuple (id, title, url, text)
'''
url = item[2]
html = urlopen(url)
soup = BeautifulSoup(html, 'html.parser')
detail = soup.find(class_='divNewsDetailsText')
detail = detail.get_text()
_list = list(item)
_list.insert(3, detail)
item = tuple(_list)
return item
def royal_order(last_id=-1):
'''Retrive royal orders
if last_id not defiend it will return the max
return list of royal orders tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
orders = []
_news = retrieve_news(royal=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
orders.append(_detail)
return orders
def cabinet_decision(last_id=-1):
'''Retrive cabinet decisions
if last_id not defiend it will return the max
return list of cabinet decisions tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
decisions = []
_news = retrieve_news(cabinet=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
decisions.append(_detail)
return decisions
def arrival_news(person, last_id=-1):
'''Retrive only arrival news for person
if last_id not defiend it will return the max
return list of arrival news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, location)...]
'''
arrival_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يصل إلى' in item[1]:
_list = list(item)
_list.insert(3, (item[1].split('يصل إلى'))[1].split('قادماً من')[0])
item = tuple(_list)
arrival_news.append(item)
return arrival_news
def leave_news(person, last_id=-1):
'''Retrive only leave news for person
if last_id not defiend it will return the max
return list of leave news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, locationFromTo)...]
'''
leave_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يغادر' in item[1]:
_list = list(item)
<|fim_middle|>
name__ == "__main__":
# just for testing
news = cabinet_decision()
print(news)
<|fim▁end|> | _list.insert(3, item[1].split('يغادر')[1])
item = tuple(_list)
leave_news.append(item)
return leave_news
if __ |
<|file_name|>spa.py<|end_file_name|><|fim▁begin|>from urllib.request import urlopen
from urllib.parse import urlparse, parse_qs
from socket import error as SocketError
import errno
from bs4 import BeautifulSoup
MAX_PAGES_TO_SEARCH = 3
def parse_news(item):
'''Parse news item
return is a tuple(id, title, url)
'''
url = 'http://www.spa.gov.sa' + item['href']
url_parsed = urlparse(url)
qs = parse_qs(url_parsed[4])
id = qs['newsid'][0]
title = item.h2.contents[0]
title = " ".join(title.split())
item_parsed = (id, title, url)
return item_parsed
def retrieve_news(person=0, royal=0, cabinet=0, last_id=-1):
'''Retrieve news for person or royal
person 1= king, 2= crown prince and 3= deputy crown prince
if royal is = 1 news will be retriveved
if last_id not definend it will return the max
return list of news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url)...]
'''
all_news = []
found = False
page = 1
while (page <= MAX_PAGES_TO_SEARCH and not found):
url = ("http://www.spa.gov.sa/ajax/listnews.php?sticky={}&cat=0&cabine"
"t={}&royal={}&lang=ar&pg={}".format(person, cabinet, royal, page))
try:
html = urlopen(url)
soup = BeautifulSoup(html, "html.parser")
news = soup.find_all("a", class_="aNewsTitle")
for item in news:
item_parsed = parse_news(item)
if item_parsed[0] <= str(last_id):
found = True
break
all_news.append(item_parsed)
except SocketError as e:
if e.errno != errno.ECONNRESET:
raise
pass
page = page + 1
return all_news
def retrieve_detail(item):
'''Retrive detaill for news item
return is tuple (id, title, url, text)
'''
url = item[2]
html = urlopen(url)
soup = BeautifulSoup(html, 'html.parser')
detail = soup.find(class_='divNewsDetailsText')
detail = detail.get_text()
_list = list(item)
_list.insert(3, detail)
item = tuple(_list)
return item
def royal_order(last_id=-1):
'''Retrive royal orders
if last_id not defiend it will return the max
return list of royal orders tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
orders = []
_news = retrieve_news(royal=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
orders.append(_detail)
return orders
def cabinet_decision(last_id=-1):
'''Retrive cabinet decisions
if last_id not defiend it will return the max
return list of cabinet decisions tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
decisions = []
_news = retrieve_news(cabinet=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
decisions.append(_detail)
return decisions
def arrival_news(person, last_id=-1):
'''Retrive only arrival news for person
if last_id not defiend it will return the max
return list of arrival news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, location)...]
'''
arrival_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يصل إلى' in item[1]:
_list = list(item)
_list.insert(3, (item[1].split('يصل إلى'))[1].split('قادماً من')[0])
item = tuple(_list)
arrival_news.append(item)
return arrival_news
def leave_news(person, last_id=-1):
'''Retrive only leave news for person
if last_id not defiend it will return the max
return list of leave news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, locationFromTo)...]
'''
leave_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يغادر' in item[1]:
_list = list(item)
_list.insert(3, item[1].split('يغادر')[1])
item = tuple(_list)
leave_news.append(item)
return leave_news
if __name__ == "__main__":
# just for testing
news = cabinet_decision()
<|fim_middle|>
<|fim▁end|> | print(news)
|
<|file_name|>spa.py<|end_file_name|><|fim▁begin|>from urllib.request import urlopen
from urllib.parse import urlparse, parse_qs
from socket import error as SocketError
import errno
from bs4 import BeautifulSoup
MAX_PAGES_TO_SEARCH = 3
def <|fim_middle|>(item):
'''Parse news item
return is a tuple(id, title, url)
'''
url = 'http://www.spa.gov.sa' + item['href']
url_parsed = urlparse(url)
qs = parse_qs(url_parsed[4])
id = qs['newsid'][0]
title = item.h2.contents[0]
title = " ".join(title.split())
item_parsed = (id, title, url)
return item_parsed
def retrieve_news(person=0, royal=0, cabinet=0, last_id=-1):
'''Retrieve news for person or royal
person 1= king, 2= crown prince and 3= deputy crown prince
if royal is = 1 news will be retriveved
if last_id not definend it will return the max
return list of news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url)...]
'''
all_news = []
found = False
page = 1
while (page <= MAX_PAGES_TO_SEARCH and not found):
url = ("http://www.spa.gov.sa/ajax/listnews.php?sticky={}&cat=0&cabine"
"t={}&royal={}&lang=ar&pg={}".format(person, cabinet, royal, page))
try:
html = urlopen(url)
soup = BeautifulSoup(html, "html.parser")
news = soup.find_all("a", class_="aNewsTitle")
for item in news:
item_parsed = parse_news(item)
if item_parsed[0] <= str(last_id):
found = True
break
all_news.append(item_parsed)
except SocketError as e:
if e.errno != errno.ECONNRESET:
raise
pass
page = page + 1
return all_news
def retrieve_detail(item):
'''Retrive detaill for news item
return is tuple (id, title, url, text)
'''
url = item[2]
html = urlopen(url)
soup = BeautifulSoup(html, 'html.parser')
detail = soup.find(class_='divNewsDetailsText')
detail = detail.get_text()
_list = list(item)
_list.insert(3, detail)
item = tuple(_list)
return item
def royal_order(last_id=-1):
'''Retrive royal orders
if last_id not defiend it will return the max
return list of royal orders tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
orders = []
_news = retrieve_news(royal=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
orders.append(_detail)
return orders
def cabinet_decision(last_id=-1):
'''Retrive cabinet decisions
if last_id not defiend it will return the max
return list of cabinet decisions tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
decisions = []
_news = retrieve_news(cabinet=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
decisions.append(_detail)
return decisions
def arrival_news(person, last_id=-1):
'''Retrive only arrival news for person
if last_id not defiend it will return the max
return list of arrival news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, location)...]
'''
arrival_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يصل إلى' in item[1]:
_list = list(item)
_list.insert(3, (item[1].split('يصل إلى'))[1].split('قادماً من')[0])
item = tuple(_list)
arrival_news.append(item)
return arrival_news
def leave_news(person, last_id=-1):
'''Retrive only leave news for person
if last_id not defiend it will return the max
return list of leave news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, locationFromTo)...]
'''
leave_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يغادر' in item[1]:
_list = list(item)
_list.insert(3, item[1].split('يغادر')[1])
item = tuple(_list)
leave_news.append(item)
return leave_news
if __name__ == "__main__":
# just for testing
news = cabinet_decision()
print(news)
<|fim▁end|> | parse_news |
<|file_name|>spa.py<|end_file_name|><|fim▁begin|>from urllib.request import urlopen
from urllib.parse import urlparse, parse_qs
from socket import error as SocketError
import errno
from bs4 import BeautifulSoup
MAX_PAGES_TO_SEARCH = 3
def parse_news(item):
'''Parse news item
return is a tuple(id, title, url)
'''
url = 'http://www.spa.gov.sa' + item['href']
url_parsed = urlparse(url)
qs = parse_qs(url_parsed[4])
id = qs['newsid'][0]
title = item.h2.contents[0]
title = " ".join(title.split())
item_parsed = (id, title, url)
return item_parsed
def <|fim_middle|>(person=0, royal=0, cabinet=0, last_id=-1):
'''Retrieve news for person or royal
person 1= king, 2= crown prince and 3= deputy crown prince
if royal is = 1 news will be retriveved
if last_id not definend it will return the max
return list of news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url)...]
'''
all_news = []
found = False
page = 1
while (page <= MAX_PAGES_TO_SEARCH and not found):
url = ("http://www.spa.gov.sa/ajax/listnews.php?sticky={}&cat=0&cabine"
"t={}&royal={}&lang=ar&pg={}".format(person, cabinet, royal, page))
try:
html = urlopen(url)
soup = BeautifulSoup(html, "html.parser")
news = soup.find_all("a", class_="aNewsTitle")
for item in news:
item_parsed = parse_news(item)
if item_parsed[0] <= str(last_id):
found = True
break
all_news.append(item_parsed)
except SocketError as e:
if e.errno != errno.ECONNRESET:
raise
pass
page = page + 1
return all_news
def retrieve_detail(item):
'''Retrive detaill for news item
return is tuple (id, title, url, text)
'''
url = item[2]
html = urlopen(url)
soup = BeautifulSoup(html, 'html.parser')
detail = soup.find(class_='divNewsDetailsText')
detail = detail.get_text()
_list = list(item)
_list.insert(3, detail)
item = tuple(_list)
return item
def royal_order(last_id=-1):
'''Retrive royal orders
if last_id not defiend it will return the max
return list of royal orders tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
orders = []
_news = retrieve_news(royal=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
orders.append(_detail)
return orders
def cabinet_decision(last_id=-1):
'''Retrive cabinet decisions
if last_id not defiend it will return the max
return list of cabinet decisions tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
decisions = []
_news = retrieve_news(cabinet=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
decisions.append(_detail)
return decisions
def arrival_news(person, last_id=-1):
'''Retrive only arrival news for person
if last_id not defiend it will return the max
return list of arrival news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, location)...]
'''
arrival_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يصل إلى' in item[1]:
_list = list(item)
_list.insert(3, (item[1].split('يصل إلى'))[1].split('قادماً من')[0])
item = tuple(_list)
arrival_news.append(item)
return arrival_news
def leave_news(person, last_id=-1):
'''Retrive only leave news for person
if last_id not defiend it will return the max
return list of leave news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, locationFromTo)...]
'''
leave_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يغادر' in item[1]:
_list = list(item)
_list.insert(3, item[1].split('يغادر')[1])
item = tuple(_list)
leave_news.append(item)
return leave_news
if __name__ == "__main__":
# just for testing
news = cabinet_decision()
print(news)
<|fim▁end|> | retrieve_news |
<|file_name|>spa.py<|end_file_name|><|fim▁begin|>from urllib.request import urlopen
from urllib.parse import urlparse, parse_qs
from socket import error as SocketError
import errno
from bs4 import BeautifulSoup
MAX_PAGES_TO_SEARCH = 3
def parse_news(item):
'''Parse news item
return is a tuple(id, title, url)
'''
url = 'http://www.spa.gov.sa' + item['href']
url_parsed = urlparse(url)
qs = parse_qs(url_parsed[4])
id = qs['newsid'][0]
title = item.h2.contents[0]
title = " ".join(title.split())
item_parsed = (id, title, url)
return item_parsed
def retrieve_news(person=0, royal=0, cabinet=0, last_id=-1):
'''Retrieve news for person or royal
person 1= king, 2= crown prince and 3= deputy crown prince
if royal is = 1 news will be retriveved
if last_id not definend it will return the max
return list of news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url)...]
'''
all_news = []
found = False
page = 1
while (page <= MAX_PAGES_TO_SEARCH and not found):
url = ("http://www.spa.gov.sa/ajax/listnews.php?sticky={}&cat=0&cabine"
"t={}&royal={}&lang=ar&pg={}".format(person, cabinet, royal, page))
try:
html = urlopen(url)
soup = BeautifulSoup(html, "html.parser")
news = soup.find_all("a", class_="aNewsTitle")
for item in news:
item_parsed = parse_news(item)
if item_parsed[0] <= str(last_id):
found = True
break
all_news.append(item_parsed)
except SocketError as e:
if e.errno != errno.ECONNRESET:
raise
pass
page = page + 1
return all_news
def <|fim_middle|>(item):
'''Retrive detaill for news item
return is tuple (id, title, url, text)
'''
url = item[2]
html = urlopen(url)
soup = BeautifulSoup(html, 'html.parser')
detail = soup.find(class_='divNewsDetailsText')
detail = detail.get_text()
_list = list(item)
_list.insert(3, detail)
item = tuple(_list)
return item
def royal_order(last_id=-1):
'''Retrive royal orders
if last_id not defiend it will return the max
return list of royal orders tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
orders = []
_news = retrieve_news(royal=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
orders.append(_detail)
return orders
def cabinet_decision(last_id=-1):
'''Retrive cabinet decisions
if last_id not defiend it will return the max
return list of cabinet decisions tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
decisions = []
_news = retrieve_news(cabinet=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
decisions.append(_detail)
return decisions
def arrival_news(person, last_id=-1):
'''Retrive only arrival news for person
if last_id not defiend it will return the max
return list of arrival news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, location)...]
'''
arrival_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يصل إلى' in item[1]:
_list = list(item)
_list.insert(3, (item[1].split('يصل إلى'))[1].split('قادماً من')[0])
item = tuple(_list)
arrival_news.append(item)
return arrival_news
def leave_news(person, last_id=-1):
'''Retrive only leave news for person
if last_id not defiend it will return the max
return list of leave news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, locationFromTo)...]
'''
leave_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يغادر' in item[1]:
_list = list(item)
_list.insert(3, item[1].split('يغادر')[1])
item = tuple(_list)
leave_news.append(item)
return leave_news
if __name__ == "__main__":
# just for testing
news = cabinet_decision()
print(news)
<|fim▁end|> | retrieve_detail |
<|file_name|>spa.py<|end_file_name|><|fim▁begin|>from urllib.request import urlopen
from urllib.parse import urlparse, parse_qs
from socket import error as SocketError
import errno
from bs4 import BeautifulSoup
MAX_PAGES_TO_SEARCH = 3
def parse_news(item):
'''Parse news item
return is a tuple(id, title, url)
'''
url = 'http://www.spa.gov.sa' + item['href']
url_parsed = urlparse(url)
qs = parse_qs(url_parsed[4])
id = qs['newsid'][0]
title = item.h2.contents[0]
title = " ".join(title.split())
item_parsed = (id, title, url)
return item_parsed
def retrieve_news(person=0, royal=0, cabinet=0, last_id=-1):
'''Retrieve news for person or royal
person 1= king, 2= crown prince and 3= deputy crown prince
if royal is = 1 news will be retriveved
if last_id not definend it will return the max
return list of news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url)...]
'''
all_news = []
found = False
page = 1
while (page <= MAX_PAGES_TO_SEARCH and not found):
url = ("http://www.spa.gov.sa/ajax/listnews.php?sticky={}&cat=0&cabine"
"t={}&royal={}&lang=ar&pg={}".format(person, cabinet, royal, page))
try:
html = urlopen(url)
soup = BeautifulSoup(html, "html.parser")
news = soup.find_all("a", class_="aNewsTitle")
for item in news:
item_parsed = parse_news(item)
if item_parsed[0] <= str(last_id):
found = True
break
all_news.append(item_parsed)
except SocketError as e:
if e.errno != errno.ECONNRESET:
raise
pass
page = page + 1
return all_news
def retrieve_detail(item):
'''Retrive detaill for news item
return is tuple (id, title, url, text)
'''
url = item[2]
html = urlopen(url)
soup = BeautifulSoup(html, 'html.parser')
detail = soup.find(class_='divNewsDetailsText')
detail = detail.get_text()
_list = list(item)
_list.insert(3, detail)
item = tuple(_list)
return item
def <|fim_middle|>(last_id=-1):
'''Retrive royal orders
if last_id not defiend it will return the max
return list of royal orders tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
orders = []
_news = retrieve_news(royal=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
orders.append(_detail)
return orders
def cabinet_decision(last_id=-1):
'''Retrive cabinet decisions
if last_id not defiend it will return the max
return list of cabinet decisions tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
decisions = []
_news = retrieve_news(cabinet=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
decisions.append(_detail)
return decisions
def arrival_news(person, last_id=-1):
'''Retrive only arrival news for person
if last_id not defiend it will return the max
return list of arrival news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, location)...]
'''
arrival_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يصل إلى' in item[1]:
_list = list(item)
_list.insert(3, (item[1].split('يصل إلى'))[1].split('قادماً من')[0])
item = tuple(_list)
arrival_news.append(item)
return arrival_news
def leave_news(person, last_id=-1):
'''Retrive only leave news for person
if last_id not defiend it will return the max
return list of leave news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, locationFromTo)...]
'''
leave_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يغادر' in item[1]:
_list = list(item)
_list.insert(3, item[1].split('يغادر')[1])
item = tuple(_list)
leave_news.append(item)
return leave_news
if __name__ == "__main__":
# just for testing
news = cabinet_decision()
print(news)
<|fim▁end|> | royal_order |
<|file_name|>spa.py<|end_file_name|><|fim▁begin|>from urllib.request import urlopen
from urllib.parse import urlparse, parse_qs
from socket import error as SocketError
import errno
from bs4 import BeautifulSoup
MAX_PAGES_TO_SEARCH = 3
def parse_news(item):
'''Parse news item
return is a tuple(id, title, url)
'''
url = 'http://www.spa.gov.sa' + item['href']
url_parsed = urlparse(url)
qs = parse_qs(url_parsed[4])
id = qs['newsid'][0]
title = item.h2.contents[0]
title = " ".join(title.split())
item_parsed = (id, title, url)
return item_parsed
def retrieve_news(person=0, royal=0, cabinet=0, last_id=-1):
'''Retrieve news for person or royal
person 1= king, 2= crown prince and 3= deputy crown prince
if royal is = 1 news will be retriveved
if last_id not definend it will return the max
return list of news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url)...]
'''
all_news = []
found = False
page = 1
while (page <= MAX_PAGES_TO_SEARCH and not found):
url = ("http://www.spa.gov.sa/ajax/listnews.php?sticky={}&cat=0&cabine"
"t={}&royal={}&lang=ar&pg={}".format(person, cabinet, royal, page))
try:
html = urlopen(url)
soup = BeautifulSoup(html, "html.parser")
news = soup.find_all("a", class_="aNewsTitle")
for item in news:
item_parsed = parse_news(item)
if item_parsed[0] <= str(last_id):
found = True
break
all_news.append(item_parsed)
except SocketError as e:
if e.errno != errno.ECONNRESET:
raise
pass
page = page + 1
return all_news
def retrieve_detail(item):
'''Retrive detaill for news item
return is tuple (id, title, url, text)
'''
url = item[2]
html = urlopen(url)
soup = BeautifulSoup(html, 'html.parser')
detail = soup.find(class_='divNewsDetailsText')
detail = detail.get_text()
_list = list(item)
_list.insert(3, detail)
item = tuple(_list)
return item
def royal_order(last_id=-1):
'''Retrive royal orders
if last_id not defiend it will return the max
return list of royal orders tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
orders = []
_news = retrieve_news(royal=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
orders.append(_detail)
return orders
def <|fim_middle|>(last_id=-1):
'''Retrive cabinet decisions
if last_id not defiend it will return the max
return list of cabinet decisions tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
decisions = []
_news = retrieve_news(cabinet=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
decisions.append(_detail)
return decisions
def arrival_news(person, last_id=-1):
'''Retrive only arrival news for person
if last_id not defiend it will return the max
return list of arrival news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, location)...]
'''
arrival_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يصل إلى' in item[1]:
_list = list(item)
_list.insert(3, (item[1].split('يصل إلى'))[1].split('قادماً من')[0])
item = tuple(_list)
arrival_news.append(item)
return arrival_news
def leave_news(person, last_id=-1):
'''Retrive only leave news for person
if last_id not defiend it will return the max
return list of leave news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, locationFromTo)...]
'''
leave_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يغادر' in item[1]:
_list = list(item)
_list.insert(3, item[1].split('يغادر')[1])
item = tuple(_list)
leave_news.append(item)
return leave_news
if __name__ == "__main__":
# just for testing
news = cabinet_decision()
print(news)
<|fim▁end|> | cabinet_decision |
<|file_name|>spa.py<|end_file_name|><|fim▁begin|>from urllib.request import urlopen
from urllib.parse import urlparse, parse_qs
from socket import error as SocketError
import errno
from bs4 import BeautifulSoup
MAX_PAGES_TO_SEARCH = 3
def parse_news(item):
'''Parse news item
return is a tuple(id, title, url)
'''
url = 'http://www.spa.gov.sa' + item['href']
url_parsed = urlparse(url)
qs = parse_qs(url_parsed[4])
id = qs['newsid'][0]
title = item.h2.contents[0]
title = " ".join(title.split())
item_parsed = (id, title, url)
return item_parsed
def retrieve_news(person=0, royal=0, cabinet=0, last_id=-1):
'''Retrieve news for person or royal
person 1= king, 2= crown prince and 3= deputy crown prince
if royal is = 1 news will be retriveved
if last_id not definend it will return the max
return list of news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url)...]
'''
all_news = []
found = False
page = 1
while (page <= MAX_PAGES_TO_SEARCH and not found):
url = ("http://www.spa.gov.sa/ajax/listnews.php?sticky={}&cat=0&cabine"
"t={}&royal={}&lang=ar&pg={}".format(person, cabinet, royal, page))
try:
html = urlopen(url)
soup = BeautifulSoup(html, "html.parser")
news = soup.find_all("a", class_="aNewsTitle")
for item in news:
item_parsed = parse_news(item)
if item_parsed[0] <= str(last_id):
found = True
break
all_news.append(item_parsed)
except SocketError as e:
if e.errno != errno.ECONNRESET:
raise
pass
page = page + 1
return all_news
def retrieve_detail(item):
'''Retrive detaill for news item
return is tuple (id, title, url, text)
'''
url = item[2]
html = urlopen(url)
soup = BeautifulSoup(html, 'html.parser')
detail = soup.find(class_='divNewsDetailsText')
detail = detail.get_text()
_list = list(item)
_list.insert(3, detail)
item = tuple(_list)
return item
def royal_order(last_id=-1):
'''Retrive royal orders
if last_id not defiend it will return the max
return list of royal orders tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
orders = []
_news = retrieve_news(royal=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
orders.append(_detail)
return orders
def cabinet_decision(last_id=-1):
'''Retrive cabinet decisions
if last_id not defiend it will return the max
return list of cabinet decisions tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
decisions = []
_news = retrieve_news(cabinet=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
decisions.append(_detail)
return decisions
def <|fim_middle|>(person, last_id=-1):
'''Retrive only arrival news for person
if last_id not defiend it will return the max
return list of arrival news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, location)...]
'''
arrival_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يصل إلى' in item[1]:
_list = list(item)
_list.insert(3, (item[1].split('يصل إلى'))[1].split('قادماً من')[0])
item = tuple(_list)
arrival_news.append(item)
return arrival_news
def leave_news(person, last_id=-1):
'''Retrive only leave news for person
if last_id not defiend it will return the max
return list of leave news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, locationFromTo)...]
'''
leave_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يغادر' in item[1]:
_list = list(item)
_list.insert(3, item[1].split('يغادر')[1])
item = tuple(_list)
leave_news.append(item)
return leave_news
if __name__ == "__main__":
# just for testing
news = cabinet_decision()
print(news)
<|fim▁end|> | arrival_news |
<|file_name|>spa.py<|end_file_name|><|fim▁begin|>from urllib.request import urlopen
from urllib.parse import urlparse, parse_qs
from socket import error as SocketError
import errno
from bs4 import BeautifulSoup
MAX_PAGES_TO_SEARCH = 3
def parse_news(item):
'''Parse news item
return is a tuple(id, title, url)
'''
url = 'http://www.spa.gov.sa' + item['href']
url_parsed = urlparse(url)
qs = parse_qs(url_parsed[4])
id = qs['newsid'][0]
title = item.h2.contents[0]
title = " ".join(title.split())
item_parsed = (id, title, url)
return item_parsed
def retrieve_news(person=0, royal=0, cabinet=0, last_id=-1):
'''Retrieve news for person or royal
person 1= king, 2= crown prince and 3= deputy crown prince
if royal is = 1 news will be retriveved
if last_id not definend it will return the max
return list of news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url)...]
'''
all_news = []
found = False
page = 1
while (page <= MAX_PAGES_TO_SEARCH and not found):
url = ("http://www.spa.gov.sa/ajax/listnews.php?sticky={}&cat=0&cabine"
"t={}&royal={}&lang=ar&pg={}".format(person, cabinet, royal, page))
try:
html = urlopen(url)
soup = BeautifulSoup(html, "html.parser")
news = soup.find_all("a", class_="aNewsTitle")
for item in news:
item_parsed = parse_news(item)
if item_parsed[0] <= str(last_id):
found = True
break
all_news.append(item_parsed)
except SocketError as e:
if e.errno != errno.ECONNRESET:
raise
pass
page = page + 1
return all_news
def retrieve_detail(item):
'''Retrive detaill for news item
return is tuple (id, title, url, text)
'''
url = item[2]
html = urlopen(url)
soup = BeautifulSoup(html, 'html.parser')
detail = soup.find(class_='divNewsDetailsText')
detail = detail.get_text()
_list = list(item)
_list.insert(3, detail)
item = tuple(_list)
return item
def royal_order(last_id=-1):
'''Retrive royal orders
if last_id not defiend it will return the max
return list of royal orders tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
orders = []
_news = retrieve_news(royal=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
orders.append(_detail)
return orders
def cabinet_decision(last_id=-1):
'''Retrive cabinet decisions
if last_id not defiend it will return the max
return list of cabinet decisions tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
decisions = []
_news = retrieve_news(cabinet=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
decisions.append(_detail)
return decisions
def arrival_news(person, last_id=-1):
'''Retrive only arrival news for person
if last_id not defiend it will return the max
return list of arrival news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, location)...]
'''
arrival_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يصل إلى' in item[1]:
_list = list(item)
_list.insert(3, (item[1].split('يصل إلى'))[1].split('قادماً من')[0])
item = tuple(_list)
arrival_news.append(item)
return arrival_news
def leave_news(person, l<|fim_middle|>:
'''Retrive only leave news for person
if last_id not defiend it will return the max
return list of leave news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, locationFromTo)...]
'''
leave_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يغادر' in item[1]:
_list = list(item)
_list.insert(3, item[1].split('يغادر')[1])
item = tuple(_list)
leave_news.append(item)
return leave_news
if __name__ == "__main__":
# just for testing
news = cabinet_decision()
print(news)
<|fim▁end|> | ast_id=-1) |
<|file_name|>player.py<|end_file_name|><|fim▁begin|>#!/Users/wuga/Documents/website/wuga/env/bin/python2.7
#
# The Python Imaging Library
# $Id$
#
from __future__ import print_function
import sys
if sys.version_info[0] > 2:
import tkinter
else:
import Tkinter as tkinter
from PIL import Image, ImageTk
# --------------------------------------------------------------------
# an image animation player
class UI(tkinter.Label):
def __init__(self, master, im):
if isinstance(im, list):
# list of images
self.im = im[1:]
im = self.im[0]
else:
# sequence
self.im = im
if im.mode == "1":
self.image = ImageTk.BitmapImage(im, foreground="white")
else:
self.image = ImageTk.PhotoImage(im)
tkinter.Label.__init__(self, master, image=self.image, bg="black", bd=0)
self.update()
duration = im.info.get("duration", 100)
self.after(duration, self.next)
def next(self):
if isinstance(self.im, list):
try:
im = self.im[0]
del self.im[0]
self.image.paste(im)
except IndexError:
return # end of list
else:
try:
im = self.im
im.seek(im.tell() + 1)
self.image.paste(im)
except EOFError:
return # end of file
duration = im.info.get("duration", 100)
self.after(duration, self.next)
self.update_idletasks()
# --------------------------------------------------------------------
# script interface
if __name__ == "__main__":
<|fim▁hole|> sys.exit(1)
filename = sys.argv[1]
root = tkinter.Tk()
root.title(filename)
if len(sys.argv) > 2:
# list of images
print("loading...")
im = []
for filename in sys.argv[1:]:
im.append(Image.open(filename))
else:
# sequence
im = Image.open(filename)
UI(root, im).pack()
root.mainloop()<|fim▁end|> | if not sys.argv[1:]:
print("Syntax: python player.py imagefile(s)") |
<|file_name|>player.py<|end_file_name|><|fim▁begin|>#!/Users/wuga/Documents/website/wuga/env/bin/python2.7
#
# The Python Imaging Library
# $Id$
#
from __future__ import print_function
import sys
if sys.version_info[0] > 2:
import tkinter
else:
import Tkinter as tkinter
from PIL import Image, ImageTk
# --------------------------------------------------------------------
# an image animation player
class UI(tkinter.Label):
<|fim_middle|>
# --------------------------------------------------------------------
# script interface
if __name__ == "__main__":
if not sys.argv[1:]:
print("Syntax: python player.py imagefile(s)")
sys.exit(1)
filename = sys.argv[1]
root = tkinter.Tk()
root.title(filename)
if len(sys.argv) > 2:
# list of images
print("loading...")
im = []
for filename in sys.argv[1:]:
im.append(Image.open(filename))
else:
# sequence
im = Image.open(filename)
UI(root, im).pack()
root.mainloop()
<|fim▁end|> | def __init__(self, master, im):
if isinstance(im, list):
# list of images
self.im = im[1:]
im = self.im[0]
else:
# sequence
self.im = im
if im.mode == "1":
self.image = ImageTk.BitmapImage(im, foreground="white")
else:
self.image = ImageTk.PhotoImage(im)
tkinter.Label.__init__(self, master, image=self.image, bg="black", bd=0)
self.update()
duration = im.info.get("duration", 100)
self.after(duration, self.next)
def next(self):
if isinstance(self.im, list):
try:
im = self.im[0]
del self.im[0]
self.image.paste(im)
except IndexError:
return # end of list
else:
try:
im = self.im
im.seek(im.tell() + 1)
self.image.paste(im)
except EOFError:
return # end of file
duration = im.info.get("duration", 100)
self.after(duration, self.next)
self.update_idletasks() |
<|file_name|>player.py<|end_file_name|><|fim▁begin|>#!/Users/wuga/Documents/website/wuga/env/bin/python2.7
#
# The Python Imaging Library
# $Id$
#
from __future__ import print_function
import sys
if sys.version_info[0] > 2:
import tkinter
else:
import Tkinter as tkinter
from PIL import Image, ImageTk
# --------------------------------------------------------------------
# an image animation player
class UI(tkinter.Label):
def __init__(self, master, im):
<|fim_middle|>
def next(self):
if isinstance(self.im, list):
try:
im = self.im[0]
del self.im[0]
self.image.paste(im)
except IndexError:
return # end of list
else:
try:
im = self.im
im.seek(im.tell() + 1)
self.image.paste(im)
except EOFError:
return # end of file
duration = im.info.get("duration", 100)
self.after(duration, self.next)
self.update_idletasks()
# --------------------------------------------------------------------
# script interface
if __name__ == "__main__":
if not sys.argv[1:]:
print("Syntax: python player.py imagefile(s)")
sys.exit(1)
filename = sys.argv[1]
root = tkinter.Tk()
root.title(filename)
if len(sys.argv) > 2:
# list of images
print("loading...")
im = []
for filename in sys.argv[1:]:
im.append(Image.open(filename))
else:
# sequence
im = Image.open(filename)
UI(root, im).pack()
root.mainloop()
<|fim▁end|> | if isinstance(im, list):
# list of images
self.im = im[1:]
im = self.im[0]
else:
# sequence
self.im = im
if im.mode == "1":
self.image = ImageTk.BitmapImage(im, foreground="white")
else:
self.image = ImageTk.PhotoImage(im)
tkinter.Label.__init__(self, master, image=self.image, bg="black", bd=0)
self.update()
duration = im.info.get("duration", 100)
self.after(duration, self.next) |
<|file_name|>player.py<|end_file_name|><|fim▁begin|>#!/Users/wuga/Documents/website/wuga/env/bin/python2.7
#
# The Python Imaging Library
# $Id$
#
from __future__ import print_function
import sys
if sys.version_info[0] > 2:
import tkinter
else:
import Tkinter as tkinter
from PIL import Image, ImageTk
# --------------------------------------------------------------------
# an image animation player
class UI(tkinter.Label):
def __init__(self, master, im):
if isinstance(im, list):
# list of images
self.im = im[1:]
im = self.im[0]
else:
# sequence
self.im = im
if im.mode == "1":
self.image = ImageTk.BitmapImage(im, foreground="white")
else:
self.image = ImageTk.PhotoImage(im)
tkinter.Label.__init__(self, master, image=self.image, bg="black", bd=0)
self.update()
duration = im.info.get("duration", 100)
self.after(duration, self.next)
def next(self):
<|fim_middle|>
# --------------------------------------------------------------------
# script interface
if __name__ == "__main__":
if not sys.argv[1:]:
print("Syntax: python player.py imagefile(s)")
sys.exit(1)
filename = sys.argv[1]
root = tkinter.Tk()
root.title(filename)
if len(sys.argv) > 2:
# list of images
print("loading...")
im = []
for filename in sys.argv[1:]:
im.append(Image.open(filename))
else:
# sequence
im = Image.open(filename)
UI(root, im).pack()
root.mainloop()
<|fim▁end|> | if isinstance(self.im, list):
try:
im = self.im[0]
del self.im[0]
self.image.paste(im)
except IndexError:
return # end of list
else:
try:
im = self.im
im.seek(im.tell() + 1)
self.image.paste(im)
except EOFError:
return # end of file
duration = im.info.get("duration", 100)
self.after(duration, self.next)
self.update_idletasks() |
<|file_name|>player.py<|end_file_name|><|fim▁begin|>#!/Users/wuga/Documents/website/wuga/env/bin/python2.7
#
# The Python Imaging Library
# $Id$
#
from __future__ import print_function
import sys
if sys.version_info[0] > 2:
<|fim_middle|>
else:
import Tkinter as tkinter
from PIL import Image, ImageTk
# --------------------------------------------------------------------
# an image animation player
class UI(tkinter.Label):
def __init__(self, master, im):
if isinstance(im, list):
# list of images
self.im = im[1:]
im = self.im[0]
else:
# sequence
self.im = im
if im.mode == "1":
self.image = ImageTk.BitmapImage(im, foreground="white")
else:
self.image = ImageTk.PhotoImage(im)
tkinter.Label.__init__(self, master, image=self.image, bg="black", bd=0)
self.update()
duration = im.info.get("duration", 100)
self.after(duration, self.next)
def next(self):
if isinstance(self.im, list):
try:
im = self.im[0]
del self.im[0]
self.image.paste(im)
except IndexError:
return # end of list
else:
try:
im = self.im
im.seek(im.tell() + 1)
self.image.paste(im)
except EOFError:
return # end of file
duration = im.info.get("duration", 100)
self.after(duration, self.next)
self.update_idletasks()
# --------------------------------------------------------------------
# script interface
if __name__ == "__main__":
if not sys.argv[1:]:
print("Syntax: python player.py imagefile(s)")
sys.exit(1)
filename = sys.argv[1]
root = tkinter.Tk()
root.title(filename)
if len(sys.argv) > 2:
# list of images
print("loading...")
im = []
for filename in sys.argv[1:]:
im.append(Image.open(filename))
else:
# sequence
im = Image.open(filename)
UI(root, im).pack()
root.mainloop()
<|fim▁end|> | import tkinter |
<|file_name|>player.py<|end_file_name|><|fim▁begin|>#!/Users/wuga/Documents/website/wuga/env/bin/python2.7
#
# The Python Imaging Library
# $Id$
#
from __future__ import print_function
import sys
if sys.version_info[0] > 2:
import tkinter
else:
<|fim_middle|>
from PIL import Image, ImageTk
# --------------------------------------------------------------------
# an image animation player
class UI(tkinter.Label):
def __init__(self, master, im):
if isinstance(im, list):
# list of images
self.im = im[1:]
im = self.im[0]
else:
# sequence
self.im = im
if im.mode == "1":
self.image = ImageTk.BitmapImage(im, foreground="white")
else:
self.image = ImageTk.PhotoImage(im)
tkinter.Label.__init__(self, master, image=self.image, bg="black", bd=0)
self.update()
duration = im.info.get("duration", 100)
self.after(duration, self.next)
def next(self):
if isinstance(self.im, list):
try:
im = self.im[0]
del self.im[0]
self.image.paste(im)
except IndexError:
return # end of list
else:
try:
im = self.im
im.seek(im.tell() + 1)
self.image.paste(im)
except EOFError:
return # end of file
duration = im.info.get("duration", 100)
self.after(duration, self.next)
self.update_idletasks()
# --------------------------------------------------------------------
# script interface
if __name__ == "__main__":
if not sys.argv[1:]:
print("Syntax: python player.py imagefile(s)")
sys.exit(1)
filename = sys.argv[1]
root = tkinter.Tk()
root.title(filename)
if len(sys.argv) > 2:
# list of images
print("loading...")
im = []
for filename in sys.argv[1:]:
im.append(Image.open(filename))
else:
# sequence
im = Image.open(filename)
UI(root, im).pack()
root.mainloop()
<|fim▁end|> | import Tkinter as tkinter |
<|file_name|>player.py<|end_file_name|><|fim▁begin|>#!/Users/wuga/Documents/website/wuga/env/bin/python2.7
#
# The Python Imaging Library
# $Id$
#
from __future__ import print_function
import sys
if sys.version_info[0] > 2:
import tkinter
else:
import Tkinter as tkinter
from PIL import Image, ImageTk
# --------------------------------------------------------------------
# an image animation player
class UI(tkinter.Label):
def __init__(self, master, im):
if isinstance(im, list):
# list of images
<|fim_middle|>
else:
# sequence
self.im = im
if im.mode == "1":
self.image = ImageTk.BitmapImage(im, foreground="white")
else:
self.image = ImageTk.PhotoImage(im)
tkinter.Label.__init__(self, master, image=self.image, bg="black", bd=0)
self.update()
duration = im.info.get("duration", 100)
self.after(duration, self.next)
def next(self):
if isinstance(self.im, list):
try:
im = self.im[0]
del self.im[0]
self.image.paste(im)
except IndexError:
return # end of list
else:
try:
im = self.im
im.seek(im.tell() + 1)
self.image.paste(im)
except EOFError:
return # end of file
duration = im.info.get("duration", 100)
self.after(duration, self.next)
self.update_idletasks()
# --------------------------------------------------------------------
# script interface
if __name__ == "__main__":
if not sys.argv[1:]:
print("Syntax: python player.py imagefile(s)")
sys.exit(1)
filename = sys.argv[1]
root = tkinter.Tk()
root.title(filename)
if len(sys.argv) > 2:
# list of images
print("loading...")
im = []
for filename in sys.argv[1:]:
im.append(Image.open(filename))
else:
# sequence
im = Image.open(filename)
UI(root, im).pack()
root.mainloop()
<|fim▁end|> | self.im = im[1:]
im = self.im[0] |
<|file_name|>player.py<|end_file_name|><|fim▁begin|>#!/Users/wuga/Documents/website/wuga/env/bin/python2.7
#
# The Python Imaging Library
# $Id$
#
from __future__ import print_function
import sys
if sys.version_info[0] > 2:
import tkinter
else:
import Tkinter as tkinter
from PIL import Image, ImageTk
# --------------------------------------------------------------------
# an image animation player
class UI(tkinter.Label):
def __init__(self, master, im):
if isinstance(im, list):
# list of images
self.im = im[1:]
im = self.im[0]
else:
# sequence
<|fim_middle|>
if im.mode == "1":
self.image = ImageTk.BitmapImage(im, foreground="white")
else:
self.image = ImageTk.PhotoImage(im)
tkinter.Label.__init__(self, master, image=self.image, bg="black", bd=0)
self.update()
duration = im.info.get("duration", 100)
self.after(duration, self.next)
def next(self):
if isinstance(self.im, list):
try:
im = self.im[0]
del self.im[0]
self.image.paste(im)
except IndexError:
return # end of list
else:
try:
im = self.im
im.seek(im.tell() + 1)
self.image.paste(im)
except EOFError:
return # end of file
duration = im.info.get("duration", 100)
self.after(duration, self.next)
self.update_idletasks()
# --------------------------------------------------------------------
# script interface
if __name__ == "__main__":
if not sys.argv[1:]:
print("Syntax: python player.py imagefile(s)")
sys.exit(1)
filename = sys.argv[1]
root = tkinter.Tk()
root.title(filename)
if len(sys.argv) > 2:
# list of images
print("loading...")
im = []
for filename in sys.argv[1:]:
im.append(Image.open(filename))
else:
# sequence
im = Image.open(filename)
UI(root, im).pack()
root.mainloop()
<|fim▁end|> | self.im = im |
<|file_name|>player.py<|end_file_name|><|fim▁begin|>#!/Users/wuga/Documents/website/wuga/env/bin/python2.7
#
# The Python Imaging Library
# $Id$
#
from __future__ import print_function
import sys
if sys.version_info[0] > 2:
import tkinter
else:
import Tkinter as tkinter
from PIL import Image, ImageTk
# --------------------------------------------------------------------
# an image animation player
class UI(tkinter.Label):
def __init__(self, master, im):
if isinstance(im, list):
# list of images
self.im = im[1:]
im = self.im[0]
else:
# sequence
self.im = im
if im.mode == "1":
<|fim_middle|>
else:
self.image = ImageTk.PhotoImage(im)
tkinter.Label.__init__(self, master, image=self.image, bg="black", bd=0)
self.update()
duration = im.info.get("duration", 100)
self.after(duration, self.next)
def next(self):
if isinstance(self.im, list):
try:
im = self.im[0]
del self.im[0]
self.image.paste(im)
except IndexError:
return # end of list
else:
try:
im = self.im
im.seek(im.tell() + 1)
self.image.paste(im)
except EOFError:
return # end of file
duration = im.info.get("duration", 100)
self.after(duration, self.next)
self.update_idletasks()
# --------------------------------------------------------------------
# script interface
if __name__ == "__main__":
if not sys.argv[1:]:
print("Syntax: python player.py imagefile(s)")
sys.exit(1)
filename = sys.argv[1]
root = tkinter.Tk()
root.title(filename)
if len(sys.argv) > 2:
# list of images
print("loading...")
im = []
for filename in sys.argv[1:]:
im.append(Image.open(filename))
else:
# sequence
im = Image.open(filename)
UI(root, im).pack()
root.mainloop()
<|fim▁end|> | self.image = ImageTk.BitmapImage(im, foreground="white") |
<|file_name|>player.py<|end_file_name|><|fim▁begin|>#!/Users/wuga/Documents/website/wuga/env/bin/python2.7
#
# The Python Imaging Library
# $Id$
#
from __future__ import print_function
import sys
if sys.version_info[0] > 2:
import tkinter
else:
import Tkinter as tkinter
from PIL import Image, ImageTk
# --------------------------------------------------------------------
# an image animation player
class UI(tkinter.Label):
def __init__(self, master, im):
if isinstance(im, list):
# list of images
self.im = im[1:]
im = self.im[0]
else:
# sequence
self.im = im
if im.mode == "1":
self.image = ImageTk.BitmapImage(im, foreground="white")
else:
<|fim_middle|>
tkinter.Label.__init__(self, master, image=self.image, bg="black", bd=0)
self.update()
duration = im.info.get("duration", 100)
self.after(duration, self.next)
def next(self):
if isinstance(self.im, list):
try:
im = self.im[0]
del self.im[0]
self.image.paste(im)
except IndexError:
return # end of list
else:
try:
im = self.im
im.seek(im.tell() + 1)
self.image.paste(im)
except EOFError:
return # end of file
duration = im.info.get("duration", 100)
self.after(duration, self.next)
self.update_idletasks()
# --------------------------------------------------------------------
# script interface
if __name__ == "__main__":
if not sys.argv[1:]:
print("Syntax: python player.py imagefile(s)")
sys.exit(1)
filename = sys.argv[1]
root = tkinter.Tk()
root.title(filename)
if len(sys.argv) > 2:
# list of images
print("loading...")
im = []
for filename in sys.argv[1:]:
im.append(Image.open(filename))
else:
# sequence
im = Image.open(filename)
UI(root, im).pack()
root.mainloop()
<|fim▁end|> | self.image = ImageTk.PhotoImage(im) |
<|file_name|>player.py<|end_file_name|><|fim▁begin|>#!/Users/wuga/Documents/website/wuga/env/bin/python2.7
#
# The Python Imaging Library
# $Id$
#
from __future__ import print_function
import sys
if sys.version_info[0] > 2:
import tkinter
else:
import Tkinter as tkinter
from PIL import Image, ImageTk
# --------------------------------------------------------------------
# an image animation player
class UI(tkinter.Label):
def __init__(self, master, im):
if isinstance(im, list):
# list of images
self.im = im[1:]
im = self.im[0]
else:
# sequence
self.im = im
if im.mode == "1":
self.image = ImageTk.BitmapImage(im, foreground="white")
else:
self.image = ImageTk.PhotoImage(im)
tkinter.Label.__init__(self, master, image=self.image, bg="black", bd=0)
self.update()
duration = im.info.get("duration", 100)
self.after(duration, self.next)
def next(self):
if isinstance(self.im, list):
<|fim_middle|>
else:
try:
im = self.im
im.seek(im.tell() + 1)
self.image.paste(im)
except EOFError:
return # end of file
duration = im.info.get("duration", 100)
self.after(duration, self.next)
self.update_idletasks()
# --------------------------------------------------------------------
# script interface
if __name__ == "__main__":
if not sys.argv[1:]:
print("Syntax: python player.py imagefile(s)")
sys.exit(1)
filename = sys.argv[1]
root = tkinter.Tk()
root.title(filename)
if len(sys.argv) > 2:
# list of images
print("loading...")
im = []
for filename in sys.argv[1:]:
im.append(Image.open(filename))
else:
# sequence
im = Image.open(filename)
UI(root, im).pack()
root.mainloop()
<|fim▁end|> | try:
im = self.im[0]
del self.im[0]
self.image.paste(im)
except IndexError:
return # end of list |
<|file_name|>player.py<|end_file_name|><|fim▁begin|>#!/Users/wuga/Documents/website/wuga/env/bin/python2.7
#
# The Python Imaging Library
# $Id$
#
from __future__ import print_function
import sys
if sys.version_info[0] > 2:
import tkinter
else:
import Tkinter as tkinter
from PIL import Image, ImageTk
# --------------------------------------------------------------------
# an image animation player
class UI(tkinter.Label):
def __init__(self, master, im):
if isinstance(im, list):
# list of images
self.im = im[1:]
im = self.im[0]
else:
# sequence
self.im = im
if im.mode == "1":
self.image = ImageTk.BitmapImage(im, foreground="white")
else:
self.image = ImageTk.PhotoImage(im)
tkinter.Label.__init__(self, master, image=self.image, bg="black", bd=0)
self.update()
duration = im.info.get("duration", 100)
self.after(duration, self.next)
def next(self):
if isinstance(self.im, list):
try:
im = self.im[0]
del self.im[0]
self.image.paste(im)
except IndexError:
return # end of list
else:
<|fim_middle|>
duration = im.info.get("duration", 100)
self.after(duration, self.next)
self.update_idletasks()
# --------------------------------------------------------------------
# script interface
if __name__ == "__main__":
if not sys.argv[1:]:
print("Syntax: python player.py imagefile(s)")
sys.exit(1)
filename = sys.argv[1]
root = tkinter.Tk()
root.title(filename)
if len(sys.argv) > 2:
# list of images
print("loading...")
im = []
for filename in sys.argv[1:]:
im.append(Image.open(filename))
else:
# sequence
im = Image.open(filename)
UI(root, im).pack()
root.mainloop()
<|fim▁end|> | try:
im = self.im
im.seek(im.tell() + 1)
self.image.paste(im)
except EOFError:
return # end of file |
<|file_name|>player.py<|end_file_name|><|fim▁begin|>#!/Users/wuga/Documents/website/wuga/env/bin/python2.7
#
# The Python Imaging Library
# $Id$
#
from __future__ import print_function
import sys
if sys.version_info[0] > 2:
import tkinter
else:
import Tkinter as tkinter
from PIL import Image, ImageTk
# --------------------------------------------------------------------
# an image animation player
class UI(tkinter.Label):
def __init__(self, master, im):
if isinstance(im, list):
# list of images
self.im = im[1:]
im = self.im[0]
else:
# sequence
self.im = im
if im.mode == "1":
self.image = ImageTk.BitmapImage(im, foreground="white")
else:
self.image = ImageTk.PhotoImage(im)
tkinter.Label.__init__(self, master, image=self.image, bg="black", bd=0)
self.update()
duration = im.info.get("duration", 100)
self.after(duration, self.next)
def next(self):
if isinstance(self.im, list):
try:
im = self.im[0]
del self.im[0]
self.image.paste(im)
except IndexError:
return # end of list
else:
try:
im = self.im
im.seek(im.tell() + 1)
self.image.paste(im)
except EOFError:
return # end of file
duration = im.info.get("duration", 100)
self.after(duration, self.next)
self.update_idletasks()
# --------------------------------------------------------------------
# script interface
if __name__ == "__main__":
<|fim_middle|>
<|fim▁end|> | if not sys.argv[1:]:
print("Syntax: python player.py imagefile(s)")
sys.exit(1)
filename = sys.argv[1]
root = tkinter.Tk()
root.title(filename)
if len(sys.argv) > 2:
# list of images
print("loading...")
im = []
for filename in sys.argv[1:]:
im.append(Image.open(filename))
else:
# sequence
im = Image.open(filename)
UI(root, im).pack()
root.mainloop() |
<|file_name|>player.py<|end_file_name|><|fim▁begin|>#!/Users/wuga/Documents/website/wuga/env/bin/python2.7
#
# The Python Imaging Library
# $Id$
#
from __future__ import print_function
import sys
if sys.version_info[0] > 2:
import tkinter
else:
import Tkinter as tkinter
from PIL import Image, ImageTk
# --------------------------------------------------------------------
# an image animation player
class UI(tkinter.Label):
def __init__(self, master, im):
if isinstance(im, list):
# list of images
self.im = im[1:]
im = self.im[0]
else:
# sequence
self.im = im
if im.mode == "1":
self.image = ImageTk.BitmapImage(im, foreground="white")
else:
self.image = ImageTk.PhotoImage(im)
tkinter.Label.__init__(self, master, image=self.image, bg="black", bd=0)
self.update()
duration = im.info.get("duration", 100)
self.after(duration, self.next)
def next(self):
if isinstance(self.im, list):
try:
im = self.im[0]
del self.im[0]
self.image.paste(im)
except IndexError:
return # end of list
else:
try:
im = self.im
im.seek(im.tell() + 1)
self.image.paste(im)
except EOFError:
return # end of file
duration = im.info.get("duration", 100)
self.after(duration, self.next)
self.update_idletasks()
# --------------------------------------------------------------------
# script interface
if __name__ == "__main__":
if not sys.argv[1:]:
<|fim_middle|>
filename = sys.argv[1]
root = tkinter.Tk()
root.title(filename)
if len(sys.argv) > 2:
# list of images
print("loading...")
im = []
for filename in sys.argv[1:]:
im.append(Image.open(filename))
else:
# sequence
im = Image.open(filename)
UI(root, im).pack()
root.mainloop()
<|fim▁end|> | print("Syntax: python player.py imagefile(s)")
sys.exit(1) |
<|file_name|>player.py<|end_file_name|><|fim▁begin|>#!/Users/wuga/Documents/website/wuga/env/bin/python2.7
#
# The Python Imaging Library
# $Id$
#
from __future__ import print_function
import sys
if sys.version_info[0] > 2:
import tkinter
else:
import Tkinter as tkinter
from PIL import Image, ImageTk
# --------------------------------------------------------------------
# an image animation player
class UI(tkinter.Label):
def __init__(self, master, im):
if isinstance(im, list):
# list of images
self.im = im[1:]
im = self.im[0]
else:
# sequence
self.im = im
if im.mode == "1":
self.image = ImageTk.BitmapImage(im, foreground="white")
else:
self.image = ImageTk.PhotoImage(im)
tkinter.Label.__init__(self, master, image=self.image, bg="black", bd=0)
self.update()
duration = im.info.get("duration", 100)
self.after(duration, self.next)
def next(self):
if isinstance(self.im, list):
try:
im = self.im[0]
del self.im[0]
self.image.paste(im)
except IndexError:
return # end of list
else:
try:
im = self.im
im.seek(im.tell() + 1)
self.image.paste(im)
except EOFError:
return # end of file
duration = im.info.get("duration", 100)
self.after(duration, self.next)
self.update_idletasks()
# --------------------------------------------------------------------
# script interface
if __name__ == "__main__":
if not sys.argv[1:]:
print("Syntax: python player.py imagefile(s)")
sys.exit(1)
filename = sys.argv[1]
root = tkinter.Tk()
root.title(filename)
if len(sys.argv) > 2:
# list of images
<|fim_middle|>
else:
# sequence
im = Image.open(filename)
UI(root, im).pack()
root.mainloop()
<|fim▁end|> | print("loading...")
im = []
for filename in sys.argv[1:]:
im.append(Image.open(filename)) |
<|file_name|>player.py<|end_file_name|><|fim▁begin|>#!/Users/wuga/Documents/website/wuga/env/bin/python2.7
#
# The Python Imaging Library
# $Id$
#
from __future__ import print_function
import sys
if sys.version_info[0] > 2:
import tkinter
else:
import Tkinter as tkinter
from PIL import Image, ImageTk
# --------------------------------------------------------------------
# an image animation player
class UI(tkinter.Label):
def __init__(self, master, im):
if isinstance(im, list):
# list of images
self.im = im[1:]
im = self.im[0]
else:
# sequence
self.im = im
if im.mode == "1":
self.image = ImageTk.BitmapImage(im, foreground="white")
else:
self.image = ImageTk.PhotoImage(im)
tkinter.Label.__init__(self, master, image=self.image, bg="black", bd=0)
self.update()
duration = im.info.get("duration", 100)
self.after(duration, self.next)
def next(self):
if isinstance(self.im, list):
try:
im = self.im[0]
del self.im[0]
self.image.paste(im)
except IndexError:
return # end of list
else:
try:
im = self.im
im.seek(im.tell() + 1)
self.image.paste(im)
except EOFError:
return # end of file
duration = im.info.get("duration", 100)
self.after(duration, self.next)
self.update_idletasks()
# --------------------------------------------------------------------
# script interface
if __name__ == "__main__":
if not sys.argv[1:]:
print("Syntax: python player.py imagefile(s)")
sys.exit(1)
filename = sys.argv[1]
root = tkinter.Tk()
root.title(filename)
if len(sys.argv) > 2:
# list of images
print("loading...")
im = []
for filename in sys.argv[1:]:
im.append(Image.open(filename))
else:
# sequence
<|fim_middle|>
UI(root, im).pack()
root.mainloop()
<|fim▁end|> | im = Image.open(filename) |
<|file_name|>player.py<|end_file_name|><|fim▁begin|>#!/Users/wuga/Documents/website/wuga/env/bin/python2.7
#
# The Python Imaging Library
# $Id$
#
from __future__ import print_function
import sys
if sys.version_info[0] > 2:
import tkinter
else:
import Tkinter as tkinter
from PIL import Image, ImageTk
# --------------------------------------------------------------------
# an image animation player
class UI(tkinter.Label):
def <|fim_middle|>(self, master, im):
if isinstance(im, list):
# list of images
self.im = im[1:]
im = self.im[0]
else:
# sequence
self.im = im
if im.mode == "1":
self.image = ImageTk.BitmapImage(im, foreground="white")
else:
self.image = ImageTk.PhotoImage(im)
tkinter.Label.__init__(self, master, image=self.image, bg="black", bd=0)
self.update()
duration = im.info.get("duration", 100)
self.after(duration, self.next)
def next(self):
if isinstance(self.im, list):
try:
im = self.im[0]
del self.im[0]
self.image.paste(im)
except IndexError:
return # end of list
else:
try:
im = self.im
im.seek(im.tell() + 1)
self.image.paste(im)
except EOFError:
return # end of file
duration = im.info.get("duration", 100)
self.after(duration, self.next)
self.update_idletasks()
# --------------------------------------------------------------------
# script interface
if __name__ == "__main__":
if not sys.argv[1:]:
print("Syntax: python player.py imagefile(s)")
sys.exit(1)
filename = sys.argv[1]
root = tkinter.Tk()
root.title(filename)
if len(sys.argv) > 2:
# list of images
print("loading...")
im = []
for filename in sys.argv[1:]:
im.append(Image.open(filename))
else:
# sequence
im = Image.open(filename)
UI(root, im).pack()
root.mainloop()
<|fim▁end|> | __init__ |
<|file_name|>player.py<|end_file_name|><|fim▁begin|>#!/Users/wuga/Documents/website/wuga/env/bin/python2.7
#
# The Python Imaging Library
# $Id$
#
from __future__ import print_function
import sys
if sys.version_info[0] > 2:
import tkinter
else:
import Tkinter as tkinter
from PIL import Image, ImageTk
# --------------------------------------------------------------------
# an image animation player
class UI(tkinter.Label):
def __init__(self, master, im):
if isinstance(im, list):
# list of images
self.im = im[1:]
im = self.im[0]
else:
# sequence
self.im = im
if im.mode == "1":
self.image = ImageTk.BitmapImage(im, foreground="white")
else:
self.image = ImageTk.PhotoImage(im)
tkinter.Label.__init__(self, master, image=self.image, bg="black", bd=0)
self.update()
duration = im.info.get("duration", 100)
self.after(duration, self.next)
def <|fim_middle|>(self):
if isinstance(self.im, list):
try:
im = self.im[0]
del self.im[0]
self.image.paste(im)
except IndexError:
return # end of list
else:
try:
im = self.im
im.seek(im.tell() + 1)
self.image.paste(im)
except EOFError:
return # end of file
duration = im.info.get("duration", 100)
self.after(duration, self.next)
self.update_idletasks()
# --------------------------------------------------------------------
# script interface
if __name__ == "__main__":
if not sys.argv[1:]:
print("Syntax: python player.py imagefile(s)")
sys.exit(1)
filename = sys.argv[1]
root = tkinter.Tk()
root.title(filename)
if len(sys.argv) > 2:
# list of images
print("loading...")
im = []
for filename in sys.argv[1:]:
im.append(Image.open(filename))
else:
# sequence
im = Image.open(filename)
UI(root, im).pack()
root.mainloop()
<|fim▁end|> | next |
<|file_name|>test_tir_transform_simplify.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
import tvm
from tvm import te
def test_stmt_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
with ib.for_range(0, n, name="i") as i:
with ib.if_scope(i < 12):
A[i] = C[i]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body, tvm.tir.Store)
def test_thread_extent_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(ty, "thread_extent", 1)
with ib.if_scope(tx + ty < 12):
A[tx] = C[tx + ty]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body<|fim▁hole|> ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", 32)
ib.scope_attr(ty, "thread_extent", 32)
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
A[tx] = C[tx * 32 + ty]
body = ib.get()
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body, tvm.tir.IfThenElse)
assert not isinstance(body.body.body.then_case, tvm.tir.IfThenElse)
def test_basic_likely_elimination():
n = te.size_var("n")
X = te.placeholder(shape=(n,), name="x")
W = te.placeholder(shape=(n + 1,), dtype="int32", name="w")
def f(i):
start = W[i]
extent = W[i + 1] - W[i]
rv = te.reduce_axis((0, extent))
return te.sum(X[rv + start], axis=rv)
Y = te.compute(X.shape, f, name="y")
s = te.create_schedule([Y.op])
stmt = tvm.lower(s, [X, W, Y], simple_mode=True)
assert "if" not in str(stmt)
def test_complex_likely_elimination():
def cumsum(X):
"""
Y[i] = sum(X[:i])
"""
(m,) = X.shape
s_state = te.placeholder((m + 1,), dtype="int32", name="state")
s_init = te.compute((1,), lambda _: tvm.tir.const(0, "int32"))
s_update = te.compute((m + 1,), lambda l: s_state[l - 1] + X[l - 1])
return tvm.te.scan(s_init, s_update, s_state, inputs=[X], name="cumsum")
def sparse_lengths_sum(data, indices, lengths):
oshape = list(data.shape)
oshape[0] = lengths.shape[0]
length_offsets = cumsum(lengths)
def sls(n, d):
gg = te.reduce_axis((0, lengths[n]))
indices_idx = length_offsets[n] + gg
data_idx = indices[indices_idx]
data_val = data[data_idx, d]
return te.sum(data_val, axis=gg)
return te.compute(oshape, sls)
m, n, d, i, l = (
te.size_var("m"),
te.size_var("n"),
te.size_var("d"),
te.size_var("i"),
te.size_var("l"),
)
data_ph = te.placeholder((m, d * 32), name="data")
indices_ph = te.placeholder((i,), name="indices", dtype="int32")
lengths_ph = te.placeholder((n,), name="lengths", dtype="int32")
Y = sparse_lengths_sum(data_ph, indices_ph, lengths_ph)
s = te.create_schedule([Y.op])
(n, d) = s[Y].op.axis
(do, di) = s[Y].split(d, factor=32)
(gg,) = s[Y].op.reduce_axis
s[Y].reorder(n, do, gg, di)
s[Y].vectorize(di)
stmt = tvm.lower(s, [data_ph, indices_ph, lengths_ph, Y], simple_mode=True)
assert "if" not in str(stmt)
if __name__ == "__main__":
test_stmt_simplify()
test_thread_extent_simplify()
test_if_likely()
test_basic_likely_elimination()
test_complex_likely_elimination()<|fim▁end|> | assert isinstance(body.body.body.body, tvm.tir.Store)
def test_if_likely(): |
<|file_name|>test_tir_transform_simplify.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
import tvm
from tvm import te
def test_stmt_simplify():
<|fim_middle|>
def test_thread_extent_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(ty, "thread_extent", 1)
with ib.if_scope(tx + ty < 12):
A[tx] = C[tx + ty]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body.body, tvm.tir.Store)
def test_if_likely():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", 32)
ib.scope_attr(ty, "thread_extent", 32)
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
A[tx] = C[tx * 32 + ty]
body = ib.get()
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body, tvm.tir.IfThenElse)
assert not isinstance(body.body.body.then_case, tvm.tir.IfThenElse)
def test_basic_likely_elimination():
n = te.size_var("n")
X = te.placeholder(shape=(n,), name="x")
W = te.placeholder(shape=(n + 1,), dtype="int32", name="w")
def f(i):
start = W[i]
extent = W[i + 1] - W[i]
rv = te.reduce_axis((0, extent))
return te.sum(X[rv + start], axis=rv)
Y = te.compute(X.shape, f, name="y")
s = te.create_schedule([Y.op])
stmt = tvm.lower(s, [X, W, Y], simple_mode=True)
assert "if" not in str(stmt)
def test_complex_likely_elimination():
def cumsum(X):
"""
Y[i] = sum(X[:i])
"""
(m,) = X.shape
s_state = te.placeholder((m + 1,), dtype="int32", name="state")
s_init = te.compute((1,), lambda _: tvm.tir.const(0, "int32"))
s_update = te.compute((m + 1,), lambda l: s_state[l - 1] + X[l - 1])
return tvm.te.scan(s_init, s_update, s_state, inputs=[X], name="cumsum")
def sparse_lengths_sum(data, indices, lengths):
oshape = list(data.shape)
oshape[0] = lengths.shape[0]
length_offsets = cumsum(lengths)
def sls(n, d):
gg = te.reduce_axis((0, lengths[n]))
indices_idx = length_offsets[n] + gg
data_idx = indices[indices_idx]
data_val = data[data_idx, d]
return te.sum(data_val, axis=gg)
return te.compute(oshape, sls)
m, n, d, i, l = (
te.size_var("m"),
te.size_var("n"),
te.size_var("d"),
te.size_var("i"),
te.size_var("l"),
)
data_ph = te.placeholder((m, d * 32), name="data")
indices_ph = te.placeholder((i,), name="indices", dtype="int32")
lengths_ph = te.placeholder((n,), name="lengths", dtype="int32")
Y = sparse_lengths_sum(data_ph, indices_ph, lengths_ph)
s = te.create_schedule([Y.op])
(n, d) = s[Y].op.axis
(do, di) = s[Y].split(d, factor=32)
(gg,) = s[Y].op.reduce_axis
s[Y].reorder(n, do, gg, di)
s[Y].vectorize(di)
stmt = tvm.lower(s, [data_ph, indices_ph, lengths_ph, Y], simple_mode=True)
assert "if" not in str(stmt)
if __name__ == "__main__":
test_stmt_simplify()
test_thread_extent_simplify()
test_if_likely()
test_basic_likely_elimination()
test_complex_likely_elimination()
<|fim▁end|> | ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
with ib.for_range(0, n, name="i") as i:
with ib.if_scope(i < 12):
A[i] = C[i]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body, tvm.tir.Store) |
<|file_name|>test_tir_transform_simplify.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
import tvm
from tvm import te
def test_stmt_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
with ib.for_range(0, n, name="i") as i:
with ib.if_scope(i < 12):
A[i] = C[i]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body, tvm.tir.Store)
def test_thread_extent_simplify():
<|fim_middle|>
def test_if_likely():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", 32)
ib.scope_attr(ty, "thread_extent", 32)
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
A[tx] = C[tx * 32 + ty]
body = ib.get()
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body, tvm.tir.IfThenElse)
assert not isinstance(body.body.body.then_case, tvm.tir.IfThenElse)
def test_basic_likely_elimination():
n = te.size_var("n")
X = te.placeholder(shape=(n,), name="x")
W = te.placeholder(shape=(n + 1,), dtype="int32", name="w")
def f(i):
start = W[i]
extent = W[i + 1] - W[i]
rv = te.reduce_axis((0, extent))
return te.sum(X[rv + start], axis=rv)
Y = te.compute(X.shape, f, name="y")
s = te.create_schedule([Y.op])
stmt = tvm.lower(s, [X, W, Y], simple_mode=True)
assert "if" not in str(stmt)
def test_complex_likely_elimination():
def cumsum(X):
"""
Y[i] = sum(X[:i])
"""
(m,) = X.shape
s_state = te.placeholder((m + 1,), dtype="int32", name="state")
s_init = te.compute((1,), lambda _: tvm.tir.const(0, "int32"))
s_update = te.compute((m + 1,), lambda l: s_state[l - 1] + X[l - 1])
return tvm.te.scan(s_init, s_update, s_state, inputs=[X], name="cumsum")
def sparse_lengths_sum(data, indices, lengths):
oshape = list(data.shape)
oshape[0] = lengths.shape[0]
length_offsets = cumsum(lengths)
def sls(n, d):
gg = te.reduce_axis((0, lengths[n]))
indices_idx = length_offsets[n] + gg
data_idx = indices[indices_idx]
data_val = data[data_idx, d]
return te.sum(data_val, axis=gg)
return te.compute(oshape, sls)
m, n, d, i, l = (
te.size_var("m"),
te.size_var("n"),
te.size_var("d"),
te.size_var("i"),
te.size_var("l"),
)
data_ph = te.placeholder((m, d * 32), name="data")
indices_ph = te.placeholder((i,), name="indices", dtype="int32")
lengths_ph = te.placeholder((n,), name="lengths", dtype="int32")
Y = sparse_lengths_sum(data_ph, indices_ph, lengths_ph)
s = te.create_schedule([Y.op])
(n, d) = s[Y].op.axis
(do, di) = s[Y].split(d, factor=32)
(gg,) = s[Y].op.reduce_axis
s[Y].reorder(n, do, gg, di)
s[Y].vectorize(di)
stmt = tvm.lower(s, [data_ph, indices_ph, lengths_ph, Y], simple_mode=True)
assert "if" not in str(stmt)
if __name__ == "__main__":
test_stmt_simplify()
test_thread_extent_simplify()
test_if_likely()
test_basic_likely_elimination()
test_complex_likely_elimination()
<|fim▁end|> | ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(ty, "thread_extent", 1)
with ib.if_scope(tx + ty < 12):
A[tx] = C[tx + ty]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body.body, tvm.tir.Store) |
<|file_name|>test_tir_transform_simplify.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
import tvm
from tvm import te
def test_stmt_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
with ib.for_range(0, n, name="i") as i:
with ib.if_scope(i < 12):
A[i] = C[i]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body, tvm.tir.Store)
def test_thread_extent_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(ty, "thread_extent", 1)
with ib.if_scope(tx + ty < 12):
A[tx] = C[tx + ty]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body.body, tvm.tir.Store)
def test_if_likely():
<|fim_middle|>
def test_basic_likely_elimination():
n = te.size_var("n")
X = te.placeholder(shape=(n,), name="x")
W = te.placeholder(shape=(n + 1,), dtype="int32", name="w")
def f(i):
start = W[i]
extent = W[i + 1] - W[i]
rv = te.reduce_axis((0, extent))
return te.sum(X[rv + start], axis=rv)
Y = te.compute(X.shape, f, name="y")
s = te.create_schedule([Y.op])
stmt = tvm.lower(s, [X, W, Y], simple_mode=True)
assert "if" not in str(stmt)
def test_complex_likely_elimination():
def cumsum(X):
"""
Y[i] = sum(X[:i])
"""
(m,) = X.shape
s_state = te.placeholder((m + 1,), dtype="int32", name="state")
s_init = te.compute((1,), lambda _: tvm.tir.const(0, "int32"))
s_update = te.compute((m + 1,), lambda l: s_state[l - 1] + X[l - 1])
return tvm.te.scan(s_init, s_update, s_state, inputs=[X], name="cumsum")
def sparse_lengths_sum(data, indices, lengths):
oshape = list(data.shape)
oshape[0] = lengths.shape[0]
length_offsets = cumsum(lengths)
def sls(n, d):
gg = te.reduce_axis((0, lengths[n]))
indices_idx = length_offsets[n] + gg
data_idx = indices[indices_idx]
data_val = data[data_idx, d]
return te.sum(data_val, axis=gg)
return te.compute(oshape, sls)
m, n, d, i, l = (
te.size_var("m"),
te.size_var("n"),
te.size_var("d"),
te.size_var("i"),
te.size_var("l"),
)
data_ph = te.placeholder((m, d * 32), name="data")
indices_ph = te.placeholder((i,), name="indices", dtype="int32")
lengths_ph = te.placeholder((n,), name="lengths", dtype="int32")
Y = sparse_lengths_sum(data_ph, indices_ph, lengths_ph)
s = te.create_schedule([Y.op])
(n, d) = s[Y].op.axis
(do, di) = s[Y].split(d, factor=32)
(gg,) = s[Y].op.reduce_axis
s[Y].reorder(n, do, gg, di)
s[Y].vectorize(di)
stmt = tvm.lower(s, [data_ph, indices_ph, lengths_ph, Y], simple_mode=True)
assert "if" not in str(stmt)
if __name__ == "__main__":
test_stmt_simplify()
test_thread_extent_simplify()
test_if_likely()
test_basic_likely_elimination()
test_complex_likely_elimination()
<|fim▁end|> | ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", 32)
ib.scope_attr(ty, "thread_extent", 32)
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
A[tx] = C[tx * 32 + ty]
body = ib.get()
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body, tvm.tir.IfThenElse)
assert not isinstance(body.body.body.then_case, tvm.tir.IfThenElse) |
<|file_name|>test_tir_transform_simplify.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
import tvm
from tvm import te
def test_stmt_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
with ib.for_range(0, n, name="i") as i:
with ib.if_scope(i < 12):
A[i] = C[i]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body, tvm.tir.Store)
def test_thread_extent_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(ty, "thread_extent", 1)
with ib.if_scope(tx + ty < 12):
A[tx] = C[tx + ty]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body.body, tvm.tir.Store)
def test_if_likely():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", 32)
ib.scope_attr(ty, "thread_extent", 32)
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
A[tx] = C[tx * 32 + ty]
body = ib.get()
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body, tvm.tir.IfThenElse)
assert not isinstance(body.body.body.then_case, tvm.tir.IfThenElse)
def test_basic_likely_elimination():
<|fim_middle|>
def test_complex_likely_elimination():
def cumsum(X):
"""
Y[i] = sum(X[:i])
"""
(m,) = X.shape
s_state = te.placeholder((m + 1,), dtype="int32", name="state")
s_init = te.compute((1,), lambda _: tvm.tir.const(0, "int32"))
s_update = te.compute((m + 1,), lambda l: s_state[l - 1] + X[l - 1])
return tvm.te.scan(s_init, s_update, s_state, inputs=[X], name="cumsum")
def sparse_lengths_sum(data, indices, lengths):
oshape = list(data.shape)
oshape[0] = lengths.shape[0]
length_offsets = cumsum(lengths)
def sls(n, d):
gg = te.reduce_axis((0, lengths[n]))
indices_idx = length_offsets[n] + gg
data_idx = indices[indices_idx]
data_val = data[data_idx, d]
return te.sum(data_val, axis=gg)
return te.compute(oshape, sls)
m, n, d, i, l = (
te.size_var("m"),
te.size_var("n"),
te.size_var("d"),
te.size_var("i"),
te.size_var("l"),
)
data_ph = te.placeholder((m, d * 32), name="data")
indices_ph = te.placeholder((i,), name="indices", dtype="int32")
lengths_ph = te.placeholder((n,), name="lengths", dtype="int32")
Y = sparse_lengths_sum(data_ph, indices_ph, lengths_ph)
s = te.create_schedule([Y.op])
(n, d) = s[Y].op.axis
(do, di) = s[Y].split(d, factor=32)
(gg,) = s[Y].op.reduce_axis
s[Y].reorder(n, do, gg, di)
s[Y].vectorize(di)
stmt = tvm.lower(s, [data_ph, indices_ph, lengths_ph, Y], simple_mode=True)
assert "if" not in str(stmt)
if __name__ == "__main__":
test_stmt_simplify()
test_thread_extent_simplify()
test_if_likely()
test_basic_likely_elimination()
test_complex_likely_elimination()
<|fim▁end|> | n = te.size_var("n")
X = te.placeholder(shape=(n,), name="x")
W = te.placeholder(shape=(n + 1,), dtype="int32", name="w")
def f(i):
start = W[i]
extent = W[i + 1] - W[i]
rv = te.reduce_axis((0, extent))
return te.sum(X[rv + start], axis=rv)
Y = te.compute(X.shape, f, name="y")
s = te.create_schedule([Y.op])
stmt = tvm.lower(s, [X, W, Y], simple_mode=True)
assert "if" not in str(stmt) |
<|file_name|>test_tir_transform_simplify.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
import tvm
from tvm import te
def test_stmt_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
with ib.for_range(0, n, name="i") as i:
with ib.if_scope(i < 12):
A[i] = C[i]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body, tvm.tir.Store)
def test_thread_extent_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(ty, "thread_extent", 1)
with ib.if_scope(tx + ty < 12):
A[tx] = C[tx + ty]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body.body, tvm.tir.Store)
def test_if_likely():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", 32)
ib.scope_attr(ty, "thread_extent", 32)
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
A[tx] = C[tx * 32 + ty]
body = ib.get()
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body, tvm.tir.IfThenElse)
assert not isinstance(body.body.body.then_case, tvm.tir.IfThenElse)
def test_basic_likely_elimination():
n = te.size_var("n")
X = te.placeholder(shape=(n,), name="x")
W = te.placeholder(shape=(n + 1,), dtype="int32", name="w")
def f(i):
<|fim_middle|>
Y = te.compute(X.shape, f, name="y")
s = te.create_schedule([Y.op])
stmt = tvm.lower(s, [X, W, Y], simple_mode=True)
assert "if" not in str(stmt)
def test_complex_likely_elimination():
def cumsum(X):
"""
Y[i] = sum(X[:i])
"""
(m,) = X.shape
s_state = te.placeholder((m + 1,), dtype="int32", name="state")
s_init = te.compute((1,), lambda _: tvm.tir.const(0, "int32"))
s_update = te.compute((m + 1,), lambda l: s_state[l - 1] + X[l - 1])
return tvm.te.scan(s_init, s_update, s_state, inputs=[X], name="cumsum")
def sparse_lengths_sum(data, indices, lengths):
oshape = list(data.shape)
oshape[0] = lengths.shape[0]
length_offsets = cumsum(lengths)
def sls(n, d):
gg = te.reduce_axis((0, lengths[n]))
indices_idx = length_offsets[n] + gg
data_idx = indices[indices_idx]
data_val = data[data_idx, d]
return te.sum(data_val, axis=gg)
return te.compute(oshape, sls)
m, n, d, i, l = (
te.size_var("m"),
te.size_var("n"),
te.size_var("d"),
te.size_var("i"),
te.size_var("l"),
)
data_ph = te.placeholder((m, d * 32), name="data")
indices_ph = te.placeholder((i,), name="indices", dtype="int32")
lengths_ph = te.placeholder((n,), name="lengths", dtype="int32")
Y = sparse_lengths_sum(data_ph, indices_ph, lengths_ph)
s = te.create_schedule([Y.op])
(n, d) = s[Y].op.axis
(do, di) = s[Y].split(d, factor=32)
(gg,) = s[Y].op.reduce_axis
s[Y].reorder(n, do, gg, di)
s[Y].vectorize(di)
stmt = tvm.lower(s, [data_ph, indices_ph, lengths_ph, Y], simple_mode=True)
assert "if" not in str(stmt)
if __name__ == "__main__":
test_stmt_simplify()
test_thread_extent_simplify()
test_if_likely()
test_basic_likely_elimination()
test_complex_likely_elimination()
<|fim▁end|> | start = W[i]
extent = W[i + 1] - W[i]
rv = te.reduce_axis((0, extent))
return te.sum(X[rv + start], axis=rv) |
<|file_name|>test_tir_transform_simplify.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
import tvm
from tvm import te
def test_stmt_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
with ib.for_range(0, n, name="i") as i:
with ib.if_scope(i < 12):
A[i] = C[i]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body, tvm.tir.Store)
def test_thread_extent_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(ty, "thread_extent", 1)
with ib.if_scope(tx + ty < 12):
A[tx] = C[tx + ty]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body.body, tvm.tir.Store)
def test_if_likely():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", 32)
ib.scope_attr(ty, "thread_extent", 32)
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
A[tx] = C[tx * 32 + ty]
body = ib.get()
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body, tvm.tir.IfThenElse)
assert not isinstance(body.body.body.then_case, tvm.tir.IfThenElse)
def test_basic_likely_elimination():
n = te.size_var("n")
X = te.placeholder(shape=(n,), name="x")
W = te.placeholder(shape=(n + 1,), dtype="int32", name="w")
def f(i):
start = W[i]
extent = W[i + 1] - W[i]
rv = te.reduce_axis((0, extent))
return te.sum(X[rv + start], axis=rv)
Y = te.compute(X.shape, f, name="y")
s = te.create_schedule([Y.op])
stmt = tvm.lower(s, [X, W, Y], simple_mode=True)
assert "if" not in str(stmt)
def test_complex_likely_elimination():
<|fim_middle|>
if __name__ == "__main__":
test_stmt_simplify()
test_thread_extent_simplify()
test_if_likely()
test_basic_likely_elimination()
test_complex_likely_elimination()
<|fim▁end|> | def cumsum(X):
"""
Y[i] = sum(X[:i])
"""
(m,) = X.shape
s_state = te.placeholder((m + 1,), dtype="int32", name="state")
s_init = te.compute((1,), lambda _: tvm.tir.const(0, "int32"))
s_update = te.compute((m + 1,), lambda l: s_state[l - 1] + X[l - 1])
return tvm.te.scan(s_init, s_update, s_state, inputs=[X], name="cumsum")
def sparse_lengths_sum(data, indices, lengths):
oshape = list(data.shape)
oshape[0] = lengths.shape[0]
length_offsets = cumsum(lengths)
def sls(n, d):
gg = te.reduce_axis((0, lengths[n]))
indices_idx = length_offsets[n] + gg
data_idx = indices[indices_idx]
data_val = data[data_idx, d]
return te.sum(data_val, axis=gg)
return te.compute(oshape, sls)
m, n, d, i, l = (
te.size_var("m"),
te.size_var("n"),
te.size_var("d"),
te.size_var("i"),
te.size_var("l"),
)
data_ph = te.placeholder((m, d * 32), name="data")
indices_ph = te.placeholder((i,), name="indices", dtype="int32")
lengths_ph = te.placeholder((n,), name="lengths", dtype="int32")
Y = sparse_lengths_sum(data_ph, indices_ph, lengths_ph)
s = te.create_schedule([Y.op])
(n, d) = s[Y].op.axis
(do, di) = s[Y].split(d, factor=32)
(gg,) = s[Y].op.reduce_axis
s[Y].reorder(n, do, gg, di)
s[Y].vectorize(di)
stmt = tvm.lower(s, [data_ph, indices_ph, lengths_ph, Y], simple_mode=True)
assert "if" not in str(stmt) |
<|file_name|>test_tir_transform_simplify.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
import tvm
from tvm import te
def test_stmt_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
with ib.for_range(0, n, name="i") as i:
with ib.if_scope(i < 12):
A[i] = C[i]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body, tvm.tir.Store)
def test_thread_extent_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(ty, "thread_extent", 1)
with ib.if_scope(tx + ty < 12):
A[tx] = C[tx + ty]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body.body, tvm.tir.Store)
def test_if_likely():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", 32)
ib.scope_attr(ty, "thread_extent", 32)
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
A[tx] = C[tx * 32 + ty]
body = ib.get()
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body, tvm.tir.IfThenElse)
assert not isinstance(body.body.body.then_case, tvm.tir.IfThenElse)
def test_basic_likely_elimination():
n = te.size_var("n")
X = te.placeholder(shape=(n,), name="x")
W = te.placeholder(shape=(n + 1,), dtype="int32", name="w")
def f(i):
start = W[i]
extent = W[i + 1] - W[i]
rv = te.reduce_axis((0, extent))
return te.sum(X[rv + start], axis=rv)
Y = te.compute(X.shape, f, name="y")
s = te.create_schedule([Y.op])
stmt = tvm.lower(s, [X, W, Y], simple_mode=True)
assert "if" not in str(stmt)
def test_complex_likely_elimination():
def cumsum(X):
<|fim_middle|>
def sparse_lengths_sum(data, indices, lengths):
oshape = list(data.shape)
oshape[0] = lengths.shape[0]
length_offsets = cumsum(lengths)
def sls(n, d):
gg = te.reduce_axis((0, lengths[n]))
indices_idx = length_offsets[n] + gg
data_idx = indices[indices_idx]
data_val = data[data_idx, d]
return te.sum(data_val, axis=gg)
return te.compute(oshape, sls)
m, n, d, i, l = (
te.size_var("m"),
te.size_var("n"),
te.size_var("d"),
te.size_var("i"),
te.size_var("l"),
)
data_ph = te.placeholder((m, d * 32), name="data")
indices_ph = te.placeholder((i,), name="indices", dtype="int32")
lengths_ph = te.placeholder((n,), name="lengths", dtype="int32")
Y = sparse_lengths_sum(data_ph, indices_ph, lengths_ph)
s = te.create_schedule([Y.op])
(n, d) = s[Y].op.axis
(do, di) = s[Y].split(d, factor=32)
(gg,) = s[Y].op.reduce_axis
s[Y].reorder(n, do, gg, di)
s[Y].vectorize(di)
stmt = tvm.lower(s, [data_ph, indices_ph, lengths_ph, Y], simple_mode=True)
assert "if" not in str(stmt)
if __name__ == "__main__":
test_stmt_simplify()
test_thread_extent_simplify()
test_if_likely()
test_basic_likely_elimination()
test_complex_likely_elimination()
<|fim▁end|> | """
Y[i] = sum(X[:i])
"""
(m,) = X.shape
s_state = te.placeholder((m + 1,), dtype="int32", name="state")
s_init = te.compute((1,), lambda _: tvm.tir.const(0, "int32"))
s_update = te.compute((m + 1,), lambda l: s_state[l - 1] + X[l - 1])
return tvm.te.scan(s_init, s_update, s_state, inputs=[X], name="cumsum") |
<|file_name|>test_tir_transform_simplify.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
import tvm
from tvm import te
def test_stmt_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
with ib.for_range(0, n, name="i") as i:
with ib.if_scope(i < 12):
A[i] = C[i]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body, tvm.tir.Store)
def test_thread_extent_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(ty, "thread_extent", 1)
with ib.if_scope(tx + ty < 12):
A[tx] = C[tx + ty]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body.body, tvm.tir.Store)
def test_if_likely():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", 32)
ib.scope_attr(ty, "thread_extent", 32)
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
A[tx] = C[tx * 32 + ty]
body = ib.get()
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body, tvm.tir.IfThenElse)
assert not isinstance(body.body.body.then_case, tvm.tir.IfThenElse)
def test_basic_likely_elimination():
n = te.size_var("n")
X = te.placeholder(shape=(n,), name="x")
W = te.placeholder(shape=(n + 1,), dtype="int32", name="w")
def f(i):
start = W[i]
extent = W[i + 1] - W[i]
rv = te.reduce_axis((0, extent))
return te.sum(X[rv + start], axis=rv)
Y = te.compute(X.shape, f, name="y")
s = te.create_schedule([Y.op])
stmt = tvm.lower(s, [X, W, Y], simple_mode=True)
assert "if" not in str(stmt)
def test_complex_likely_elimination():
def cumsum(X):
"""
Y[i] = sum(X[:i])
"""
(m,) = X.shape
s_state = te.placeholder((m + 1,), dtype="int32", name="state")
s_init = te.compute((1,), lambda _: tvm.tir.const(0, "int32"))
s_update = te.compute((m + 1,), lambda l: s_state[l - 1] + X[l - 1])
return tvm.te.scan(s_init, s_update, s_state, inputs=[X], name="cumsum")
def sparse_lengths_sum(data, indices, lengths):
<|fim_middle|>
m, n, d, i, l = (
te.size_var("m"),
te.size_var("n"),
te.size_var("d"),
te.size_var("i"),
te.size_var("l"),
)
data_ph = te.placeholder((m, d * 32), name="data")
indices_ph = te.placeholder((i,), name="indices", dtype="int32")
lengths_ph = te.placeholder((n,), name="lengths", dtype="int32")
Y = sparse_lengths_sum(data_ph, indices_ph, lengths_ph)
s = te.create_schedule([Y.op])
(n, d) = s[Y].op.axis
(do, di) = s[Y].split(d, factor=32)
(gg,) = s[Y].op.reduce_axis
s[Y].reorder(n, do, gg, di)
s[Y].vectorize(di)
stmt = tvm.lower(s, [data_ph, indices_ph, lengths_ph, Y], simple_mode=True)
assert "if" not in str(stmt)
if __name__ == "__main__":
test_stmt_simplify()
test_thread_extent_simplify()
test_if_likely()
test_basic_likely_elimination()
test_complex_likely_elimination()
<|fim▁end|> | oshape = list(data.shape)
oshape[0] = lengths.shape[0]
length_offsets = cumsum(lengths)
def sls(n, d):
gg = te.reduce_axis((0, lengths[n]))
indices_idx = length_offsets[n] + gg
data_idx = indices[indices_idx]
data_val = data[data_idx, d]
return te.sum(data_val, axis=gg)
return te.compute(oshape, sls) |
<|file_name|>test_tir_transform_simplify.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
import tvm
from tvm import te
def test_stmt_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
with ib.for_range(0, n, name="i") as i:
with ib.if_scope(i < 12):
A[i] = C[i]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body, tvm.tir.Store)
def test_thread_extent_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(ty, "thread_extent", 1)
with ib.if_scope(tx + ty < 12):
A[tx] = C[tx + ty]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body.body, tvm.tir.Store)
def test_if_likely():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", 32)
ib.scope_attr(ty, "thread_extent", 32)
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
A[tx] = C[tx * 32 + ty]
body = ib.get()
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body, tvm.tir.IfThenElse)
assert not isinstance(body.body.body.then_case, tvm.tir.IfThenElse)
def test_basic_likely_elimination():
n = te.size_var("n")
X = te.placeholder(shape=(n,), name="x")
W = te.placeholder(shape=(n + 1,), dtype="int32", name="w")
def f(i):
start = W[i]
extent = W[i + 1] - W[i]
rv = te.reduce_axis((0, extent))
return te.sum(X[rv + start], axis=rv)
Y = te.compute(X.shape, f, name="y")
s = te.create_schedule([Y.op])
stmt = tvm.lower(s, [X, W, Y], simple_mode=True)
assert "if" not in str(stmt)
def test_complex_likely_elimination():
def cumsum(X):
"""
Y[i] = sum(X[:i])
"""
(m,) = X.shape
s_state = te.placeholder((m + 1,), dtype="int32", name="state")
s_init = te.compute((1,), lambda _: tvm.tir.const(0, "int32"))
s_update = te.compute((m + 1,), lambda l: s_state[l - 1] + X[l - 1])
return tvm.te.scan(s_init, s_update, s_state, inputs=[X], name="cumsum")
def sparse_lengths_sum(data, indices, lengths):
oshape = list(data.shape)
oshape[0] = lengths.shape[0]
length_offsets = cumsum(lengths)
def sls(n, d):
<|fim_middle|>
return te.compute(oshape, sls)
m, n, d, i, l = (
te.size_var("m"),
te.size_var("n"),
te.size_var("d"),
te.size_var("i"),
te.size_var("l"),
)
data_ph = te.placeholder((m, d * 32), name="data")
indices_ph = te.placeholder((i,), name="indices", dtype="int32")
lengths_ph = te.placeholder((n,), name="lengths", dtype="int32")
Y = sparse_lengths_sum(data_ph, indices_ph, lengths_ph)
s = te.create_schedule([Y.op])
(n, d) = s[Y].op.axis
(do, di) = s[Y].split(d, factor=32)
(gg,) = s[Y].op.reduce_axis
s[Y].reorder(n, do, gg, di)
s[Y].vectorize(di)
stmt = tvm.lower(s, [data_ph, indices_ph, lengths_ph, Y], simple_mode=True)
assert "if" not in str(stmt)
if __name__ == "__main__":
test_stmt_simplify()
test_thread_extent_simplify()
test_if_likely()
test_basic_likely_elimination()
test_complex_likely_elimination()
<|fim▁end|> | gg = te.reduce_axis((0, lengths[n]))
indices_idx = length_offsets[n] + gg
data_idx = indices[indices_idx]
data_val = data[data_idx, d]
return te.sum(data_val, axis=gg) |
<|file_name|>test_tir_transform_simplify.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
import tvm
from tvm import te
def test_stmt_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
with ib.for_range(0, n, name="i") as i:
with ib.if_scope(i < 12):
A[i] = C[i]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body, tvm.tir.Store)
def test_thread_extent_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(ty, "thread_extent", 1)
with ib.if_scope(tx + ty < 12):
A[tx] = C[tx + ty]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body.body, tvm.tir.Store)
def test_if_likely():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", 32)
ib.scope_attr(ty, "thread_extent", 32)
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
A[tx] = C[tx * 32 + ty]
body = ib.get()
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body, tvm.tir.IfThenElse)
assert not isinstance(body.body.body.then_case, tvm.tir.IfThenElse)
def test_basic_likely_elimination():
n = te.size_var("n")
X = te.placeholder(shape=(n,), name="x")
W = te.placeholder(shape=(n + 1,), dtype="int32", name="w")
def f(i):
start = W[i]
extent = W[i + 1] - W[i]
rv = te.reduce_axis((0, extent))
return te.sum(X[rv + start], axis=rv)
Y = te.compute(X.shape, f, name="y")
s = te.create_schedule([Y.op])
stmt = tvm.lower(s, [X, W, Y], simple_mode=True)
assert "if" not in str(stmt)
def test_complex_likely_elimination():
def cumsum(X):
"""
Y[i] = sum(X[:i])
"""
(m,) = X.shape
s_state = te.placeholder((m + 1,), dtype="int32", name="state")
s_init = te.compute((1,), lambda _: tvm.tir.const(0, "int32"))
s_update = te.compute((m + 1,), lambda l: s_state[l - 1] + X[l - 1])
return tvm.te.scan(s_init, s_update, s_state, inputs=[X], name="cumsum")
def sparse_lengths_sum(data, indices, lengths):
oshape = list(data.shape)
oshape[0] = lengths.shape[0]
length_offsets = cumsum(lengths)
def sls(n, d):
gg = te.reduce_axis((0, lengths[n]))
indices_idx = length_offsets[n] + gg
data_idx = indices[indices_idx]
data_val = data[data_idx, d]
return te.sum(data_val, axis=gg)
return te.compute(oshape, sls)
m, n, d, i, l = (
te.size_var("m"),
te.size_var("n"),
te.size_var("d"),
te.size_var("i"),
te.size_var("l"),
)
data_ph = te.placeholder((m, d * 32), name="data")
indices_ph = te.placeholder((i,), name="indices", dtype="int32")
lengths_ph = te.placeholder((n,), name="lengths", dtype="int32")
Y = sparse_lengths_sum(data_ph, indices_ph, lengths_ph)
s = te.create_schedule([Y.op])
(n, d) = s[Y].op.axis
(do, di) = s[Y].split(d, factor=32)
(gg,) = s[Y].op.reduce_axis
s[Y].reorder(n, do, gg, di)
s[Y].vectorize(di)
stmt = tvm.lower(s, [data_ph, indices_ph, lengths_ph, Y], simple_mode=True)
assert "if" not in str(stmt)
if __name__ == "__main__":
<|fim_middle|>
<|fim▁end|> | test_stmt_simplify()
test_thread_extent_simplify()
test_if_likely()
test_basic_likely_elimination()
test_complex_likely_elimination() |
Subsets and Splits