prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>282 Expression Add Operators.py<|end_file_name|><|fim▁begin|>"""
Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not
unary) +, -, or * between the digits so they evaluate to the target value.
Examples:
"123", 6 -> ["1+2+3", "1*2*3"]
"232", 8 -> ["2*3+2", "2+3*2"]
"105", 5 -> ["1*0+5","10-5"]
"00", 0 -> ["0+0", "0-0", "0*0"]
"3456237490", 9191 -> []
"""
__author__ = 'Daniel'
class Solution(object):
def addOperators(self, num, target):
"""
Adapted from https://leetcode.com/discuss/58614/java-standard-backtrace-ac-solutoin-short-and-clear
Algorithm:
1. DFS
2. Special handling for multiplication
3. Detect invalid number with leading 0's
:type num: str
:type target: int
:rtype: List[str]
"""
ret = []
self.dfs(num, target, 0, "", 0, 0, ret)
return ret
def dfs(self, num, target, pos, cur_str, cur_val, mul, ret):
if pos >= len(num):
<|fim_middle|>
else:
for i in xrange(pos, len(num)):
if i != pos and num[pos] == "0":
continue
nxt_val = int(num[pos:i+1])
if not cur_str:
self.dfs(num, target, i+1, "%d"%nxt_val, nxt_val, nxt_val, ret)
else:
self.dfs(num, target, i+1, cur_str+"+%d"%nxt_val, cur_val+nxt_val, nxt_val, ret)
self.dfs(num, target, i+1, cur_str+"-%d"%nxt_val, cur_val-nxt_val, -nxt_val, ret)
self.dfs(num, target, i+1, cur_str+"*%d"%nxt_val, cur_val-mul+mul*nxt_val, mul*nxt_val, ret)
if __name__ == "__main__":
assert Solution().addOperators("232", 8) == ["2+3*2", "2*3+2"]
<|fim▁end|> | if cur_val == target:
ret.append(cur_str) |
<|file_name|>282 Expression Add Operators.py<|end_file_name|><|fim▁begin|>"""
Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not
unary) +, -, or * between the digits so they evaluate to the target value.
Examples:
"123", 6 -> ["1+2+3", "1*2*3"]
"232", 8 -> ["2*3+2", "2+3*2"]
"105", 5 -> ["1*0+5","10-5"]
"00", 0 -> ["0+0", "0-0", "0*0"]
"3456237490", 9191 -> []
"""
__author__ = 'Daniel'
class Solution(object):
def addOperators(self, num, target):
"""
Adapted from https://leetcode.com/discuss/58614/java-standard-backtrace-ac-solutoin-short-and-clear
Algorithm:
1. DFS
2. Special handling for multiplication
3. Detect invalid number with leading 0's
:type num: str
:type target: int
:rtype: List[str]
"""
ret = []
self.dfs(num, target, 0, "", 0, 0, ret)
return ret
def dfs(self, num, target, pos, cur_str, cur_val, mul, ret):
if pos >= len(num):
if cur_val == target:
<|fim_middle|>
else:
for i in xrange(pos, len(num)):
if i != pos and num[pos] == "0":
continue
nxt_val = int(num[pos:i+1])
if not cur_str:
self.dfs(num, target, i+1, "%d"%nxt_val, nxt_val, nxt_val, ret)
else:
self.dfs(num, target, i+1, cur_str+"+%d"%nxt_val, cur_val+nxt_val, nxt_val, ret)
self.dfs(num, target, i+1, cur_str+"-%d"%nxt_val, cur_val-nxt_val, -nxt_val, ret)
self.dfs(num, target, i+1, cur_str+"*%d"%nxt_val, cur_val-mul+mul*nxt_val, mul*nxt_val, ret)
if __name__ == "__main__":
assert Solution().addOperators("232", 8) == ["2+3*2", "2*3+2"]
<|fim▁end|> | ret.append(cur_str) |
<|file_name|>282 Expression Add Operators.py<|end_file_name|><|fim▁begin|>"""
Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not
unary) +, -, or * between the digits so they evaluate to the target value.
Examples:
"123", 6 -> ["1+2+3", "1*2*3"]
"232", 8 -> ["2*3+2", "2+3*2"]
"105", 5 -> ["1*0+5","10-5"]
"00", 0 -> ["0+0", "0-0", "0*0"]
"3456237490", 9191 -> []
"""
__author__ = 'Daniel'
class Solution(object):
def addOperators(self, num, target):
"""
Adapted from https://leetcode.com/discuss/58614/java-standard-backtrace-ac-solutoin-short-and-clear
Algorithm:
1. DFS
2. Special handling for multiplication
3. Detect invalid number with leading 0's
:type num: str
:type target: int
:rtype: List[str]
"""
ret = []
self.dfs(num, target, 0, "", 0, 0, ret)
return ret
def dfs(self, num, target, pos, cur_str, cur_val, mul, ret):
if pos >= len(num):
if cur_val == target:
ret.append(cur_str)
else:
<|fim_middle|>
if __name__ == "__main__":
assert Solution().addOperators("232", 8) == ["2+3*2", "2*3+2"]
<|fim▁end|> | for i in xrange(pos, len(num)):
if i != pos and num[pos] == "0":
continue
nxt_val = int(num[pos:i+1])
if not cur_str:
self.dfs(num, target, i+1, "%d"%nxt_val, nxt_val, nxt_val, ret)
else:
self.dfs(num, target, i+1, cur_str+"+%d"%nxt_val, cur_val+nxt_val, nxt_val, ret)
self.dfs(num, target, i+1, cur_str+"-%d"%nxt_val, cur_val-nxt_val, -nxt_val, ret)
self.dfs(num, target, i+1, cur_str+"*%d"%nxt_val, cur_val-mul+mul*nxt_val, mul*nxt_val, ret) |
<|file_name|>282 Expression Add Operators.py<|end_file_name|><|fim▁begin|>"""
Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not
unary) +, -, or * between the digits so they evaluate to the target value.
Examples:
"123", 6 -> ["1+2+3", "1*2*3"]
"232", 8 -> ["2*3+2", "2+3*2"]
"105", 5 -> ["1*0+5","10-5"]
"00", 0 -> ["0+0", "0-0", "0*0"]
"3456237490", 9191 -> []
"""
__author__ = 'Daniel'
class Solution(object):
def addOperators(self, num, target):
"""
Adapted from https://leetcode.com/discuss/58614/java-standard-backtrace-ac-solutoin-short-and-clear
Algorithm:
1. DFS
2. Special handling for multiplication
3. Detect invalid number with leading 0's
:type num: str
:type target: int
:rtype: List[str]
"""
ret = []
self.dfs(num, target, 0, "", 0, 0, ret)
return ret
def dfs(self, num, target, pos, cur_str, cur_val, mul, ret):
if pos >= len(num):
if cur_val == target:
ret.append(cur_str)
else:
for i in xrange(pos, len(num)):
if i != pos and num[pos] == "0":
<|fim_middle|>
nxt_val = int(num[pos:i+1])
if not cur_str:
self.dfs(num, target, i+1, "%d"%nxt_val, nxt_val, nxt_val, ret)
else:
self.dfs(num, target, i+1, cur_str+"+%d"%nxt_val, cur_val+nxt_val, nxt_val, ret)
self.dfs(num, target, i+1, cur_str+"-%d"%nxt_val, cur_val-nxt_val, -nxt_val, ret)
self.dfs(num, target, i+1, cur_str+"*%d"%nxt_val, cur_val-mul+mul*nxt_val, mul*nxt_val, ret)
if __name__ == "__main__":
assert Solution().addOperators("232", 8) == ["2+3*2", "2*3+2"]
<|fim▁end|> | continue |
<|file_name|>282 Expression Add Operators.py<|end_file_name|><|fim▁begin|>"""
Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not
unary) +, -, or * between the digits so they evaluate to the target value.
Examples:
"123", 6 -> ["1+2+3", "1*2*3"]
"232", 8 -> ["2*3+2", "2+3*2"]
"105", 5 -> ["1*0+5","10-5"]
"00", 0 -> ["0+0", "0-0", "0*0"]
"3456237490", 9191 -> []
"""
__author__ = 'Daniel'
class Solution(object):
def addOperators(self, num, target):
"""
Adapted from https://leetcode.com/discuss/58614/java-standard-backtrace-ac-solutoin-short-and-clear
Algorithm:
1. DFS
2. Special handling for multiplication
3. Detect invalid number with leading 0's
:type num: str
:type target: int
:rtype: List[str]
"""
ret = []
self.dfs(num, target, 0, "", 0, 0, ret)
return ret
def dfs(self, num, target, pos, cur_str, cur_val, mul, ret):
if pos >= len(num):
if cur_val == target:
ret.append(cur_str)
else:
for i in xrange(pos, len(num)):
if i != pos and num[pos] == "0":
continue
nxt_val = int(num[pos:i+1])
if not cur_str:
<|fim_middle|>
else:
self.dfs(num, target, i+1, cur_str+"+%d"%nxt_val, cur_val+nxt_val, nxt_val, ret)
self.dfs(num, target, i+1, cur_str+"-%d"%nxt_val, cur_val-nxt_val, -nxt_val, ret)
self.dfs(num, target, i+1, cur_str+"*%d"%nxt_val, cur_val-mul+mul*nxt_val, mul*nxt_val, ret)
if __name__ == "__main__":
assert Solution().addOperators("232", 8) == ["2+3*2", "2*3+2"]
<|fim▁end|> | self.dfs(num, target, i+1, "%d"%nxt_val, nxt_val, nxt_val, ret) |
<|file_name|>282 Expression Add Operators.py<|end_file_name|><|fim▁begin|>"""
Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not
unary) +, -, or * between the digits so they evaluate to the target value.
Examples:
"123", 6 -> ["1+2+3", "1*2*3"]
"232", 8 -> ["2*3+2", "2+3*2"]
"105", 5 -> ["1*0+5","10-5"]
"00", 0 -> ["0+0", "0-0", "0*0"]
"3456237490", 9191 -> []
"""
__author__ = 'Daniel'
class Solution(object):
def addOperators(self, num, target):
"""
Adapted from https://leetcode.com/discuss/58614/java-standard-backtrace-ac-solutoin-short-and-clear
Algorithm:
1. DFS
2. Special handling for multiplication
3. Detect invalid number with leading 0's
:type num: str
:type target: int
:rtype: List[str]
"""
ret = []
self.dfs(num, target, 0, "", 0, 0, ret)
return ret
def dfs(self, num, target, pos, cur_str, cur_val, mul, ret):
if pos >= len(num):
if cur_val == target:
ret.append(cur_str)
else:
for i in xrange(pos, len(num)):
if i != pos and num[pos] == "0":
continue
nxt_val = int(num[pos:i+1])
if not cur_str:
self.dfs(num, target, i+1, "%d"%nxt_val, nxt_val, nxt_val, ret)
else:
<|fim_middle|>
if __name__ == "__main__":
assert Solution().addOperators("232", 8) == ["2+3*2", "2*3+2"]
<|fim▁end|> | self.dfs(num, target, i+1, cur_str+"+%d"%nxt_val, cur_val+nxt_val, nxt_val, ret)
self.dfs(num, target, i+1, cur_str+"-%d"%nxt_val, cur_val-nxt_val, -nxt_val, ret)
self.dfs(num, target, i+1, cur_str+"*%d"%nxt_val, cur_val-mul+mul*nxt_val, mul*nxt_val, ret) |
<|file_name|>282 Expression Add Operators.py<|end_file_name|><|fim▁begin|>"""
Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not
unary) +, -, or * between the digits so they evaluate to the target value.
Examples:
"123", 6 -> ["1+2+3", "1*2*3"]
"232", 8 -> ["2*3+2", "2+3*2"]
"105", 5 -> ["1*0+5","10-5"]
"00", 0 -> ["0+0", "0-0", "0*0"]
"3456237490", 9191 -> []
"""
__author__ = 'Daniel'
class Solution(object):
def addOperators(self, num, target):
"""
Adapted from https://leetcode.com/discuss/58614/java-standard-backtrace-ac-solutoin-short-and-clear
Algorithm:
1. DFS
2. Special handling for multiplication
3. Detect invalid number with leading 0's
:type num: str
:type target: int
:rtype: List[str]
"""
ret = []
self.dfs(num, target, 0, "", 0, 0, ret)
return ret
def dfs(self, num, target, pos, cur_str, cur_val, mul, ret):
if pos >= len(num):
if cur_val == target:
ret.append(cur_str)
else:
for i in xrange(pos, len(num)):
if i != pos and num[pos] == "0":
continue
nxt_val = int(num[pos:i+1])
if not cur_str:
self.dfs(num, target, i+1, "%d"%nxt_val, nxt_val, nxt_val, ret)
else:
self.dfs(num, target, i+1, cur_str+"+%d"%nxt_val, cur_val+nxt_val, nxt_val, ret)
self.dfs(num, target, i+1, cur_str+"-%d"%nxt_val, cur_val-nxt_val, -nxt_val, ret)
self.dfs(num, target, i+1, cur_str+"*%d"%nxt_val, cur_val-mul+mul*nxt_val, mul*nxt_val, ret)
if __name__ == "__main__":
<|fim_middle|>
<|fim▁end|> | assert Solution().addOperators("232", 8) == ["2+3*2", "2*3+2"] |
<|file_name|>282 Expression Add Operators.py<|end_file_name|><|fim▁begin|>"""
Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not
unary) +, -, or * between the digits so they evaluate to the target value.
Examples:
"123", 6 -> ["1+2+3", "1*2*3"]
"232", 8 -> ["2*3+2", "2+3*2"]
"105", 5 -> ["1*0+5","10-5"]
"00", 0 -> ["0+0", "0-0", "0*0"]
"3456237490", 9191 -> []
"""
__author__ = 'Daniel'
class Solution(object):
def <|fim_middle|>(self, num, target):
"""
Adapted from https://leetcode.com/discuss/58614/java-standard-backtrace-ac-solutoin-short-and-clear
Algorithm:
1. DFS
2. Special handling for multiplication
3. Detect invalid number with leading 0's
:type num: str
:type target: int
:rtype: List[str]
"""
ret = []
self.dfs(num, target, 0, "", 0, 0, ret)
return ret
def dfs(self, num, target, pos, cur_str, cur_val, mul, ret):
if pos >= len(num):
if cur_val == target:
ret.append(cur_str)
else:
for i in xrange(pos, len(num)):
if i != pos and num[pos] == "0":
continue
nxt_val = int(num[pos:i+1])
if not cur_str:
self.dfs(num, target, i+1, "%d"%nxt_val, nxt_val, nxt_val, ret)
else:
self.dfs(num, target, i+1, cur_str+"+%d"%nxt_val, cur_val+nxt_val, nxt_val, ret)
self.dfs(num, target, i+1, cur_str+"-%d"%nxt_val, cur_val-nxt_val, -nxt_val, ret)
self.dfs(num, target, i+1, cur_str+"*%d"%nxt_val, cur_val-mul+mul*nxt_val, mul*nxt_val, ret)
if __name__ == "__main__":
assert Solution().addOperators("232", 8) == ["2+3*2", "2*3+2"]
<|fim▁end|> | addOperators |
<|file_name|>282 Expression Add Operators.py<|end_file_name|><|fim▁begin|>"""
Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not
unary) +, -, or * between the digits so they evaluate to the target value.
Examples:
"123", 6 -> ["1+2+3", "1*2*3"]
"232", 8 -> ["2*3+2", "2+3*2"]
"105", 5 -> ["1*0+5","10-5"]
"00", 0 -> ["0+0", "0-0", "0*0"]
"3456237490", 9191 -> []
"""
__author__ = 'Daniel'
class Solution(object):
def addOperators(self, num, target):
"""
Adapted from https://leetcode.com/discuss/58614/java-standard-backtrace-ac-solutoin-short-and-clear
Algorithm:
1. DFS
2. Special handling for multiplication
3. Detect invalid number with leading 0's
:type num: str
:type target: int
:rtype: List[str]
"""
ret = []
self.dfs(num, target, 0, "", 0, 0, ret)
return ret
def <|fim_middle|>(self, num, target, pos, cur_str, cur_val, mul, ret):
if pos >= len(num):
if cur_val == target:
ret.append(cur_str)
else:
for i in xrange(pos, len(num)):
if i != pos and num[pos] == "0":
continue
nxt_val = int(num[pos:i+1])
if not cur_str:
self.dfs(num, target, i+1, "%d"%nxt_val, nxt_val, nxt_val, ret)
else:
self.dfs(num, target, i+1, cur_str+"+%d"%nxt_val, cur_val+nxt_val, nxt_val, ret)
self.dfs(num, target, i+1, cur_str+"-%d"%nxt_val, cur_val-nxt_val, -nxt_val, ret)
self.dfs(num, target, i+1, cur_str+"*%d"%nxt_val, cur_val-mul+mul*nxt_val, mul*nxt_val, ret)
if __name__ == "__main__":
assert Solution().addOperators("232", 8) == ["2+3*2", "2*3+2"]
<|fim▁end|> | dfs |
<|file_name|>runescapecompare.py<|end_file_name|><|fim▁begin|>import discord
import asyncio
import datetime
import time
import aiohttp
import threading
import glob
import re
import json
import os
import urllib.request
from discord.ext import commands
from random import randint
from random import choice as randchoice
from random import choice as rndchoice
from random import shuffle
from .utils.dataIO import fileIO
from .utils import checks
from bs4 import BeautifulSoup
class Runescapecompare:
"""Runescape-relate commands"""
def __init__(self, bot):
self.bot = bot
"""
imLink = http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=
nmLink = http://services.runescape.com/m=hiscore/index_lite.ws?player=
"""<|fim▁hole|> if ctx.invoked_subcommand is None:
await self.bot.say("Please, choose a skill to compare!")
#####Overall#####
@_compare.command(name="overall", pass_context=True)
async def compare_overall(self, ctx, name1 : str, name2 : str):
address1 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name1
address2 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name2
try:
website1 = urllib.request.urlopen(address1)
website2 = urllib.request.urlopen(address2)
website_html1 = website1.read().decode(website1.headers.get_content_charset())
website_html2 = website2.read().decode(website2.headers.get_content_charset())
stats1 = website_html1.split("\n")
stats2 = website_html2.split("\n")
stat1 = stats1[0].split(",")
stat2= stats2[0].split(",")
if stat1[2] > stat2[2]:
comparerank = int(stat2[0]) - int(stat1[0])
comparelvl = int(stat1[1]) - int(stat2[1])
comparexp = int(stat1[2]) - int(stat2[2])
await self.bot.say("```" + name1 + "'s ranking is " + str(comparerank) + " ranks higher than " + name2 + "'s rank.\n" + name1 + "'s level is " + str(comparelvl) + " levels higher than " + name2 + "'s.\n" + name1 + "'s total experience is " + str(comparexp) + " higher than " + name2 + "'s.```")
if stat2[2] > stat1[2]:
comparerank = stat2[0] - stat1[0]
comparelvl = stat2[1] - stat1[1]
comparexp = stat2[2] - stat1[2]
await self.bot.say("```" + name2 + "'s ranking is " + str(comparerank) + " ranks higher than " + name1 + "'s rank.\n" + name2 + "'s level is " + str(comparelvl) + " levels higher than " + name1 + "'s.\n" + name2 + "'s total experience is " + str(comparexp) + " higher than " + name1 + "'s.```")
except:
await self.bot.say("Sorry... Something went wrong there. Did you type the name correctly?")
def setup(bot):
n = Runescapecompare(bot)
bot.add_cog(n)<|fim▁end|> |
@commands.group(name="compare", pass_context=True)
async def _compare(self, ctx): |
<|file_name|>runescapecompare.py<|end_file_name|><|fim▁begin|>import discord
import asyncio
import datetime
import time
import aiohttp
import threading
import glob
import re
import json
import os
import urllib.request
from discord.ext import commands
from random import randint
from random import choice as randchoice
from random import choice as rndchoice
from random import shuffle
from .utils.dataIO import fileIO
from .utils import checks
from bs4 import BeautifulSoup
class Runescapecompare:
<|fim_middle|>
def setup(bot):
n = Runescapecompare(bot)
bot.add_cog(n)
<|fim▁end|> | """Runescape-relate commands"""
def __init__(self, bot):
self.bot = bot
"""
imLink = http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=
nmLink = http://services.runescape.com/m=hiscore/index_lite.ws?player=
"""
@commands.group(name="compare", pass_context=True)
async def _compare(self, ctx):
if ctx.invoked_subcommand is None:
await self.bot.say("Please, choose a skill to compare!")
#####Overall#####
@_compare.command(name="overall", pass_context=True)
async def compare_overall(self, ctx, name1 : str, name2 : str):
address1 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name1
address2 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name2
try:
website1 = urllib.request.urlopen(address1)
website2 = urllib.request.urlopen(address2)
website_html1 = website1.read().decode(website1.headers.get_content_charset())
website_html2 = website2.read().decode(website2.headers.get_content_charset())
stats1 = website_html1.split("\n")
stats2 = website_html2.split("\n")
stat1 = stats1[0].split(",")
stat2= stats2[0].split(",")
if stat1[2] > stat2[2]:
comparerank = int(stat2[0]) - int(stat1[0])
comparelvl = int(stat1[1]) - int(stat2[1])
comparexp = int(stat1[2]) - int(stat2[2])
await self.bot.say("```" + name1 + "'s ranking is " + str(comparerank) + " ranks higher than " + name2 + "'s rank.\n" + name1 + "'s level is " + str(comparelvl) + " levels higher than " + name2 + "'s.\n" + name1 + "'s total experience is " + str(comparexp) + " higher than " + name2 + "'s.```")
if stat2[2] > stat1[2]:
comparerank = stat2[0] - stat1[0]
comparelvl = stat2[1] - stat1[1]
comparexp = stat2[2] - stat1[2]
await self.bot.say("```" + name2 + "'s ranking is " + str(comparerank) + " ranks higher than " + name1 + "'s rank.\n" + name2 + "'s level is " + str(comparelvl) + " levels higher than " + name1 + "'s.\n" + name2 + "'s total experience is " + str(comparexp) + " higher than " + name1 + "'s.```")
except:
await self.bot.say("Sorry... Something went wrong there. Did you type the name correctly?") |
<|file_name|>runescapecompare.py<|end_file_name|><|fim▁begin|>import discord
import asyncio
import datetime
import time
import aiohttp
import threading
import glob
import re
import json
import os
import urllib.request
from discord.ext import commands
from random import randint
from random import choice as randchoice
from random import choice as rndchoice
from random import shuffle
from .utils.dataIO import fileIO
from .utils import checks
from bs4 import BeautifulSoup
class Runescapecompare:
"""Runescape-relate commands"""
def __init__(self, bot):
<|fim_middle|>
@commands.group(name="compare", pass_context=True)
async def _compare(self, ctx):
if ctx.invoked_subcommand is None:
await self.bot.say("Please, choose a skill to compare!")
#####Overall#####
@_compare.command(name="overall", pass_context=True)
async def compare_overall(self, ctx, name1 : str, name2 : str):
address1 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name1
address2 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name2
try:
website1 = urllib.request.urlopen(address1)
website2 = urllib.request.urlopen(address2)
website_html1 = website1.read().decode(website1.headers.get_content_charset())
website_html2 = website2.read().decode(website2.headers.get_content_charset())
stats1 = website_html1.split("\n")
stats2 = website_html2.split("\n")
stat1 = stats1[0].split(",")
stat2= stats2[0].split(",")
if stat1[2] > stat2[2]:
comparerank = int(stat2[0]) - int(stat1[0])
comparelvl = int(stat1[1]) - int(stat2[1])
comparexp = int(stat1[2]) - int(stat2[2])
await self.bot.say("```" + name1 + "'s ranking is " + str(comparerank) + " ranks higher than " + name2 + "'s rank.\n" + name1 + "'s level is " + str(comparelvl) + " levels higher than " + name2 + "'s.\n" + name1 + "'s total experience is " + str(comparexp) + " higher than " + name2 + "'s.```")
if stat2[2] > stat1[2]:
comparerank = stat2[0] - stat1[0]
comparelvl = stat2[1] - stat1[1]
comparexp = stat2[2] - stat1[2]
await self.bot.say("```" + name2 + "'s ranking is " + str(comparerank) + " ranks higher than " + name1 + "'s rank.\n" + name2 + "'s level is " + str(comparelvl) + " levels higher than " + name1 + "'s.\n" + name2 + "'s total experience is " + str(comparexp) + " higher than " + name1 + "'s.```")
except:
await self.bot.say("Sorry... Something went wrong there. Did you type the name correctly?")
def setup(bot):
n = Runescapecompare(bot)
bot.add_cog(n)
<|fim▁end|> | self.bot = bot
"""
imLink = http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=
nmLink = http://services.runescape.com/m=hiscore/index_lite.ws?player=
""" |
<|file_name|>runescapecompare.py<|end_file_name|><|fim▁begin|>import discord
import asyncio
import datetime
import time
import aiohttp
import threading
import glob
import re
import json
import os
import urllib.request
from discord.ext import commands
from random import randint
from random import choice as randchoice
from random import choice as rndchoice
from random import shuffle
from .utils.dataIO import fileIO
from .utils import checks
from bs4 import BeautifulSoup
class Runescapecompare:
"""Runescape-relate commands"""
def __init__(self, bot):
self.bot = bot
"""
imLink = http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=
nmLink = http://services.runescape.com/m=hiscore/index_lite.ws?player=
"""
@commands.group(name="compare", pass_context=True)
async def _compare(self, ctx):
<|fim_middle|>
#####Overall#####
@_compare.command(name="overall", pass_context=True)
async def compare_overall(self, ctx, name1 : str, name2 : str):
address1 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name1
address2 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name2
try:
website1 = urllib.request.urlopen(address1)
website2 = urllib.request.urlopen(address2)
website_html1 = website1.read().decode(website1.headers.get_content_charset())
website_html2 = website2.read().decode(website2.headers.get_content_charset())
stats1 = website_html1.split("\n")
stats2 = website_html2.split("\n")
stat1 = stats1[0].split(",")
stat2= stats2[0].split(",")
if stat1[2] > stat2[2]:
comparerank = int(stat2[0]) - int(stat1[0])
comparelvl = int(stat1[1]) - int(stat2[1])
comparexp = int(stat1[2]) - int(stat2[2])
await self.bot.say("```" + name1 + "'s ranking is " + str(comparerank) + " ranks higher than " + name2 + "'s rank.\n" + name1 + "'s level is " + str(comparelvl) + " levels higher than " + name2 + "'s.\n" + name1 + "'s total experience is " + str(comparexp) + " higher than " + name2 + "'s.```")
if stat2[2] > stat1[2]:
comparerank = stat2[0] - stat1[0]
comparelvl = stat2[1] - stat1[1]
comparexp = stat2[2] - stat1[2]
await self.bot.say("```" + name2 + "'s ranking is " + str(comparerank) + " ranks higher than " + name1 + "'s rank.\n" + name2 + "'s level is " + str(comparelvl) + " levels higher than " + name1 + "'s.\n" + name2 + "'s total experience is " + str(comparexp) + " higher than " + name1 + "'s.```")
except:
await self.bot.say("Sorry... Something went wrong there. Did you type the name correctly?")
def setup(bot):
n = Runescapecompare(bot)
bot.add_cog(n)
<|fim▁end|> | if ctx.invoked_subcommand is None:
await self.bot.say("Please, choose a skill to compare!") |
<|file_name|>runescapecompare.py<|end_file_name|><|fim▁begin|>import discord
import asyncio
import datetime
import time
import aiohttp
import threading
import glob
import re
import json
import os
import urllib.request
from discord.ext import commands
from random import randint
from random import choice as randchoice
from random import choice as rndchoice
from random import shuffle
from .utils.dataIO import fileIO
from .utils import checks
from bs4 import BeautifulSoup
class Runescapecompare:
"""Runescape-relate commands"""
def __init__(self, bot):
self.bot = bot
"""
imLink = http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=
nmLink = http://services.runescape.com/m=hiscore/index_lite.ws?player=
"""
@commands.group(name="compare", pass_context=True)
async def _compare(self, ctx):
if ctx.invoked_subcommand is None:
await self.bot.say("Please, choose a skill to compare!")
#####Overall#####
@_compare.command(name="overall", pass_context=True)
async def compare_overall(self, ctx, name1 : str, name2 : str):
<|fim_middle|>
def setup(bot):
n = Runescapecompare(bot)
bot.add_cog(n)
<|fim▁end|> | address1 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name1
address2 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name2
try:
website1 = urllib.request.urlopen(address1)
website2 = urllib.request.urlopen(address2)
website_html1 = website1.read().decode(website1.headers.get_content_charset())
website_html2 = website2.read().decode(website2.headers.get_content_charset())
stats1 = website_html1.split("\n")
stats2 = website_html2.split("\n")
stat1 = stats1[0].split(",")
stat2= stats2[0].split(",")
if stat1[2] > stat2[2]:
comparerank = int(stat2[0]) - int(stat1[0])
comparelvl = int(stat1[1]) - int(stat2[1])
comparexp = int(stat1[2]) - int(stat2[2])
await self.bot.say("```" + name1 + "'s ranking is " + str(comparerank) + " ranks higher than " + name2 + "'s rank.\n" + name1 + "'s level is " + str(comparelvl) + " levels higher than " + name2 + "'s.\n" + name1 + "'s total experience is " + str(comparexp) + " higher than " + name2 + "'s.```")
if stat2[2] > stat1[2]:
comparerank = stat2[0] - stat1[0]
comparelvl = stat2[1] - stat1[1]
comparexp = stat2[2] - stat1[2]
await self.bot.say("```" + name2 + "'s ranking is " + str(comparerank) + " ranks higher than " + name1 + "'s rank.\n" + name2 + "'s level is " + str(comparelvl) + " levels higher than " + name1 + "'s.\n" + name2 + "'s total experience is " + str(comparexp) + " higher than " + name1 + "'s.```")
except:
await self.bot.say("Sorry... Something went wrong there. Did you type the name correctly?") |
<|file_name|>runescapecompare.py<|end_file_name|><|fim▁begin|>import discord
import asyncio
import datetime
import time
import aiohttp
import threading
import glob
import re
import json
import os
import urllib.request
from discord.ext import commands
from random import randint
from random import choice as randchoice
from random import choice as rndchoice
from random import shuffle
from .utils.dataIO import fileIO
from .utils import checks
from bs4 import BeautifulSoup
class Runescapecompare:
"""Runescape-relate commands"""
def __init__(self, bot):
self.bot = bot
"""
imLink = http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=
nmLink = http://services.runescape.com/m=hiscore/index_lite.ws?player=
"""
@commands.group(name="compare", pass_context=True)
async def _compare(self, ctx):
if ctx.invoked_subcommand is None:
await self.bot.say("Please, choose a skill to compare!")
#####Overall#####
@_compare.command(name="overall", pass_context=True)
async def compare_overall(self, ctx, name1 : str, name2 : str):
address1 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name1
address2 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name2
try:
website1 = urllib.request.urlopen(address1)
website2 = urllib.request.urlopen(address2)
website_html1 = website1.read().decode(website1.headers.get_content_charset())
website_html2 = website2.read().decode(website2.headers.get_content_charset())
stats1 = website_html1.split("\n")
stats2 = website_html2.split("\n")
stat1 = stats1[0].split(",")
stat2= stats2[0].split(",")
if stat1[2] > stat2[2]:
comparerank = int(stat2[0]) - int(stat1[0])
comparelvl = int(stat1[1]) - int(stat2[1])
comparexp = int(stat1[2]) - int(stat2[2])
await self.bot.say("```" + name1 + "'s ranking is " + str(comparerank) + " ranks higher than " + name2 + "'s rank.\n" + name1 + "'s level is " + str(comparelvl) + " levels higher than " + name2 + "'s.\n" + name1 + "'s total experience is " + str(comparexp) + " higher than " + name2 + "'s.```")
if stat2[2] > stat1[2]:
comparerank = stat2[0] - stat1[0]
comparelvl = stat2[1] - stat1[1]
comparexp = stat2[2] - stat1[2]
await self.bot.say("```" + name2 + "'s ranking is " + str(comparerank) + " ranks higher than " + name1 + "'s rank.\n" + name2 + "'s level is " + str(comparelvl) + " levels higher than " + name1 + "'s.\n" + name2 + "'s total experience is " + str(comparexp) + " higher than " + name1 + "'s.```")
except:
await self.bot.say("Sorry... Something went wrong there. Did you type the name correctly?")
def setup(bot):
<|fim_middle|>
<|fim▁end|> | n = Runescapecompare(bot)
bot.add_cog(n) |
<|file_name|>runescapecompare.py<|end_file_name|><|fim▁begin|>import discord
import asyncio
import datetime
import time
import aiohttp
import threading
import glob
import re
import json
import os
import urllib.request
from discord.ext import commands
from random import randint
from random import choice as randchoice
from random import choice as rndchoice
from random import shuffle
from .utils.dataIO import fileIO
from .utils import checks
from bs4 import BeautifulSoup
class Runescapecompare:
"""Runescape-relate commands"""
def __init__(self, bot):
self.bot = bot
"""
imLink = http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=
nmLink = http://services.runescape.com/m=hiscore/index_lite.ws?player=
"""
@commands.group(name="compare", pass_context=True)
async def _compare(self, ctx):
if ctx.invoked_subcommand is None:
<|fim_middle|>
#####Overall#####
@_compare.command(name="overall", pass_context=True)
async def compare_overall(self, ctx, name1 : str, name2 : str):
address1 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name1
address2 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name2
try:
website1 = urllib.request.urlopen(address1)
website2 = urllib.request.urlopen(address2)
website_html1 = website1.read().decode(website1.headers.get_content_charset())
website_html2 = website2.read().decode(website2.headers.get_content_charset())
stats1 = website_html1.split("\n")
stats2 = website_html2.split("\n")
stat1 = stats1[0].split(",")
stat2= stats2[0].split(",")
if stat1[2] > stat2[2]:
comparerank = int(stat2[0]) - int(stat1[0])
comparelvl = int(stat1[1]) - int(stat2[1])
comparexp = int(stat1[2]) - int(stat2[2])
await self.bot.say("```" + name1 + "'s ranking is " + str(comparerank) + " ranks higher than " + name2 + "'s rank.\n" + name1 + "'s level is " + str(comparelvl) + " levels higher than " + name2 + "'s.\n" + name1 + "'s total experience is " + str(comparexp) + " higher than " + name2 + "'s.```")
if stat2[2] > stat1[2]:
comparerank = stat2[0] - stat1[0]
comparelvl = stat2[1] - stat1[1]
comparexp = stat2[2] - stat1[2]
await self.bot.say("```" + name2 + "'s ranking is " + str(comparerank) + " ranks higher than " + name1 + "'s rank.\n" + name2 + "'s level is " + str(comparelvl) + " levels higher than " + name1 + "'s.\n" + name2 + "'s total experience is " + str(comparexp) + " higher than " + name1 + "'s.```")
except:
await self.bot.say("Sorry... Something went wrong there. Did you type the name correctly?")
def setup(bot):
n = Runescapecompare(bot)
bot.add_cog(n)
<|fim▁end|> | await self.bot.say("Please, choose a skill to compare!") |
<|file_name|>runescapecompare.py<|end_file_name|><|fim▁begin|>import discord
import asyncio
import datetime
import time
import aiohttp
import threading
import glob
import re
import json
import os
import urllib.request
from discord.ext import commands
from random import randint
from random import choice as randchoice
from random import choice as rndchoice
from random import shuffle
from .utils.dataIO import fileIO
from .utils import checks
from bs4 import BeautifulSoup
class Runescapecompare:
"""Runescape-relate commands"""
def __init__(self, bot):
self.bot = bot
"""
imLink = http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=
nmLink = http://services.runescape.com/m=hiscore/index_lite.ws?player=
"""
@commands.group(name="compare", pass_context=True)
async def _compare(self, ctx):
if ctx.invoked_subcommand is None:
await self.bot.say("Please, choose a skill to compare!")
#####Overall#####
@_compare.command(name="overall", pass_context=True)
async def compare_overall(self, ctx, name1 : str, name2 : str):
address1 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name1
address2 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name2
try:
website1 = urllib.request.urlopen(address1)
website2 = urllib.request.urlopen(address2)
website_html1 = website1.read().decode(website1.headers.get_content_charset())
website_html2 = website2.read().decode(website2.headers.get_content_charset())
stats1 = website_html1.split("\n")
stats2 = website_html2.split("\n")
stat1 = stats1[0].split(",")
stat2= stats2[0].split(",")
if stat1[2] > stat2[2]:
<|fim_middle|>
if stat2[2] > stat1[2]:
comparerank = stat2[0] - stat1[0]
comparelvl = stat2[1] - stat1[1]
comparexp = stat2[2] - stat1[2]
await self.bot.say("```" + name2 + "'s ranking is " + str(comparerank) + " ranks higher than " + name1 + "'s rank.\n" + name2 + "'s level is " + str(comparelvl) + " levels higher than " + name1 + "'s.\n" + name2 + "'s total experience is " + str(comparexp) + " higher than " + name1 + "'s.```")
except:
await self.bot.say("Sorry... Something went wrong there. Did you type the name correctly?")
def setup(bot):
n = Runescapecompare(bot)
bot.add_cog(n)
<|fim▁end|> | comparerank = int(stat2[0]) - int(stat1[0])
comparelvl = int(stat1[1]) - int(stat2[1])
comparexp = int(stat1[2]) - int(stat2[2])
await self.bot.say("```" + name1 + "'s ranking is " + str(comparerank) + " ranks higher than " + name2 + "'s rank.\n" + name1 + "'s level is " + str(comparelvl) + " levels higher than " + name2 + "'s.\n" + name1 + "'s total experience is " + str(comparexp) + " higher than " + name2 + "'s.```") |
<|file_name|>runescapecompare.py<|end_file_name|><|fim▁begin|>import discord
import asyncio
import datetime
import time
import aiohttp
import threading
import glob
import re
import json
import os
import urllib.request
from discord.ext import commands
from random import randint
from random import choice as randchoice
from random import choice as rndchoice
from random import shuffle
from .utils.dataIO import fileIO
from .utils import checks
from bs4 import BeautifulSoup
class Runescapecompare:
"""Runescape-relate commands"""
def __init__(self, bot):
self.bot = bot
"""
imLink = http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=
nmLink = http://services.runescape.com/m=hiscore/index_lite.ws?player=
"""
@commands.group(name="compare", pass_context=True)
async def _compare(self, ctx):
if ctx.invoked_subcommand is None:
await self.bot.say("Please, choose a skill to compare!")
#####Overall#####
@_compare.command(name="overall", pass_context=True)
async def compare_overall(self, ctx, name1 : str, name2 : str):
address1 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name1
address2 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name2
try:
website1 = urllib.request.urlopen(address1)
website2 = urllib.request.urlopen(address2)
website_html1 = website1.read().decode(website1.headers.get_content_charset())
website_html2 = website2.read().decode(website2.headers.get_content_charset())
stats1 = website_html1.split("\n")
stats2 = website_html2.split("\n")
stat1 = stats1[0].split(",")
stat2= stats2[0].split(",")
if stat1[2] > stat2[2]:
comparerank = int(stat2[0]) - int(stat1[0])
comparelvl = int(stat1[1]) - int(stat2[1])
comparexp = int(stat1[2]) - int(stat2[2])
await self.bot.say("```" + name1 + "'s ranking is " + str(comparerank) + " ranks higher than " + name2 + "'s rank.\n" + name1 + "'s level is " + str(comparelvl) + " levels higher than " + name2 + "'s.\n" + name1 + "'s total experience is " + str(comparexp) + " higher than " + name2 + "'s.```")
if stat2[2] > stat1[2]:
<|fim_middle|>
except:
await self.bot.say("Sorry... Something went wrong there. Did you type the name correctly?")
def setup(bot):
n = Runescapecompare(bot)
bot.add_cog(n)
<|fim▁end|> | comparerank = stat2[0] - stat1[0]
comparelvl = stat2[1] - stat1[1]
comparexp = stat2[2] - stat1[2]
await self.bot.say("```" + name2 + "'s ranking is " + str(comparerank) + " ranks higher than " + name1 + "'s rank.\n" + name2 + "'s level is " + str(comparelvl) + " levels higher than " + name1 + "'s.\n" + name2 + "'s total experience is " + str(comparexp) + " higher than " + name1 + "'s.```") |
<|file_name|>runescapecompare.py<|end_file_name|><|fim▁begin|>import discord
import asyncio
import datetime
import time
import aiohttp
import threading
import glob
import re
import json
import os
import urllib.request
from discord.ext import commands
from random import randint
from random import choice as randchoice
from random import choice as rndchoice
from random import shuffle
from .utils.dataIO import fileIO
from .utils import checks
from bs4 import BeautifulSoup
class Runescapecompare:
"""Runescape-relate commands"""
def <|fim_middle|>(self, bot):
self.bot = bot
"""
imLink = http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=
nmLink = http://services.runescape.com/m=hiscore/index_lite.ws?player=
"""
@commands.group(name="compare", pass_context=True)
async def _compare(self, ctx):
if ctx.invoked_subcommand is None:
await self.bot.say("Please, choose a skill to compare!")
#####Overall#####
@_compare.command(name="overall", pass_context=True)
async def compare_overall(self, ctx, name1 : str, name2 : str):
address1 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name1
address2 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name2
try:
website1 = urllib.request.urlopen(address1)
website2 = urllib.request.urlopen(address2)
website_html1 = website1.read().decode(website1.headers.get_content_charset())
website_html2 = website2.read().decode(website2.headers.get_content_charset())
stats1 = website_html1.split("\n")
stats2 = website_html2.split("\n")
stat1 = stats1[0].split(",")
stat2= stats2[0].split(",")
if stat1[2] > stat2[2]:
comparerank = int(stat2[0]) - int(stat1[0])
comparelvl = int(stat1[1]) - int(stat2[1])
comparexp = int(stat1[2]) - int(stat2[2])
await self.bot.say("```" + name1 + "'s ranking is " + str(comparerank) + " ranks higher than " + name2 + "'s rank.\n" + name1 + "'s level is " + str(comparelvl) + " levels higher than " + name2 + "'s.\n" + name1 + "'s total experience is " + str(comparexp) + " higher than " + name2 + "'s.```")
if stat2[2] > stat1[2]:
comparerank = stat2[0] - stat1[0]
comparelvl = stat2[1] - stat1[1]
comparexp = stat2[2] - stat1[2]
await self.bot.say("```" + name2 + "'s ranking is " + str(comparerank) + " ranks higher than " + name1 + "'s rank.\n" + name2 + "'s level is " + str(comparelvl) + " levels higher than " + name1 + "'s.\n" + name2 + "'s total experience is " + str(comparexp) + " higher than " + name1 + "'s.```")
except:
await self.bot.say("Sorry... Something went wrong there. Did you type the name correctly?")
def setup(bot):
n = Runescapecompare(bot)
bot.add_cog(n)
<|fim▁end|> | __init__ |
<|file_name|>runescapecompare.py<|end_file_name|><|fim▁begin|>import discord
import asyncio
import datetime
import time
import aiohttp
import threading
import glob
import re
import json
import os
import urllib.request
from discord.ext import commands
from random import randint
from random import choice as randchoice
from random import choice as rndchoice
from random import shuffle
from .utils.dataIO import fileIO
from .utils import checks
from bs4 import BeautifulSoup
class Runescapecompare:
"""Runescape-relate commands"""
def __init__(self, bot):
self.bot = bot
"""
imLink = http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=
nmLink = http://services.runescape.com/m=hiscore/index_lite.ws?player=
"""
@commands.group(name="compare", pass_context=True)
async def <|fim_middle|>(self, ctx):
if ctx.invoked_subcommand is None:
await self.bot.say("Please, choose a skill to compare!")
#####Overall#####
@_compare.command(name="overall", pass_context=True)
async def compare_overall(self, ctx, name1 : str, name2 : str):
address1 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name1
address2 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name2
try:
website1 = urllib.request.urlopen(address1)
website2 = urllib.request.urlopen(address2)
website_html1 = website1.read().decode(website1.headers.get_content_charset())
website_html2 = website2.read().decode(website2.headers.get_content_charset())
stats1 = website_html1.split("\n")
stats2 = website_html2.split("\n")
stat1 = stats1[0].split(",")
stat2= stats2[0].split(",")
if stat1[2] > stat2[2]:
comparerank = int(stat2[0]) - int(stat1[0])
comparelvl = int(stat1[1]) - int(stat2[1])
comparexp = int(stat1[2]) - int(stat2[2])
await self.bot.say("```" + name1 + "'s ranking is " + str(comparerank) + " ranks higher than " + name2 + "'s rank.\n" + name1 + "'s level is " + str(comparelvl) + " levels higher than " + name2 + "'s.\n" + name1 + "'s total experience is " + str(comparexp) + " higher than " + name2 + "'s.```")
if stat2[2] > stat1[2]:
comparerank = stat2[0] - stat1[0]
comparelvl = stat2[1] - stat1[1]
comparexp = stat2[2] - stat1[2]
await self.bot.say("```" + name2 + "'s ranking is " + str(comparerank) + " ranks higher than " + name1 + "'s rank.\n" + name2 + "'s level is " + str(comparelvl) + " levels higher than " + name1 + "'s.\n" + name2 + "'s total experience is " + str(comparexp) + " higher than " + name1 + "'s.```")
except:
await self.bot.say("Sorry... Something went wrong there. Did you type the name correctly?")
def setup(bot):
n = Runescapecompare(bot)
bot.add_cog(n)
<|fim▁end|> | _compare |
<|file_name|>runescapecompare.py<|end_file_name|><|fim▁begin|>import discord
import asyncio
import datetime
import time
import aiohttp
import threading
import glob
import re
import json
import os
import urllib.request
from discord.ext import commands
from random import randint
from random import choice as randchoice
from random import choice as rndchoice
from random import shuffle
from .utils.dataIO import fileIO
from .utils import checks
from bs4 import BeautifulSoup
class Runescapecompare:
"""Runescape-relate commands"""
def __init__(self, bot):
self.bot = bot
"""
imLink = http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=
nmLink = http://services.runescape.com/m=hiscore/index_lite.ws?player=
"""
@commands.group(name="compare", pass_context=True)
async def _compare(self, ctx):
if ctx.invoked_subcommand is None:
await self.bot.say("Please, choose a skill to compare!")
#####Overall#####
@_compare.command(name="overall", pass_context=True)
async def <|fim_middle|>(self, ctx, name1 : str, name2 : str):
address1 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name1
address2 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name2
try:
website1 = urllib.request.urlopen(address1)
website2 = urllib.request.urlopen(address2)
website_html1 = website1.read().decode(website1.headers.get_content_charset())
website_html2 = website2.read().decode(website2.headers.get_content_charset())
stats1 = website_html1.split("\n")
stats2 = website_html2.split("\n")
stat1 = stats1[0].split(",")
stat2= stats2[0].split(",")
if stat1[2] > stat2[2]:
comparerank = int(stat2[0]) - int(stat1[0])
comparelvl = int(stat1[1]) - int(stat2[1])
comparexp = int(stat1[2]) - int(stat2[2])
await self.bot.say("```" + name1 + "'s ranking is " + str(comparerank) + " ranks higher than " + name2 + "'s rank.\n" + name1 + "'s level is " + str(comparelvl) + " levels higher than " + name2 + "'s.\n" + name1 + "'s total experience is " + str(comparexp) + " higher than " + name2 + "'s.```")
if stat2[2] > stat1[2]:
comparerank = stat2[0] - stat1[0]
comparelvl = stat2[1] - stat1[1]
comparexp = stat2[2] - stat1[2]
await self.bot.say("```" + name2 + "'s ranking is " + str(comparerank) + " ranks higher than " + name1 + "'s rank.\n" + name2 + "'s level is " + str(comparelvl) + " levels higher than " + name1 + "'s.\n" + name2 + "'s total experience is " + str(comparexp) + " higher than " + name1 + "'s.```")
except:
await self.bot.say("Sorry... Something went wrong there. Did you type the name correctly?")
def setup(bot):
n = Runescapecompare(bot)
bot.add_cog(n)
<|fim▁end|> | compare_overall |
<|file_name|>runescapecompare.py<|end_file_name|><|fim▁begin|>import discord
import asyncio
import datetime
import time
import aiohttp
import threading
import glob
import re
import json
import os
import urllib.request
from discord.ext import commands
from random import randint
from random import choice as randchoice
from random import choice as rndchoice
from random import shuffle
from .utils.dataIO import fileIO
from .utils import checks
from bs4 import BeautifulSoup
class Runescapecompare:
"""Runescape-relate commands"""
def __init__(self, bot):
self.bot = bot
"""
imLink = http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=
nmLink = http://services.runescape.com/m=hiscore/index_lite.ws?player=
"""
@commands.group(name="compare", pass_context=True)
async def _compare(self, ctx):
if ctx.invoked_subcommand is None:
await self.bot.say("Please, choose a skill to compare!")
#####Overall#####
@_compare.command(name="overall", pass_context=True)
async def compare_overall(self, ctx, name1 : str, name2 : str):
address1 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name1
address2 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name2
try:
website1 = urllib.request.urlopen(address1)
website2 = urllib.request.urlopen(address2)
website_html1 = website1.read().decode(website1.headers.get_content_charset())
website_html2 = website2.read().decode(website2.headers.get_content_charset())
stats1 = website_html1.split("\n")
stats2 = website_html2.split("\n")
stat1 = stats1[0].split(",")
stat2= stats2[0].split(",")
if stat1[2] > stat2[2]:
comparerank = int(stat2[0]) - int(stat1[0])
comparelvl = int(stat1[1]) - int(stat2[1])
comparexp = int(stat1[2]) - int(stat2[2])
await self.bot.say("```" + name1 + "'s ranking is " + str(comparerank) + " ranks higher than " + name2 + "'s rank.\n" + name1 + "'s level is " + str(comparelvl) + " levels higher than " + name2 + "'s.\n" + name1 + "'s total experience is " + str(comparexp) + " higher than " + name2 + "'s.```")
if stat2[2] > stat1[2]:
comparerank = stat2[0] - stat1[0]
comparelvl = stat2[1] - stat1[1]
comparexp = stat2[2] - stat1[2]
await self.bot.say("```" + name2 + "'s ranking is " + str(comparerank) + " ranks higher than " + name1 + "'s rank.\n" + name2 + "'s level is " + str(comparelvl) + " levels higher than " + name1 + "'s.\n" + name2 + "'s total experience is " + str(comparexp) + " higher than " + name1 + "'s.```")
except:
await self.bot.say("Sorry... Something went wrong there. Did you type the name correctly?")
def <|fim_middle|>(bot):
n = Runescapecompare(bot)
bot.add_cog(n)
<|fim▁end|> | setup |
<|file_name|>injection_rwx.py<|end_file_name|><|fim▁begin|># Copyright (C) 2014 Optiv, Inc. ([email protected])
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
from lib.cuckoo.common.abstracts import Signature
class InjectionRWX(Signature):
name = "injection_rwx"
description = "Creates RWX memory"
severity = 2
confidence = 50
categories = ["injection"]
authors = ["Optiv"]
minimum = "1.2"
evented = True
def __init__(self, *args, **kwargs):
Signature.__init__(self, *args, **kwargs)
<|fim▁hole|> if call["api"] == "NtAllocateVirtualMemory" or call["api"] == "VirtualProtectEx":
protection = self.get_argument(call, "Protection")
# PAGE_EXECUTE_READWRITE
if protection == "0x00000040":
return True
elif call["api"] == "NtProtectVirtualMemory":
protection = self.get_argument(call, "NewAccessProtection")
# PAGE_EXECUTE_READWRITE
if protection == "0x00000040":
return True<|fim▁end|> | filter_apinames = set(["NtAllocateVirtualMemory","NtProtectVirtualMemory","VirtualProtectEx"])
filter_analysistypes = set(["file"])
def on_call(self, call, process): |
<|file_name|>injection_rwx.py<|end_file_name|><|fim▁begin|># Copyright (C) 2014 Optiv, Inc. ([email protected])
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
from lib.cuckoo.common.abstracts import Signature
class InjectionRWX(Signature):
<|fim_middle|>
<|fim▁end|> | name = "injection_rwx"
description = "Creates RWX memory"
severity = 2
confidence = 50
categories = ["injection"]
authors = ["Optiv"]
minimum = "1.2"
evented = True
def __init__(self, *args, **kwargs):
Signature.__init__(self, *args, **kwargs)
filter_apinames = set(["NtAllocateVirtualMemory","NtProtectVirtualMemory","VirtualProtectEx"])
filter_analysistypes = set(["file"])
def on_call(self, call, process):
if call["api"] == "NtAllocateVirtualMemory" or call["api"] == "VirtualProtectEx":
protection = self.get_argument(call, "Protection")
# PAGE_EXECUTE_READWRITE
if protection == "0x00000040":
return True
elif call["api"] == "NtProtectVirtualMemory":
protection = self.get_argument(call, "NewAccessProtection")
# PAGE_EXECUTE_READWRITE
if protection == "0x00000040":
return True |
<|file_name|>injection_rwx.py<|end_file_name|><|fim▁begin|># Copyright (C) 2014 Optiv, Inc. ([email protected])
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
from lib.cuckoo.common.abstracts import Signature
class InjectionRWX(Signature):
name = "injection_rwx"
description = "Creates RWX memory"
severity = 2
confidence = 50
categories = ["injection"]
authors = ["Optiv"]
minimum = "1.2"
evented = True
def __init__(self, *args, **kwargs):
<|fim_middle|>
filter_apinames = set(["NtAllocateVirtualMemory","NtProtectVirtualMemory","VirtualProtectEx"])
filter_analysistypes = set(["file"])
def on_call(self, call, process):
if call["api"] == "NtAllocateVirtualMemory" or call["api"] == "VirtualProtectEx":
protection = self.get_argument(call, "Protection")
# PAGE_EXECUTE_READWRITE
if protection == "0x00000040":
return True
elif call["api"] == "NtProtectVirtualMemory":
protection = self.get_argument(call, "NewAccessProtection")
# PAGE_EXECUTE_READWRITE
if protection == "0x00000040":
return True
<|fim▁end|> | Signature.__init__(self, *args, **kwargs) |
<|file_name|>injection_rwx.py<|end_file_name|><|fim▁begin|># Copyright (C) 2014 Optiv, Inc. ([email protected])
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
from lib.cuckoo.common.abstracts import Signature
class InjectionRWX(Signature):
name = "injection_rwx"
description = "Creates RWX memory"
severity = 2
confidence = 50
categories = ["injection"]
authors = ["Optiv"]
minimum = "1.2"
evented = True
def __init__(self, *args, **kwargs):
Signature.__init__(self, *args, **kwargs)
filter_apinames = set(["NtAllocateVirtualMemory","NtProtectVirtualMemory","VirtualProtectEx"])
filter_analysistypes = set(["file"])
def on_call(self, call, process):
<|fim_middle|>
<|fim▁end|> | if call["api"] == "NtAllocateVirtualMemory" or call["api"] == "VirtualProtectEx":
protection = self.get_argument(call, "Protection")
# PAGE_EXECUTE_READWRITE
if protection == "0x00000040":
return True
elif call["api"] == "NtProtectVirtualMemory":
protection = self.get_argument(call, "NewAccessProtection")
# PAGE_EXECUTE_READWRITE
if protection == "0x00000040":
return True |
<|file_name|>injection_rwx.py<|end_file_name|><|fim▁begin|># Copyright (C) 2014 Optiv, Inc. ([email protected])
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
from lib.cuckoo.common.abstracts import Signature
class InjectionRWX(Signature):
name = "injection_rwx"
description = "Creates RWX memory"
severity = 2
confidence = 50
categories = ["injection"]
authors = ["Optiv"]
minimum = "1.2"
evented = True
def __init__(self, *args, **kwargs):
Signature.__init__(self, *args, **kwargs)
filter_apinames = set(["NtAllocateVirtualMemory","NtProtectVirtualMemory","VirtualProtectEx"])
filter_analysistypes = set(["file"])
def on_call(self, call, process):
if call["api"] == "NtAllocateVirtualMemory" or call["api"] == "VirtualProtectEx":
<|fim_middle|>
elif call["api"] == "NtProtectVirtualMemory":
protection = self.get_argument(call, "NewAccessProtection")
# PAGE_EXECUTE_READWRITE
if protection == "0x00000040":
return True
<|fim▁end|> | protection = self.get_argument(call, "Protection")
# PAGE_EXECUTE_READWRITE
if protection == "0x00000040":
return True |
<|file_name|>injection_rwx.py<|end_file_name|><|fim▁begin|># Copyright (C) 2014 Optiv, Inc. ([email protected])
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
from lib.cuckoo.common.abstracts import Signature
class InjectionRWX(Signature):
name = "injection_rwx"
description = "Creates RWX memory"
severity = 2
confidence = 50
categories = ["injection"]
authors = ["Optiv"]
minimum = "1.2"
evented = True
def __init__(self, *args, **kwargs):
Signature.__init__(self, *args, **kwargs)
filter_apinames = set(["NtAllocateVirtualMemory","NtProtectVirtualMemory","VirtualProtectEx"])
filter_analysistypes = set(["file"])
def on_call(self, call, process):
if call["api"] == "NtAllocateVirtualMemory" or call["api"] == "VirtualProtectEx":
protection = self.get_argument(call, "Protection")
# PAGE_EXECUTE_READWRITE
if protection == "0x00000040":
<|fim_middle|>
elif call["api"] == "NtProtectVirtualMemory":
protection = self.get_argument(call, "NewAccessProtection")
# PAGE_EXECUTE_READWRITE
if protection == "0x00000040":
return True
<|fim▁end|> | return True |
<|file_name|>injection_rwx.py<|end_file_name|><|fim▁begin|># Copyright (C) 2014 Optiv, Inc. ([email protected])
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
from lib.cuckoo.common.abstracts import Signature
class InjectionRWX(Signature):
name = "injection_rwx"
description = "Creates RWX memory"
severity = 2
confidence = 50
categories = ["injection"]
authors = ["Optiv"]
minimum = "1.2"
evented = True
def __init__(self, *args, **kwargs):
Signature.__init__(self, *args, **kwargs)
filter_apinames = set(["NtAllocateVirtualMemory","NtProtectVirtualMemory","VirtualProtectEx"])
filter_analysistypes = set(["file"])
def on_call(self, call, process):
if call["api"] == "NtAllocateVirtualMemory" or call["api"] == "VirtualProtectEx":
protection = self.get_argument(call, "Protection")
# PAGE_EXECUTE_READWRITE
if protection == "0x00000040":
return True
elif call["api"] == "NtProtectVirtualMemory":
<|fim_middle|>
<|fim▁end|> | protection = self.get_argument(call, "NewAccessProtection")
# PAGE_EXECUTE_READWRITE
if protection == "0x00000040":
return True |
<|file_name|>injection_rwx.py<|end_file_name|><|fim▁begin|># Copyright (C) 2014 Optiv, Inc. ([email protected])
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
from lib.cuckoo.common.abstracts import Signature
class InjectionRWX(Signature):
name = "injection_rwx"
description = "Creates RWX memory"
severity = 2
confidence = 50
categories = ["injection"]
authors = ["Optiv"]
minimum = "1.2"
evented = True
def __init__(self, *args, **kwargs):
Signature.__init__(self, *args, **kwargs)
filter_apinames = set(["NtAllocateVirtualMemory","NtProtectVirtualMemory","VirtualProtectEx"])
filter_analysistypes = set(["file"])
def on_call(self, call, process):
if call["api"] == "NtAllocateVirtualMemory" or call["api"] == "VirtualProtectEx":
protection = self.get_argument(call, "Protection")
# PAGE_EXECUTE_READWRITE
if protection == "0x00000040":
return True
elif call["api"] == "NtProtectVirtualMemory":
protection = self.get_argument(call, "NewAccessProtection")
# PAGE_EXECUTE_READWRITE
if protection == "0x00000040":
<|fim_middle|>
<|fim▁end|> | return True |
<|file_name|>injection_rwx.py<|end_file_name|><|fim▁begin|># Copyright (C) 2014 Optiv, Inc. ([email protected])
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
from lib.cuckoo.common.abstracts import Signature
class InjectionRWX(Signature):
name = "injection_rwx"
description = "Creates RWX memory"
severity = 2
confidence = 50
categories = ["injection"]
authors = ["Optiv"]
minimum = "1.2"
evented = True
def <|fim_middle|>(self, *args, **kwargs):
Signature.__init__(self, *args, **kwargs)
filter_apinames = set(["NtAllocateVirtualMemory","NtProtectVirtualMemory","VirtualProtectEx"])
filter_analysistypes = set(["file"])
def on_call(self, call, process):
if call["api"] == "NtAllocateVirtualMemory" or call["api"] == "VirtualProtectEx":
protection = self.get_argument(call, "Protection")
# PAGE_EXECUTE_READWRITE
if protection == "0x00000040":
return True
elif call["api"] == "NtProtectVirtualMemory":
protection = self.get_argument(call, "NewAccessProtection")
# PAGE_EXECUTE_READWRITE
if protection == "0x00000040":
return True
<|fim▁end|> | __init__ |
<|file_name|>injection_rwx.py<|end_file_name|><|fim▁begin|># Copyright (C) 2014 Optiv, Inc. ([email protected])
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
from lib.cuckoo.common.abstracts import Signature
class InjectionRWX(Signature):
name = "injection_rwx"
description = "Creates RWX memory"
severity = 2
confidence = 50
categories = ["injection"]
authors = ["Optiv"]
minimum = "1.2"
evented = True
def __init__(self, *args, **kwargs):
Signature.__init__(self, *args, **kwargs)
filter_apinames = set(["NtAllocateVirtualMemory","NtProtectVirtualMemory","VirtualProtectEx"])
filter_analysistypes = set(["file"])
def <|fim_middle|>(self, call, process):
if call["api"] == "NtAllocateVirtualMemory" or call["api"] == "VirtualProtectEx":
protection = self.get_argument(call, "Protection")
# PAGE_EXECUTE_READWRITE
if protection == "0x00000040":
return True
elif call["api"] == "NtProtectVirtualMemory":
protection = self.get_argument(call, "NewAccessProtection")
# PAGE_EXECUTE_READWRITE
if protection == "0x00000040":
return True
<|fim▁end|> | on_call |
<|file_name|>logger.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
import time
import string
import json
import config
import helper
import busses
def log_message(msg):
#log format: time type message
time_str = str(time.time())
line = time_str[:time_str.find(".")]
line = line.rjust(10, str(" "))
line += " "
busses.status_bus["latest_messages"][msg.chat_id] = msg
msg_type = helper.get_message_type(msg)
if msg_type == "text" and msg.text.startswith("/"):
msg_type = "command"
appendix = "ERROR"
if msg_type == "text":
appendix = msg.text
elif msg_type == "command":
appendix = msg.text[1:]
elif msg_type == "location":
location_data = msg.location.to_dict()
appendix = str(location_data["latitude"]) + "°, " + str(location_data["longitude"]) + "°"
elif msg_type == "contact":
appendix = str(msg.contact.user_id) + " " + msg.contact.first_name + " " + msg.contact.last_name
elif msg_type == "new_user":
appendix = str(msg.new_chat_member.id) + " " + str(msg.new_chat_member.first_name) + " " + str(msg.new_chat_member.last_name)
elif msg_type in ["audio", "document", "game", "photo", "sticker", "video", "voice", "video_note", "unknown"]:<|fim▁hole|> msg_type = msg_type.rjust(10, str(" "))
appendix = appendix.replace("\n", "\\n").rjust(40, str(" "))
line += msg_type + " " + appendix + " "
line += str(msg.chat_id) + "," + str(msg.message_id)
line += "\n"
with open(config.msg_log_file_path, "a") as log_file:
log_file.write(line.encode("utf-8"))
def complete_log(update):
with open(config.complete_log_file_path, "a") as log_file:
data = update.to_dict()
data.update({"time": time.time()})
json_data = json.dumps(data)
log_file.write(str(json_data).replace("\n", "\\n") + "\n".encode("utf-8"))<|fim▁end|> | appendix = ""
|
<|file_name|>logger.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
import time
import string
import json
import config
import helper
import busses
def log_message(msg):
#log format: time type message
<|fim_middle|>
def complete_log(update):
with open(config.complete_log_file_path, "a") as log_file:
data = update.to_dict()
data.update({"time": time.time()})
json_data = json.dumps(data)
log_file.write(str(json_data).replace("\n", "\\n") + "\n".encode("utf-8"))
<|fim▁end|> | time_str = str(time.time())
line = time_str[:time_str.find(".")]
line = line.rjust(10, str(" "))
line += " "
busses.status_bus["latest_messages"][msg.chat_id] = msg
msg_type = helper.get_message_type(msg)
if msg_type == "text" and msg.text.startswith("/"):
msg_type = "command"
appendix = "ERROR"
if msg_type == "text":
appendix = msg.text
elif msg_type == "command":
appendix = msg.text[1:]
elif msg_type == "location":
location_data = msg.location.to_dict()
appendix = str(location_data["latitude"]) + "°, " + str(location_data["longitude"]) + "°"
elif msg_type == "contact":
appendix = str(msg.contact.user_id) + " " + msg.contact.first_name + " " + msg.contact.last_name
elif msg_type == "new_user":
appendix = str(msg.new_chat_member.id) + " " + str(msg.new_chat_member.first_name) + " " + str(msg.new_chat_member.last_name)
elif msg_type in ["audio", "document", "game", "photo", "sticker", "video", "voice", "video_note", "unknown"]:
appendix = ""
msg_type = msg_type.rjust(10, str(" "))
appendix = appendix.replace("\n", "\\n").rjust(40, str(" "))
line += msg_type + " " + appendix + " "
line += str(msg.chat_id) + "," + str(msg.message_id)
line += "\n"
with open(config.msg_log_file_path, "a") as log_file:
log_file.write(line.encode("utf-8"))
|
<|file_name|>logger.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
import time
import string
import json
import config
import helper
import busses
def log_message(msg):
#log format: time type message
time_str = str(time.time())
line = time_str[:time_str.find(".")]
line = line.rjust(10, str(" "))
line += " "
busses.status_bus["latest_messages"][msg.chat_id] = msg
msg_type = helper.get_message_type(msg)
if msg_type == "text" and msg.text.startswith("/"):
msg_type = "command"
appendix = "ERROR"
if msg_type == "text":
appendix = msg.text
elif msg_type == "command":
appendix = msg.text[1:]
elif msg_type == "location":
location_data = msg.location.to_dict()
appendix = str(location_data["latitude"]) + "°, " + str(location_data["longitude"]) + "°"
elif msg_type == "contact":
appendix = str(msg.contact.user_id) + " " + msg.contact.first_name + " " + msg.contact.last_name
elif msg_type == "new_user":
appendix = str(msg.new_chat_member.id) + " " + str(msg.new_chat_member.first_name) + " " + str(msg.new_chat_member.last_name)
elif msg_type in ["audio", "document", "game", "photo", "sticker", "video", "voice", "video_note", "unknown"]:
appendix = ""
msg_type = msg_type.rjust(10, str(" "))
appendix = appendix.replace("\n", "\\n").rjust(40, str(" "))
line += msg_type + " " + appendix + " "
line += str(msg.chat_id) + "," + str(msg.message_id)
line += "\n"
with open(config.msg_log_file_path, "a") as log_file:
log_file.write(line.encode("utf-8"))
def complete_log(update):
wi<|fim_middle|>
<|fim▁end|> | th open(config.complete_log_file_path, "a") as log_file:
data = update.to_dict()
data.update({"time": time.time()})
json_data = json.dumps(data)
log_file.write(str(json_data).replace("\n", "\\n") + "\n".encode("utf-8"))
|
<|file_name|>logger.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
import time
import string
import json
import config
import helper
import busses
def log_message(msg):
#log format: time type message
time_str = str(time.time())
line = time_str[:time_str.find(".")]
line = line.rjust(10, str(" "))
line += " "
busses.status_bus["latest_messages"][msg.chat_id] = msg
msg_type = helper.get_message_type(msg)
if msg_type == "text" and msg.text.startswith("/"):
<|fim_middle|>
appendix = "ERROR"
if msg_type == "text":
appendix = msg.text
elif msg_type == "command":
appendix = msg.text[1:]
elif msg_type == "location":
location_data = msg.location.to_dict()
appendix = str(location_data["latitude"]) + "°, " + str(location_data["longitude"]) + "°"
elif msg_type == "contact":
appendix = str(msg.contact.user_id) + " " + msg.contact.first_name + " " + msg.contact.last_name
elif msg_type == "new_user":
appendix = str(msg.new_chat_member.id) + " " + str(msg.new_chat_member.first_name) + " " + str(msg.new_chat_member.last_name)
elif msg_type in ["audio", "document", "game", "photo", "sticker", "video", "voice", "video_note", "unknown"]:
appendix = ""
msg_type = msg_type.rjust(10, str(" "))
appendix = appendix.replace("\n", "\\n").rjust(40, str(" "))
line += msg_type + " " + appendix + " "
line += str(msg.chat_id) + "," + str(msg.message_id)
line += "\n"
with open(config.msg_log_file_path, "a") as log_file:
log_file.write(line.encode("utf-8"))
def complete_log(update):
with open(config.complete_log_file_path, "a") as log_file:
data = update.to_dict()
data.update({"time": time.time()})
json_data = json.dumps(data)
log_file.write(str(json_data).replace("\n", "\\n") + "\n".encode("utf-8"))
<|fim▁end|> | msg_type = "command" |
<|file_name|>logger.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
import time
import string
import json
import config
import helper
import busses
def log_message(msg):
#log format: time type message
time_str = str(time.time())
line = time_str[:time_str.find(".")]
line = line.rjust(10, str(" "))
line += " "
busses.status_bus["latest_messages"][msg.chat_id] = msg
msg_type = helper.get_message_type(msg)
if msg_type == "text" and msg.text.startswith("/"):
msg_type = "command"
appendix = "ERROR"
if msg_type == "text":
<|fim_middle|>
elif msg_type == "command":
appendix = msg.text[1:]
elif msg_type == "location":
location_data = msg.location.to_dict()
appendix = str(location_data["latitude"]) + "°, " + str(location_data["longitude"]) + "°"
elif msg_type == "contact":
appendix = str(msg.contact.user_id) + " " + msg.contact.first_name + " " + msg.contact.last_name
elif msg_type == "new_user":
appendix = str(msg.new_chat_member.id) + " " + str(msg.new_chat_member.first_name) + " " + str(msg.new_chat_member.last_name)
elif msg_type in ["audio", "document", "game", "photo", "sticker", "video", "voice", "video_note", "unknown"]:
appendix = ""
msg_type = msg_type.rjust(10, str(" "))
appendix = appendix.replace("\n", "\\n").rjust(40, str(" "))
line += msg_type + " " + appendix + " "
line += str(msg.chat_id) + "," + str(msg.message_id)
line += "\n"
with open(config.msg_log_file_path, "a") as log_file:
log_file.write(line.encode("utf-8"))
def complete_log(update):
with open(config.complete_log_file_path, "a") as log_file:
data = update.to_dict()
data.update({"time": time.time()})
json_data = json.dumps(data)
log_file.write(str(json_data).replace("\n", "\\n") + "\n".encode("utf-8"))
<|fim▁end|> | appendix = msg.text |
<|file_name|>logger.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
import time
import string
import json
import config
import helper
import busses
def log_message(msg):
#log format: time type message
time_str = str(time.time())
line = time_str[:time_str.find(".")]
line = line.rjust(10, str(" "))
line += " "
busses.status_bus["latest_messages"][msg.chat_id] = msg
msg_type = helper.get_message_type(msg)
if msg_type == "text" and msg.text.startswith("/"):
msg_type = "command"
appendix = "ERROR"
if msg_type == "text":
appendix = msg.text
elif msg_type == "command":
<|fim_middle|>
elif msg_type == "location":
location_data = msg.location.to_dict()
appendix = str(location_data["latitude"]) + "°, " + str(location_data["longitude"]) + "°"
elif msg_type == "contact":
appendix = str(msg.contact.user_id) + " " + msg.contact.first_name + " " + msg.contact.last_name
elif msg_type == "new_user":
appendix = str(msg.new_chat_member.id) + " " + str(msg.new_chat_member.first_name) + " " + str(msg.new_chat_member.last_name)
elif msg_type in ["audio", "document", "game", "photo", "sticker", "video", "voice", "video_note", "unknown"]:
appendix = ""
msg_type = msg_type.rjust(10, str(" "))
appendix = appendix.replace("\n", "\\n").rjust(40, str(" "))
line += msg_type + " " + appendix + " "
line += str(msg.chat_id) + "," + str(msg.message_id)
line += "\n"
with open(config.msg_log_file_path, "a") as log_file:
log_file.write(line.encode("utf-8"))
def complete_log(update):
with open(config.complete_log_file_path, "a") as log_file:
data = update.to_dict()
data.update({"time": time.time()})
json_data = json.dumps(data)
log_file.write(str(json_data).replace("\n", "\\n") + "\n".encode("utf-8"))
<|fim▁end|> | appendix = msg.text[1:] |
<|file_name|>logger.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
import time
import string
import json
import config
import helper
import busses
def log_message(msg):
#log format: time type message
time_str = str(time.time())
line = time_str[:time_str.find(".")]
line = line.rjust(10, str(" "))
line += " "
busses.status_bus["latest_messages"][msg.chat_id] = msg
msg_type = helper.get_message_type(msg)
if msg_type == "text" and msg.text.startswith("/"):
msg_type = "command"
appendix = "ERROR"
if msg_type == "text":
appendix = msg.text
elif msg_type == "command":
appendix = msg.text[1:]
elif msg_type == "location":
<|fim_middle|>
elif msg_type == "contact":
appendix = str(msg.contact.user_id) + " " + msg.contact.first_name + " " + msg.contact.last_name
elif msg_type == "new_user":
appendix = str(msg.new_chat_member.id) + " " + str(msg.new_chat_member.first_name) + " " + str(msg.new_chat_member.last_name)
elif msg_type in ["audio", "document", "game", "photo", "sticker", "video", "voice", "video_note", "unknown"]:
appendix = ""
msg_type = msg_type.rjust(10, str(" "))
appendix = appendix.replace("\n", "\\n").rjust(40, str(" "))
line += msg_type + " " + appendix + " "
line += str(msg.chat_id) + "," + str(msg.message_id)
line += "\n"
with open(config.msg_log_file_path, "a") as log_file:
log_file.write(line.encode("utf-8"))
def complete_log(update):
with open(config.complete_log_file_path, "a") as log_file:
data = update.to_dict()
data.update({"time": time.time()})
json_data = json.dumps(data)
log_file.write(str(json_data).replace("\n", "\\n") + "\n".encode("utf-8"))
<|fim▁end|> | location_data = msg.location.to_dict()
appendix = str(location_data["latitude"]) + "°, " + str(location_data["longitude"]) + "°"
|
<|file_name|>logger.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
import time
import string
import json
import config
import helper
import busses
def log_message(msg):
#log format: time type message
time_str = str(time.time())
line = time_str[:time_str.find(".")]
line = line.rjust(10, str(" "))
line += " "
busses.status_bus["latest_messages"][msg.chat_id] = msg
msg_type = helper.get_message_type(msg)
if msg_type == "text" and msg.text.startswith("/"):
msg_type = "command"
appendix = "ERROR"
if msg_type == "text":
appendix = msg.text
elif msg_type == "command":
appendix = msg.text[1:]
elif msg_type == "location":
location_data = msg.location.to_dict()
appendix = str(location_data["latitude"]) + "°, " + str(location_data["longitude"]) + "°"
elif msg_type == "contact":
ap <|fim_middle|>
elif msg_type == "new_user":
appendix = str(msg.new_chat_member.id) + " " + str(msg.new_chat_member.first_name) + " " + str(msg.new_chat_member.last_name)
elif msg_type in ["audio", "document", "game", "photo", "sticker", "video", "voice", "video_note", "unknown"]:
appendix = ""
msg_type = msg_type.rjust(10, str(" "))
appendix = appendix.replace("\n", "\\n").rjust(40, str(" "))
line += msg_type + " " + appendix + " "
line += str(msg.chat_id) + "," + str(msg.message_id)
line += "\n"
with open(config.msg_log_file_path, "a") as log_file:
log_file.write(line.encode("utf-8"))
def complete_log(update):
with open(config.complete_log_file_path, "a") as log_file:
data = update.to_dict()
data.update({"time": time.time()})
json_data = json.dumps(data)
log_file.write(str(json_data).replace("\n", "\\n") + "\n".encode("utf-8"))
<|fim▁end|> | pendix = str(msg.contact.user_id) + " " + msg.contact.first_name + " " + msg.contact.last_name
|
<|file_name|>logger.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
import time
import string
import json
import config
import helper
import busses
def log_message(msg):
#log format: time type message
time_str = str(time.time())
line = time_str[:time_str.find(".")]
line = line.rjust(10, str(" "))
line += " "
busses.status_bus["latest_messages"][msg.chat_id] = msg
msg_type = helper.get_message_type(msg)
if msg_type == "text" and msg.text.startswith("/"):
msg_type = "command"
appendix = "ERROR"
if msg_type == "text":
appendix = msg.text
elif msg_type == "command":
appendix = msg.text[1:]
elif msg_type == "location":
location_data = msg.location.to_dict()
appendix = str(location_data["latitude"]) + "°, " + str(location_data["longitude"]) + "°"
elif msg_type == "contact":
appendix = str(msg.contact.user_id) + " " + msg.contact.first_name + " " + msg.contact.last_name
elif msg_type == "new_user":
ap <|fim_middle|>
elif msg_type in ["audio", "document", "game", "photo", "sticker", "video", "voice", "video_note", "unknown"]:
appendix = ""
msg_type = msg_type.rjust(10, str(" "))
appendix = appendix.replace("\n", "\\n").rjust(40, str(" "))
line += msg_type + " " + appendix + " "
line += str(msg.chat_id) + "," + str(msg.message_id)
line += "\n"
with open(config.msg_log_file_path, "a") as log_file:
log_file.write(line.encode("utf-8"))
def complete_log(update):
with open(config.complete_log_file_path, "a") as log_file:
data = update.to_dict()
data.update({"time": time.time()})
json_data = json.dumps(data)
log_file.write(str(json_data).replace("\n", "\\n") + "\n".encode("utf-8"))
<|fim▁end|> | pendix = str(msg.new_chat_member.id) + " " + str(msg.new_chat_member.first_name) + " " + str(msg.new_chat_member.last_name)
|
<|file_name|>logger.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
import time
import string
import json
import config
import helper
import busses
def log_message(msg):
#log format: time type message
time_str = str(time.time())
line = time_str[:time_str.find(".")]
line = line.rjust(10, str(" "))
line += " "
busses.status_bus["latest_messages"][msg.chat_id] = msg
msg_type = helper.get_message_type(msg)
if msg_type == "text" and msg.text.startswith("/"):
msg_type = "command"
appendix = "ERROR"
if msg_type == "text":
appendix = msg.text
elif msg_type == "command":
appendix = msg.text[1:]
elif msg_type == "location":
location_data = msg.location.to_dict()
appendix = str(location_data["latitude"]) + "°, " + str(location_data["longitude"]) + "°"
elif msg_type == "contact":
appendix = str(msg.contact.user_id) + " " + msg.contact.first_name + " " + msg.contact.last_name
elif msg_type == "new_user":
appendix = str(msg.new_chat_member.id) + " " + str(msg.new_chat_member.first_name) + " " + str(msg.new_chat_member.last_name)
elif msg_type in ["audio", "document", "game", "photo", "sticker", "video", "voice", "video_note", "unknown"]:
ap <|fim_middle|>
msg_type = msg_type.rjust(10, str(" "))
appendix = appendix.replace("\n", "\\n").rjust(40, str(" "))
line += msg_type + " " + appendix + " "
line += str(msg.chat_id) + "," + str(msg.message_id)
line += "\n"
with open(config.msg_log_file_path, "a") as log_file:
log_file.write(line.encode("utf-8"))
def complete_log(update):
with open(config.complete_log_file_path, "a") as log_file:
data = update.to_dict()
data.update({"time": time.time()})
json_data = json.dumps(data)
log_file.write(str(json_data).replace("\n", "\\n") + "\n".encode("utf-8"))
<|fim▁end|> | pendix = ""
|
<|file_name|>logger.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
import time
import string
import json
import config
import helper
import busses
def <|fim_middle|>(msg):
#log format: time type message
time_str = str(time.time())
line = time_str[:time_str.find(".")]
line = line.rjust(10, str(" "))
line += " "
busses.status_bus["latest_messages"][msg.chat_id] = msg
msg_type = helper.get_message_type(msg)
if msg_type == "text" and msg.text.startswith("/"):
msg_type = "command"
appendix = "ERROR"
if msg_type == "text":
appendix = msg.text
elif msg_type == "command":
appendix = msg.text[1:]
elif msg_type == "location":
location_data = msg.location.to_dict()
appendix = str(location_data["latitude"]) + "°, " + str(location_data["longitude"]) + "°"
elif msg_type == "contact":
appendix = str(msg.contact.user_id) + " " + msg.contact.first_name + " " + msg.contact.last_name
elif msg_type == "new_user":
appendix = str(msg.new_chat_member.id) + " " + str(msg.new_chat_member.first_name) + " " + str(msg.new_chat_member.last_name)
elif msg_type in ["audio", "document", "game", "photo", "sticker", "video", "voice", "video_note", "unknown"]:
appendix = ""
msg_type = msg_type.rjust(10, str(" "))
appendix = appendix.replace("\n", "\\n").rjust(40, str(" "))
line += msg_type + " " + appendix + " "
line += str(msg.chat_id) + "," + str(msg.message_id)
line += "\n"
with open(config.msg_log_file_path, "a") as log_file:
log_file.write(line.encode("utf-8"))
def complete_log(update):
with open(config.complete_log_file_path, "a") as log_file:
data = update.to_dict()
data.update({"time": time.time()})
json_data = json.dumps(data)
log_file.write(str(json_data).replace("\n", "\\n") + "\n".encode("utf-8"))
<|fim▁end|> | log_message |
<|file_name|>logger.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
import time
import string
import json
import config
import helper
import busses
def log_message(msg):
#log format: time type message
time_str = str(time.time())
line = time_str[:time_str.find(".")]
line = line.rjust(10, str(" "))
line += " "
busses.status_bus["latest_messages"][msg.chat_id] = msg
msg_type = helper.get_message_type(msg)
if msg_type == "text" and msg.text.startswith("/"):
msg_type = "command"
appendix = "ERROR"
if msg_type == "text":
appendix = msg.text
elif msg_type == "command":
appendix = msg.text[1:]
elif msg_type == "location":
location_data = msg.location.to_dict()
appendix = str(location_data["latitude"]) + "°, " + str(location_data["longitude"]) + "°"
elif msg_type == "contact":
appendix = str(msg.contact.user_id) + " " + msg.contact.first_name + " " + msg.contact.last_name
elif msg_type == "new_user":
appendix = str(msg.new_chat_member.id) + " " + str(msg.new_chat_member.first_name) + " " + str(msg.new_chat_member.last_name)
elif msg_type in ["audio", "document", "game", "photo", "sticker", "video", "voice", "video_note", "unknown"]:
appendix = ""
msg_type = msg_type.rjust(10, str(" "))
appendix = appendix.replace("\n", "\\n").rjust(40, str(" "))
line += msg_type + " " + appendix + " "
line += str(msg.chat_id) + "," + str(msg.message_id)
line += "\n"
with open(config.msg_log_file_path, "a") as log_file:
log_file.write(line.encode("utf-8"))
def co<|fim_middle|>pdate):
with open(config.complete_log_file_path, "a") as log_file:
data = update.to_dict()
data.update({"time": time.time()})
json_data = json.dumps(data)
log_file.write(str(json_data).replace("\n", "\\n") + "\n".encode("utf-8"))
<|fim▁end|> | mplete_log(u |
<|file_name|>app.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# If this page isn't working, try executing `chmod +x app.py` in terminal.
# enable debugging
import cgitb, cgi; cgitb.enable()
from classes import Factory
fieldStorage = cgi.FieldStorage()
factory = Factory.Factory()
webApp = factory.makeWebApp(fieldStorage)
def outputHeaders():
print "Content-Type: text/html"
print # signals end of headers<|fim▁hole|>
print webApp.getOutput()<|fim▁end|> |
outputHeaders() |
<|file_name|>app.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# If this page isn't working, try executing `chmod +x app.py` in terminal.
# enable debugging
import cgitb, cgi; cgitb.enable()
from classes import Factory
fieldStorage = cgi.FieldStorage()
factory = Factory.Factory()
webApp = factory.makeWebApp(fieldStorage)
def outputHeaders():
<|fim_middle|>
outputHeaders()
print webApp.getOutput()
<|fim▁end|> | print "Content-Type: text/html"
print # signals end of headers |
<|file_name|>app.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# If this page isn't working, try executing `chmod +x app.py` in terminal.
# enable debugging
import cgitb, cgi; cgitb.enable()
from classes import Factory
fieldStorage = cgi.FieldStorage()
factory = Factory.Factory()
webApp = factory.makeWebApp(fieldStorage)
def <|fim_middle|>():
print "Content-Type: text/html"
print # signals end of headers
outputHeaders()
print webApp.getOutput()
<|fim▁end|> | outputHeaders |
<|file_name|>0002_catalogintegration_username.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('catalog', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='catalogintegration',
name='service_username',<|fim▁hole|> field=models.CharField(default=u'lms_catalog_service_user', help_text='Username created for Course Catalog Integration, e.g. lms_catalog_service_user.', max_length=100),
),
]<|fim▁end|> | |
<|file_name|>0002_catalogintegration_username.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from django.db import migrations, models
class Migration(migrations.Migration):
<|fim_middle|>
<|fim▁end|> | dependencies = [
('catalog', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='catalogintegration',
name='service_username',
field=models.CharField(default=u'lms_catalog_service_user', help_text='Username created for Course Catalog Integration, e.g. lms_catalog_service_user.', max_length=100),
),
] |
<|file_name|>order.py<|end_file_name|><|fim▁begin|>from ..cw_model import CWModel
class Order(CWModel):
def __init__(self, json_dict=None):
self.id = None # (Integer)
self.company = None # *(CompanyReference)
self.contact = None # (ContactReference)
self.phone = None # (String)
self.phoneExt = None # (String)
self.email = None # (String)
self.site = None # (SiteReference)
self.status = None # *(OrderStatusReference)
self.opportunity = None # (OpportunityReference)
self.orderDate = None # (String)
self.dueDate = None # (String)
self.billingTerms = None # (BillingTermsReference)
self.taxCode = None # (TaxCodeReference)
self.poNumber = None # (String(50))
self.locationId = None # (Integer)
self.businessUnitId = None # (Integer)
self.salesRep = None # *(MemberReference)
self.notes = None # (String)
self.billClosedFlag = None # (Boolean)
self.billShippedFlag = None # (Boolean)
self.restrictDownpaymentFlag = None # (Boolean)
self.description = None # (String)
self.topCommentFlag = None # (Boolean)
self.bottomCommentFlag = None # (Boolean)
self.shipToCompany = None # (CompanyReference)
self.shipToContact = None # (ContactReference)
self.shipToSite = None # (SiteReference)
self.billToCompany = None # (CompanyReference)
self.billToContact = None # (ContactReference)
self.billToSite = None # (SiteReference)
<|fim▁hole|> self.productIds = None # (Integer[])
self.documentIds = None # (Integer[])
self.invoiceIds = None # (Integer[])
self.configIds = None # (Integer[])
self.total = None # (Number)
self.taxTotal = None # (Number)
self._info = None # (Metadata)
# initialize object with json dict
super().__init__(json_dict)<|fim▁end|> | |
<|file_name|>order.py<|end_file_name|><|fim▁begin|>from ..cw_model import CWModel
class Order(CWModel):
<|fim_middle|>
<|fim▁end|> | def __init__(self, json_dict=None):
self.id = None # (Integer)
self.company = None # *(CompanyReference)
self.contact = None # (ContactReference)
self.phone = None # (String)
self.phoneExt = None # (String)
self.email = None # (String)
self.site = None # (SiteReference)
self.status = None # *(OrderStatusReference)
self.opportunity = None # (OpportunityReference)
self.orderDate = None # (String)
self.dueDate = None # (String)
self.billingTerms = None # (BillingTermsReference)
self.taxCode = None # (TaxCodeReference)
self.poNumber = None # (String(50))
self.locationId = None # (Integer)
self.businessUnitId = None # (Integer)
self.salesRep = None # *(MemberReference)
self.notes = None # (String)
self.billClosedFlag = None # (Boolean)
self.billShippedFlag = None # (Boolean)
self.restrictDownpaymentFlag = None # (Boolean)
self.description = None # (String)
self.topCommentFlag = None # (Boolean)
self.bottomCommentFlag = None # (Boolean)
self.shipToCompany = None # (CompanyReference)
self.shipToContact = None # (ContactReference)
self.shipToSite = None # (SiteReference)
self.billToCompany = None # (CompanyReference)
self.billToContact = None # (ContactReference)
self.billToSite = None # (SiteReference)
self.productIds = None # (Integer[])
self.documentIds = None # (Integer[])
self.invoiceIds = None # (Integer[])
self.configIds = None # (Integer[])
self.total = None # (Number)
self.taxTotal = None # (Number)
self._info = None # (Metadata)
# initialize object with json dict
super().__init__(json_dict) |
<|file_name|>order.py<|end_file_name|><|fim▁begin|>from ..cw_model import CWModel
class Order(CWModel):
def __init__(self, json_dict=None):
<|fim_middle|>
<|fim▁end|> | self.id = None # (Integer)
self.company = None # *(CompanyReference)
self.contact = None # (ContactReference)
self.phone = None # (String)
self.phoneExt = None # (String)
self.email = None # (String)
self.site = None # (SiteReference)
self.status = None # *(OrderStatusReference)
self.opportunity = None # (OpportunityReference)
self.orderDate = None # (String)
self.dueDate = None # (String)
self.billingTerms = None # (BillingTermsReference)
self.taxCode = None # (TaxCodeReference)
self.poNumber = None # (String(50))
self.locationId = None # (Integer)
self.businessUnitId = None # (Integer)
self.salesRep = None # *(MemberReference)
self.notes = None # (String)
self.billClosedFlag = None # (Boolean)
self.billShippedFlag = None # (Boolean)
self.restrictDownpaymentFlag = None # (Boolean)
self.description = None # (String)
self.topCommentFlag = None # (Boolean)
self.bottomCommentFlag = None # (Boolean)
self.shipToCompany = None # (CompanyReference)
self.shipToContact = None # (ContactReference)
self.shipToSite = None # (SiteReference)
self.billToCompany = None # (CompanyReference)
self.billToContact = None # (ContactReference)
self.billToSite = None # (SiteReference)
self.productIds = None # (Integer[])
self.documentIds = None # (Integer[])
self.invoiceIds = None # (Integer[])
self.configIds = None # (Integer[])
self.total = None # (Number)
self.taxTotal = None # (Number)
self._info = None # (Metadata)
# initialize object with json dict
super().__init__(json_dict) |
<|file_name|>order.py<|end_file_name|><|fim▁begin|>from ..cw_model import CWModel
class Order(CWModel):
def <|fim_middle|>(self, json_dict=None):
self.id = None # (Integer)
self.company = None # *(CompanyReference)
self.contact = None # (ContactReference)
self.phone = None # (String)
self.phoneExt = None # (String)
self.email = None # (String)
self.site = None # (SiteReference)
self.status = None # *(OrderStatusReference)
self.opportunity = None # (OpportunityReference)
self.orderDate = None # (String)
self.dueDate = None # (String)
self.billingTerms = None # (BillingTermsReference)
self.taxCode = None # (TaxCodeReference)
self.poNumber = None # (String(50))
self.locationId = None # (Integer)
self.businessUnitId = None # (Integer)
self.salesRep = None # *(MemberReference)
self.notes = None # (String)
self.billClosedFlag = None # (Boolean)
self.billShippedFlag = None # (Boolean)
self.restrictDownpaymentFlag = None # (Boolean)
self.description = None # (String)
self.topCommentFlag = None # (Boolean)
self.bottomCommentFlag = None # (Boolean)
self.shipToCompany = None # (CompanyReference)
self.shipToContact = None # (ContactReference)
self.shipToSite = None # (SiteReference)
self.billToCompany = None # (CompanyReference)
self.billToContact = None # (ContactReference)
self.billToSite = None # (SiteReference)
self.productIds = None # (Integer[])
self.documentIds = None # (Integer[])
self.invoiceIds = None # (Integer[])
self.configIds = None # (Integer[])
self.total = None # (Number)
self.taxTotal = None # (Number)
self._info = None # (Metadata)
# initialize object with json dict
super().__init__(json_dict)
<|fim▁end|> | __init__ |
<|file_name|>djvutext.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
- path to a file name
- dir where a djvu file name as index is located
optional, by default is current dir '.'
-pages:<start>-<end>,...<start>-<end>,<start>-<end>
Page range to upload;
optional, start=1, end=djvu file number of images.<|fim▁hole|> A- -> pages A until number of images
A -> just page A
-B -> pages 1 until B
This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`.
The following options can be set within a settings file which is scripts.ini
by default:
-summary: custom edit summary.
Use quotes if edit summary contains spaces.
-force overwrites existing text
optional, default False
-always do not bother asking to confirm any of the changes.
"""
#
# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
import os.path
from typing import Optional
import pywikibot
from pywikibot import i18n
from pywikibot.bot import SingleSiteBot
from pywikibot.exceptions import NoPageError
from pywikibot.proofreadpage import ProofreadPage
from pywikibot.tools.djvu import DjVuFile
class DjVuTextBot(SingleSiteBot):
"""
A bot that uploads text-layer from djvu files to Page:namespace.
Works only on sites with Proofread Page extension installed.
.. versionchanged:: 7.0
CheckerBot is a ConfigParserBot
"""
update_options = {
'force': False,
'summary': '',
}
def __init__(
self,
djvu,
index,
pages: Optional[tuple] = None,
**kwargs
) -> None:
"""
Initializer.
:param djvu: djvu from where to fetch the text layer
:type djvu: DjVuFile object
:param index: index page in the Index: namespace
:type index: Page object
:param pages: page interval to upload (start, end)
"""
super().__init__(**kwargs)
self._djvu = djvu
self._index = index
self._prefix = self._index.title(with_ns=False)
self._page_ns = self.site._proofread_page_ns.custom_name
if not pages:
self._pages = (1, self._djvu.number_of_images())
else:
self._pages = pages
# Get edit summary message if it's empty.
if not self.opt.summary:
self.opt.summary = i18n.twtranslate(self._index.site,
'djvutext-creating')
def page_number_gen(self):
"""Generate pages numbers from specified page intervals."""
last = 0
for start, end in sorted(self._pages):
start = max(last, start)
last = end + 1
yield from range(start, last)
@property
def generator(self):
"""Generate pages from specified page interval."""
for page_number in self.page_number_gen():
title = '{page_ns}:{prefix}/{number}'.format(
page_ns=self._page_ns,
prefix=self._prefix,
number=page_number)
page = ProofreadPage(self._index.site, title)
page.page_number = page_number # remember page number in djvu file
yield page
def treat(self, page) -> None:
"""Process one page."""
old_text = page.text
# Overwrite body of the page with content from djvu
page.body = self._djvu.get_page(page.page_number)
new_text = page.text
if page.exists() and not self.opt.force:
pywikibot.output(
'Page {} already exists, not adding!\n'
'Use -force option to overwrite the output page.'
.format(page))
else:
self.userPut(page, old_text, new_text, summary=self.opt.summary)
def main(*args: str) -> None:
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
index = None
djvu_path = '.' # default djvu file directory
pages = '1-'
options = {}
# Parse command line arguments.
local_args = pywikibot.handle_args(args)
for arg in local_args:
opt, _, value = arg.partition(':')
if opt == '-index':
index = value
elif opt == '-djvu':
djvu_path = value
elif opt == '-pages':
pages = value
elif opt == '-summary':
options['summary'] = value
elif opt in ('-force', '-always'):
options[opt[1:]] = True
else:
pywikibot.output('Unknown argument ' + arg)
# index is mandatory.
if not index:
pywikibot.bot.suggest_help(missing_parameters=['-index'])
return
# If djvu_path is not a file, build djvu_path from dir+index.
djvu_path = os.path.expanduser(djvu_path)
djvu_path = os.path.abspath(djvu_path)
if not os.path.exists(djvu_path):
pywikibot.error('No such file or directory: ' + djvu_path)
return
if os.path.isdir(djvu_path):
djvu_path = os.path.join(djvu_path, index)
# Check the djvu file exists and, if so, create the DjVuFile wrapper.
djvu = DjVuFile(djvu_path)
if not djvu.has_text():
pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
return
# Parse pages param.
pages = pages.split(',')
for i, page_interval in enumerate(pages):
start, sep, end = page_interval.partition('-')
start = int(start or 1)
end = int(end or djvu.number_of_images()) if sep else start
pages[i] = (start, end)
site = pywikibot.Site()
if not site.has_extension('ProofreadPage'):
pywikibot.error('Site {} must have ProofreadPage extension.'
.format(site))
return
index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns)
if not index_page.exists():
raise NoPageError(index)
pywikibot.output('uploading text from {} to {}'
.format(djvu.file, index_page.title(as_link=True)))
bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options)
bot.run()
if __name__ == '__main__':
try:
main()
except Exception:
pywikibot.error('Fatal error:', exc_info=True)<|fim▁end|> | Page ranges can be specified as:
A-B -> pages A until B |
<|file_name|>djvutext.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
- path to a file name
- dir where a djvu file name as index is located
optional, by default is current dir '.'
-pages:<start>-<end>,...<start>-<end>,<start>-<end>
Page range to upload;
optional, start=1, end=djvu file number of images.
Page ranges can be specified as:
A-B -> pages A until B
A- -> pages A until number of images
A -> just page A
-B -> pages 1 until B
This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`.
The following options can be set within a settings file which is scripts.ini
by default:
-summary: custom edit summary.
Use quotes if edit summary contains spaces.
-force overwrites existing text
optional, default False
-always do not bother asking to confirm any of the changes.
"""
#
# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
import os.path
from typing import Optional
import pywikibot
from pywikibot import i18n
from pywikibot.bot import SingleSiteBot
from pywikibot.exceptions import NoPageError
from pywikibot.proofreadpage import ProofreadPage
from pywikibot.tools.djvu import DjVuFile
class DjVuTextBot(SingleSiteBot):
<|fim_middle|>
def main(*args: str) -> None:
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
index = None
djvu_path = '.' # default djvu file directory
pages = '1-'
options = {}
# Parse command line arguments.
local_args = pywikibot.handle_args(args)
for arg in local_args:
opt, _, value = arg.partition(':')
if opt == '-index':
index = value
elif opt == '-djvu':
djvu_path = value
elif opt == '-pages':
pages = value
elif opt == '-summary':
options['summary'] = value
elif opt in ('-force', '-always'):
options[opt[1:]] = True
else:
pywikibot.output('Unknown argument ' + arg)
# index is mandatory.
if not index:
pywikibot.bot.suggest_help(missing_parameters=['-index'])
return
# If djvu_path is not a file, build djvu_path from dir+index.
djvu_path = os.path.expanduser(djvu_path)
djvu_path = os.path.abspath(djvu_path)
if not os.path.exists(djvu_path):
pywikibot.error('No such file or directory: ' + djvu_path)
return
if os.path.isdir(djvu_path):
djvu_path = os.path.join(djvu_path, index)
# Check the djvu file exists and, if so, create the DjVuFile wrapper.
djvu = DjVuFile(djvu_path)
if not djvu.has_text():
pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
return
# Parse pages param.
pages = pages.split(',')
for i, page_interval in enumerate(pages):
start, sep, end = page_interval.partition('-')
start = int(start or 1)
end = int(end or djvu.number_of_images()) if sep else start
pages[i] = (start, end)
site = pywikibot.Site()
if not site.has_extension('ProofreadPage'):
pywikibot.error('Site {} must have ProofreadPage extension.'
.format(site))
return
index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns)
if not index_page.exists():
raise NoPageError(index)
pywikibot.output('uploading text from {} to {}'
.format(djvu.file, index_page.title(as_link=True)))
bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options)
bot.run()
if __name__ == '__main__':
try:
main()
except Exception:
pywikibot.error('Fatal error:', exc_info=True)
<|fim▁end|> | """
A bot that uploads text-layer from djvu files to Page:namespace.
Works only on sites with Proofread Page extension installed.
.. versionchanged:: 7.0
CheckerBot is a ConfigParserBot
"""
update_options = {
'force': False,
'summary': '',
}
def __init__(
self,
djvu,
index,
pages: Optional[tuple] = None,
**kwargs
) -> None:
"""
Initializer.
:param djvu: djvu from where to fetch the text layer
:type djvu: DjVuFile object
:param index: index page in the Index: namespace
:type index: Page object
:param pages: page interval to upload (start, end)
"""
super().__init__(**kwargs)
self._djvu = djvu
self._index = index
self._prefix = self._index.title(with_ns=False)
self._page_ns = self.site._proofread_page_ns.custom_name
if not pages:
self._pages = (1, self._djvu.number_of_images())
else:
self._pages = pages
# Get edit summary message if it's empty.
if not self.opt.summary:
self.opt.summary = i18n.twtranslate(self._index.site,
'djvutext-creating')
def page_number_gen(self):
"""Generate pages numbers from specified page intervals."""
last = 0
for start, end in sorted(self._pages):
start = max(last, start)
last = end + 1
yield from range(start, last)
@property
def generator(self):
"""Generate pages from specified page interval."""
for page_number in self.page_number_gen():
title = '{page_ns}:{prefix}/{number}'.format(
page_ns=self._page_ns,
prefix=self._prefix,
number=page_number)
page = ProofreadPage(self._index.site, title)
page.page_number = page_number # remember page number in djvu file
yield page
def treat(self, page) -> None:
"""Process one page."""
old_text = page.text
# Overwrite body of the page with content from djvu
page.body = self._djvu.get_page(page.page_number)
new_text = page.text
if page.exists() and not self.opt.force:
pywikibot.output(
'Page {} already exists, not adding!\n'
'Use -force option to overwrite the output page.'
.format(page))
else:
self.userPut(page, old_text, new_text, summary=self.opt.summary) |
<|file_name|>djvutext.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
- path to a file name
- dir where a djvu file name as index is located
optional, by default is current dir '.'
-pages:<start>-<end>,...<start>-<end>,<start>-<end>
Page range to upload;
optional, start=1, end=djvu file number of images.
Page ranges can be specified as:
A-B -> pages A until B
A- -> pages A until number of images
A -> just page A
-B -> pages 1 until B
This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`.
The following options can be set within a settings file which is scripts.ini
by default:
-summary: custom edit summary.
Use quotes if edit summary contains spaces.
-force overwrites existing text
optional, default False
-always do not bother asking to confirm any of the changes.
"""
#
# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
import os.path
from typing import Optional
import pywikibot
from pywikibot import i18n
from pywikibot.bot import SingleSiteBot
from pywikibot.exceptions import NoPageError
from pywikibot.proofreadpage import ProofreadPage
from pywikibot.tools.djvu import DjVuFile
class DjVuTextBot(SingleSiteBot):
"""
A bot that uploads text-layer from djvu files to Page:namespace.
Works only on sites with Proofread Page extension installed.
.. versionchanged:: 7.0
CheckerBot is a ConfigParserBot
"""
update_options = {
'force': False,
'summary': '',
}
def __init__(
self,
djvu,
index,
pages: Optional[tuple] = None,
**kwargs
) -> None:
<|fim_middle|>
def page_number_gen(self):
"""Generate pages numbers from specified page intervals."""
last = 0
for start, end in sorted(self._pages):
start = max(last, start)
last = end + 1
yield from range(start, last)
@property
def generator(self):
"""Generate pages from specified page interval."""
for page_number in self.page_number_gen():
title = '{page_ns}:{prefix}/{number}'.format(
page_ns=self._page_ns,
prefix=self._prefix,
number=page_number)
page = ProofreadPage(self._index.site, title)
page.page_number = page_number # remember page number in djvu file
yield page
def treat(self, page) -> None:
"""Process one page."""
old_text = page.text
# Overwrite body of the page with content from djvu
page.body = self._djvu.get_page(page.page_number)
new_text = page.text
if page.exists() and not self.opt.force:
pywikibot.output(
'Page {} already exists, not adding!\n'
'Use -force option to overwrite the output page.'
.format(page))
else:
self.userPut(page, old_text, new_text, summary=self.opt.summary)
def main(*args: str) -> None:
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
index = None
djvu_path = '.' # default djvu file directory
pages = '1-'
options = {}
# Parse command line arguments.
local_args = pywikibot.handle_args(args)
for arg in local_args:
opt, _, value = arg.partition(':')
if opt == '-index':
index = value
elif opt == '-djvu':
djvu_path = value
elif opt == '-pages':
pages = value
elif opt == '-summary':
options['summary'] = value
elif opt in ('-force', '-always'):
options[opt[1:]] = True
else:
pywikibot.output('Unknown argument ' + arg)
# index is mandatory.
if not index:
pywikibot.bot.suggest_help(missing_parameters=['-index'])
return
# If djvu_path is not a file, build djvu_path from dir+index.
djvu_path = os.path.expanduser(djvu_path)
djvu_path = os.path.abspath(djvu_path)
if not os.path.exists(djvu_path):
pywikibot.error('No such file or directory: ' + djvu_path)
return
if os.path.isdir(djvu_path):
djvu_path = os.path.join(djvu_path, index)
# Check the djvu file exists and, if so, create the DjVuFile wrapper.
djvu = DjVuFile(djvu_path)
if not djvu.has_text():
pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
return
# Parse pages param.
pages = pages.split(',')
for i, page_interval in enumerate(pages):
start, sep, end = page_interval.partition('-')
start = int(start or 1)
end = int(end or djvu.number_of_images()) if sep else start
pages[i] = (start, end)
site = pywikibot.Site()
if not site.has_extension('ProofreadPage'):
pywikibot.error('Site {} must have ProofreadPage extension.'
.format(site))
return
index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns)
if not index_page.exists():
raise NoPageError(index)
pywikibot.output('uploading text from {} to {}'
.format(djvu.file, index_page.title(as_link=True)))
bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options)
bot.run()
if __name__ == '__main__':
try:
main()
except Exception:
pywikibot.error('Fatal error:', exc_info=True)
<|fim▁end|> | """
Initializer.
:param djvu: djvu from where to fetch the text layer
:type djvu: DjVuFile object
:param index: index page in the Index: namespace
:type index: Page object
:param pages: page interval to upload (start, end)
"""
super().__init__(**kwargs)
self._djvu = djvu
self._index = index
self._prefix = self._index.title(with_ns=False)
self._page_ns = self.site._proofread_page_ns.custom_name
if not pages:
self._pages = (1, self._djvu.number_of_images())
else:
self._pages = pages
# Get edit summary message if it's empty.
if not self.opt.summary:
self.opt.summary = i18n.twtranslate(self._index.site,
'djvutext-creating') |
<|file_name|>djvutext.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
- path to a file name
- dir where a djvu file name as index is located
optional, by default is current dir '.'
-pages:<start>-<end>,...<start>-<end>,<start>-<end>
Page range to upload;
optional, start=1, end=djvu file number of images.
Page ranges can be specified as:
A-B -> pages A until B
A- -> pages A until number of images
A -> just page A
-B -> pages 1 until B
This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`.
The following options can be set within a settings file which is scripts.ini
by default:
-summary: custom edit summary.
Use quotes if edit summary contains spaces.
-force overwrites existing text
optional, default False
-always do not bother asking to confirm any of the changes.
"""
#
# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
import os.path
from typing import Optional
import pywikibot
from pywikibot import i18n
from pywikibot.bot import SingleSiteBot
from pywikibot.exceptions import NoPageError
from pywikibot.proofreadpage import ProofreadPage
from pywikibot.tools.djvu import DjVuFile
class DjVuTextBot(SingleSiteBot):
"""
A bot that uploads text-layer from djvu files to Page:namespace.
Works only on sites with Proofread Page extension installed.
.. versionchanged:: 7.0
CheckerBot is a ConfigParserBot
"""
update_options = {
'force': False,
'summary': '',
}
def __init__(
self,
djvu,
index,
pages: Optional[tuple] = None,
**kwargs
) -> None:
"""
Initializer.
:param djvu: djvu from where to fetch the text layer
:type djvu: DjVuFile object
:param index: index page in the Index: namespace
:type index: Page object
:param pages: page interval to upload (start, end)
"""
super().__init__(**kwargs)
self._djvu = djvu
self._index = index
self._prefix = self._index.title(with_ns=False)
self._page_ns = self.site._proofread_page_ns.custom_name
if not pages:
self._pages = (1, self._djvu.number_of_images())
else:
self._pages = pages
# Get edit summary message if it's empty.
if not self.opt.summary:
self.opt.summary = i18n.twtranslate(self._index.site,
'djvutext-creating')
def page_number_gen(self):
<|fim_middle|>
@property
def generator(self):
"""Generate pages from specified page interval."""
for page_number in self.page_number_gen():
title = '{page_ns}:{prefix}/{number}'.format(
page_ns=self._page_ns,
prefix=self._prefix,
number=page_number)
page = ProofreadPage(self._index.site, title)
page.page_number = page_number # remember page number in djvu file
yield page
def treat(self, page) -> None:
"""Process one page."""
old_text = page.text
# Overwrite body of the page with content from djvu
page.body = self._djvu.get_page(page.page_number)
new_text = page.text
if page.exists() and not self.opt.force:
pywikibot.output(
'Page {} already exists, not adding!\n'
'Use -force option to overwrite the output page.'
.format(page))
else:
self.userPut(page, old_text, new_text, summary=self.opt.summary)
def main(*args: str) -> None:
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
index = None
djvu_path = '.' # default djvu file directory
pages = '1-'
options = {}
# Parse command line arguments.
local_args = pywikibot.handle_args(args)
for arg in local_args:
opt, _, value = arg.partition(':')
if opt == '-index':
index = value
elif opt == '-djvu':
djvu_path = value
elif opt == '-pages':
pages = value
elif opt == '-summary':
options['summary'] = value
elif opt in ('-force', '-always'):
options[opt[1:]] = True
else:
pywikibot.output('Unknown argument ' + arg)
# index is mandatory.
if not index:
pywikibot.bot.suggest_help(missing_parameters=['-index'])
return
# If djvu_path is not a file, build djvu_path from dir+index.
djvu_path = os.path.expanduser(djvu_path)
djvu_path = os.path.abspath(djvu_path)
if not os.path.exists(djvu_path):
pywikibot.error('No such file or directory: ' + djvu_path)
return
if os.path.isdir(djvu_path):
djvu_path = os.path.join(djvu_path, index)
# Check the djvu file exists and, if so, create the DjVuFile wrapper.
djvu = DjVuFile(djvu_path)
if not djvu.has_text():
pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
return
# Parse pages param.
pages = pages.split(',')
for i, page_interval in enumerate(pages):
start, sep, end = page_interval.partition('-')
start = int(start or 1)
end = int(end or djvu.number_of_images()) if sep else start
pages[i] = (start, end)
site = pywikibot.Site()
if not site.has_extension('ProofreadPage'):
pywikibot.error('Site {} must have ProofreadPage extension.'
.format(site))
return
index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns)
if not index_page.exists():
raise NoPageError(index)
pywikibot.output('uploading text from {} to {}'
.format(djvu.file, index_page.title(as_link=True)))
bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options)
bot.run()
if __name__ == '__main__':
try:
main()
except Exception:
pywikibot.error('Fatal error:', exc_info=True)
<|fim▁end|> | """Generate pages numbers from specified page intervals."""
last = 0
for start, end in sorted(self._pages):
start = max(last, start)
last = end + 1
yield from range(start, last) |
<|file_name|>djvutext.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
- path to a file name
- dir where a djvu file name as index is located
optional, by default is current dir '.'
-pages:<start>-<end>,...<start>-<end>,<start>-<end>
Page range to upload;
optional, start=1, end=djvu file number of images.
Page ranges can be specified as:
A-B -> pages A until B
A- -> pages A until number of images
A -> just page A
-B -> pages 1 until B
This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`.
The following options can be set within a settings file which is scripts.ini
by default:
-summary: custom edit summary.
Use quotes if edit summary contains spaces.
-force overwrites existing text
optional, default False
-always do not bother asking to confirm any of the changes.
"""
#
# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
import os.path
from typing import Optional
import pywikibot
from pywikibot import i18n
from pywikibot.bot import SingleSiteBot
from pywikibot.exceptions import NoPageError
from pywikibot.proofreadpage import ProofreadPage
from pywikibot.tools.djvu import DjVuFile
class DjVuTextBot(SingleSiteBot):
"""
A bot that uploads text-layer from djvu files to Page:namespace.
Works only on sites with Proofread Page extension installed.
.. versionchanged:: 7.0
CheckerBot is a ConfigParserBot
"""
update_options = {
'force': False,
'summary': '',
}
def __init__(
self,
djvu,
index,
pages: Optional[tuple] = None,
**kwargs
) -> None:
"""
Initializer.
:param djvu: djvu from where to fetch the text layer
:type djvu: DjVuFile object
:param index: index page in the Index: namespace
:type index: Page object
:param pages: page interval to upload (start, end)
"""
super().__init__(**kwargs)
self._djvu = djvu
self._index = index
self._prefix = self._index.title(with_ns=False)
self._page_ns = self.site._proofread_page_ns.custom_name
if not pages:
self._pages = (1, self._djvu.number_of_images())
else:
self._pages = pages
# Get edit summary message if it's empty.
if not self.opt.summary:
self.opt.summary = i18n.twtranslate(self._index.site,
'djvutext-creating')
def page_number_gen(self):
"""Generate pages numbers from specified page intervals."""
last = 0
for start, end in sorted(self._pages):
start = max(last, start)
last = end + 1
yield from range(start, last)
@property
def generator(self):
<|fim_middle|>
def treat(self, page) -> None:
"""Process one page."""
old_text = page.text
# Overwrite body of the page with content from djvu
page.body = self._djvu.get_page(page.page_number)
new_text = page.text
if page.exists() and not self.opt.force:
pywikibot.output(
'Page {} already exists, not adding!\n'
'Use -force option to overwrite the output page.'
.format(page))
else:
self.userPut(page, old_text, new_text, summary=self.opt.summary)
def main(*args: str) -> None:
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
index = None
djvu_path = '.' # default djvu file directory
pages = '1-'
options = {}
# Parse command line arguments.
local_args = pywikibot.handle_args(args)
for arg in local_args:
opt, _, value = arg.partition(':')
if opt == '-index':
index = value
elif opt == '-djvu':
djvu_path = value
elif opt == '-pages':
pages = value
elif opt == '-summary':
options['summary'] = value
elif opt in ('-force', '-always'):
options[opt[1:]] = True
else:
pywikibot.output('Unknown argument ' + arg)
# index is mandatory.
if not index:
pywikibot.bot.suggest_help(missing_parameters=['-index'])
return
# If djvu_path is not a file, build djvu_path from dir+index.
djvu_path = os.path.expanduser(djvu_path)
djvu_path = os.path.abspath(djvu_path)
if not os.path.exists(djvu_path):
pywikibot.error('No such file or directory: ' + djvu_path)
return
if os.path.isdir(djvu_path):
djvu_path = os.path.join(djvu_path, index)
# Check the djvu file exists and, if so, create the DjVuFile wrapper.
djvu = DjVuFile(djvu_path)
if not djvu.has_text():
pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
return
# Parse pages param.
pages = pages.split(',')
for i, page_interval in enumerate(pages):
start, sep, end = page_interval.partition('-')
start = int(start or 1)
end = int(end or djvu.number_of_images()) if sep else start
pages[i] = (start, end)
site = pywikibot.Site()
if not site.has_extension('ProofreadPage'):
pywikibot.error('Site {} must have ProofreadPage extension.'
.format(site))
return
index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns)
if not index_page.exists():
raise NoPageError(index)
pywikibot.output('uploading text from {} to {}'
.format(djvu.file, index_page.title(as_link=True)))
bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options)
bot.run()
if __name__ == '__main__':
try:
main()
except Exception:
pywikibot.error('Fatal error:', exc_info=True)
<|fim▁end|> | """Generate pages from specified page interval."""
for page_number in self.page_number_gen():
title = '{page_ns}:{prefix}/{number}'.format(
page_ns=self._page_ns,
prefix=self._prefix,
number=page_number)
page = ProofreadPage(self._index.site, title)
page.page_number = page_number # remember page number in djvu file
yield page |
<|file_name|>djvutext.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
- path to a file name
- dir where a djvu file name as index is located
optional, by default is current dir '.'
-pages:<start>-<end>,...<start>-<end>,<start>-<end>
Page range to upload;
optional, start=1, end=djvu file number of images.
Page ranges can be specified as:
A-B -> pages A until B
A- -> pages A until number of images
A -> just page A
-B -> pages 1 until B
This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`.
The following options can be set within a settings file which is scripts.ini
by default:
-summary: custom edit summary.
Use quotes if edit summary contains spaces.
-force overwrites existing text
optional, default False
-always do not bother asking to confirm any of the changes.
"""
#
# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
import os.path
from typing import Optional
import pywikibot
from pywikibot import i18n
from pywikibot.bot import SingleSiteBot
from pywikibot.exceptions import NoPageError
from pywikibot.proofreadpage import ProofreadPage
from pywikibot.tools.djvu import DjVuFile
class DjVuTextBot(SingleSiteBot):
"""
A bot that uploads text-layer from djvu files to Page:namespace.
Works only on sites with Proofread Page extension installed.
.. versionchanged:: 7.0
CheckerBot is a ConfigParserBot
"""
update_options = {
'force': False,
'summary': '',
}
def __init__(
self,
djvu,
index,
pages: Optional[tuple] = None,
**kwargs
) -> None:
"""
Initializer.
:param djvu: djvu from where to fetch the text layer
:type djvu: DjVuFile object
:param index: index page in the Index: namespace
:type index: Page object
:param pages: page interval to upload (start, end)
"""
super().__init__(**kwargs)
self._djvu = djvu
self._index = index
self._prefix = self._index.title(with_ns=False)
self._page_ns = self.site._proofread_page_ns.custom_name
if not pages:
self._pages = (1, self._djvu.number_of_images())
else:
self._pages = pages
# Get edit summary message if it's empty.
if not self.opt.summary:
self.opt.summary = i18n.twtranslate(self._index.site,
'djvutext-creating')
def page_number_gen(self):
"""Generate pages numbers from specified page intervals."""
last = 0
for start, end in sorted(self._pages):
start = max(last, start)
last = end + 1
yield from range(start, last)
@property
def generator(self):
"""Generate pages from specified page interval."""
for page_number in self.page_number_gen():
title = '{page_ns}:{prefix}/{number}'.format(
page_ns=self._page_ns,
prefix=self._prefix,
number=page_number)
page = ProofreadPage(self._index.site, title)
page.page_number = page_number # remember page number in djvu file
yield page
def treat(self, page) -> None:
<|fim_middle|>
def main(*args: str) -> None:
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
index = None
djvu_path = '.' # default djvu file directory
pages = '1-'
options = {}
# Parse command line arguments.
local_args = pywikibot.handle_args(args)
for arg in local_args:
opt, _, value = arg.partition(':')
if opt == '-index':
index = value
elif opt == '-djvu':
djvu_path = value
elif opt == '-pages':
pages = value
elif opt == '-summary':
options['summary'] = value
elif opt in ('-force', '-always'):
options[opt[1:]] = True
else:
pywikibot.output('Unknown argument ' + arg)
# index is mandatory.
if not index:
pywikibot.bot.suggest_help(missing_parameters=['-index'])
return
# If djvu_path is not a file, build djvu_path from dir+index.
djvu_path = os.path.expanduser(djvu_path)
djvu_path = os.path.abspath(djvu_path)
if not os.path.exists(djvu_path):
pywikibot.error('No such file or directory: ' + djvu_path)
return
if os.path.isdir(djvu_path):
djvu_path = os.path.join(djvu_path, index)
# Check the djvu file exists and, if so, create the DjVuFile wrapper.
djvu = DjVuFile(djvu_path)
if not djvu.has_text():
pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
return
# Parse pages param.
pages = pages.split(',')
for i, page_interval in enumerate(pages):
start, sep, end = page_interval.partition('-')
start = int(start or 1)
end = int(end or djvu.number_of_images()) if sep else start
pages[i] = (start, end)
site = pywikibot.Site()
if not site.has_extension('ProofreadPage'):
pywikibot.error('Site {} must have ProofreadPage extension.'
.format(site))
return
index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns)
if not index_page.exists():
raise NoPageError(index)
pywikibot.output('uploading text from {} to {}'
.format(djvu.file, index_page.title(as_link=True)))
bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options)
bot.run()
if __name__ == '__main__':
try:
main()
except Exception:
pywikibot.error('Fatal error:', exc_info=True)
<|fim▁end|> | """Process one page."""
old_text = page.text
# Overwrite body of the page with content from djvu
page.body = self._djvu.get_page(page.page_number)
new_text = page.text
if page.exists() and not self.opt.force:
pywikibot.output(
'Page {} already exists, not adding!\n'
'Use -force option to overwrite the output page.'
.format(page))
else:
self.userPut(page, old_text, new_text, summary=self.opt.summary) |
<|file_name|>djvutext.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
- path to a file name
- dir where a djvu file name as index is located
optional, by default is current dir '.'
-pages:<start>-<end>,...<start>-<end>,<start>-<end>
Page range to upload;
optional, start=1, end=djvu file number of images.
Page ranges can be specified as:
A-B -> pages A until B
A- -> pages A until number of images
A -> just page A
-B -> pages 1 until B
This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`.
The following options can be set within a settings file which is scripts.ini
by default:
-summary: custom edit summary.
Use quotes if edit summary contains spaces.
-force overwrites existing text
optional, default False
-always do not bother asking to confirm any of the changes.
"""
#
# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
import os.path
from typing import Optional
import pywikibot
from pywikibot import i18n
from pywikibot.bot import SingleSiteBot
from pywikibot.exceptions import NoPageError
from pywikibot.proofreadpage import ProofreadPage
from pywikibot.tools.djvu import DjVuFile
class DjVuTextBot(SingleSiteBot):
"""
A bot that uploads text-layer from djvu files to Page:namespace.
Works only on sites with Proofread Page extension installed.
.. versionchanged:: 7.0
CheckerBot is a ConfigParserBot
"""
update_options = {
'force': False,
'summary': '',
}
def __init__(
self,
djvu,
index,
pages: Optional[tuple] = None,
**kwargs
) -> None:
"""
Initializer.
:param djvu: djvu from where to fetch the text layer
:type djvu: DjVuFile object
:param index: index page in the Index: namespace
:type index: Page object
:param pages: page interval to upload (start, end)
"""
super().__init__(**kwargs)
self._djvu = djvu
self._index = index
self._prefix = self._index.title(with_ns=False)
self._page_ns = self.site._proofread_page_ns.custom_name
if not pages:
self._pages = (1, self._djvu.number_of_images())
else:
self._pages = pages
# Get edit summary message if it's empty.
if not self.opt.summary:
self.opt.summary = i18n.twtranslate(self._index.site,
'djvutext-creating')
def page_number_gen(self):
"""Generate pages numbers from specified page intervals."""
last = 0
for start, end in sorted(self._pages):
start = max(last, start)
last = end + 1
yield from range(start, last)
@property
def generator(self):
"""Generate pages from specified page interval."""
for page_number in self.page_number_gen():
title = '{page_ns}:{prefix}/{number}'.format(
page_ns=self._page_ns,
prefix=self._prefix,
number=page_number)
page = ProofreadPage(self._index.site, title)
page.page_number = page_number # remember page number in djvu file
yield page
def treat(self, page) -> None:
"""Process one page."""
old_text = page.text
# Overwrite body of the page with content from djvu
page.body = self._djvu.get_page(page.page_number)
new_text = page.text
if page.exists() and not self.opt.force:
pywikibot.output(
'Page {} already exists, not adding!\n'
'Use -force option to overwrite the output page.'
.format(page))
else:
self.userPut(page, old_text, new_text, summary=self.opt.summary)
def main(*args: str) -> None:
<|fim_middle|>
if __name__ == '__main__':
try:
main()
except Exception:
pywikibot.error('Fatal error:', exc_info=True)
<|fim▁end|> | """
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
index = None
djvu_path = '.' # default djvu file directory
pages = '1-'
options = {}
# Parse command line arguments.
local_args = pywikibot.handle_args(args)
for arg in local_args:
opt, _, value = arg.partition(':')
if opt == '-index':
index = value
elif opt == '-djvu':
djvu_path = value
elif opt == '-pages':
pages = value
elif opt == '-summary':
options['summary'] = value
elif opt in ('-force', '-always'):
options[opt[1:]] = True
else:
pywikibot.output('Unknown argument ' + arg)
# index is mandatory.
if not index:
pywikibot.bot.suggest_help(missing_parameters=['-index'])
return
# If djvu_path is not a file, build djvu_path from dir+index.
djvu_path = os.path.expanduser(djvu_path)
djvu_path = os.path.abspath(djvu_path)
if not os.path.exists(djvu_path):
pywikibot.error('No such file or directory: ' + djvu_path)
return
if os.path.isdir(djvu_path):
djvu_path = os.path.join(djvu_path, index)
# Check the djvu file exists and, if so, create the DjVuFile wrapper.
djvu = DjVuFile(djvu_path)
if not djvu.has_text():
pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
return
# Parse pages param.
pages = pages.split(',')
for i, page_interval in enumerate(pages):
start, sep, end = page_interval.partition('-')
start = int(start or 1)
end = int(end or djvu.number_of_images()) if sep else start
pages[i] = (start, end)
site = pywikibot.Site()
if not site.has_extension('ProofreadPage'):
pywikibot.error('Site {} must have ProofreadPage extension.'
.format(site))
return
index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns)
if not index_page.exists():
raise NoPageError(index)
pywikibot.output('uploading text from {} to {}'
.format(djvu.file, index_page.title(as_link=True)))
bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options)
bot.run() |
<|file_name|>djvutext.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
- path to a file name
- dir where a djvu file name as index is located
optional, by default is current dir '.'
-pages:<start>-<end>,...<start>-<end>,<start>-<end>
Page range to upload;
optional, start=1, end=djvu file number of images.
Page ranges can be specified as:
A-B -> pages A until B
A- -> pages A until number of images
A -> just page A
-B -> pages 1 until B
This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`.
The following options can be set within a settings file which is scripts.ini
by default:
-summary: custom edit summary.
Use quotes if edit summary contains spaces.
-force overwrites existing text
optional, default False
-always do not bother asking to confirm any of the changes.
"""
#
# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
import os.path
from typing import Optional
import pywikibot
from pywikibot import i18n
from pywikibot.bot import SingleSiteBot
from pywikibot.exceptions import NoPageError
from pywikibot.proofreadpage import ProofreadPage
from pywikibot.tools.djvu import DjVuFile
class DjVuTextBot(SingleSiteBot):
"""
A bot that uploads text-layer from djvu files to Page:namespace.
Works only on sites with Proofread Page extension installed.
.. versionchanged:: 7.0
CheckerBot is a ConfigParserBot
"""
update_options = {
'force': False,
'summary': '',
}
def __init__(
self,
djvu,
index,
pages: Optional[tuple] = None,
**kwargs
) -> None:
"""
Initializer.
:param djvu: djvu from where to fetch the text layer
:type djvu: DjVuFile object
:param index: index page in the Index: namespace
:type index: Page object
:param pages: page interval to upload (start, end)
"""
super().__init__(**kwargs)
self._djvu = djvu
self._index = index
self._prefix = self._index.title(with_ns=False)
self._page_ns = self.site._proofread_page_ns.custom_name
if not pages:
<|fim_middle|>
else:
self._pages = pages
# Get edit summary message if it's empty.
if not self.opt.summary:
self.opt.summary = i18n.twtranslate(self._index.site,
'djvutext-creating')
def page_number_gen(self):
"""Generate pages numbers from specified page intervals."""
last = 0
for start, end in sorted(self._pages):
start = max(last, start)
last = end + 1
yield from range(start, last)
@property
def generator(self):
"""Generate pages from specified page interval."""
for page_number in self.page_number_gen():
title = '{page_ns}:{prefix}/{number}'.format(
page_ns=self._page_ns,
prefix=self._prefix,
number=page_number)
page = ProofreadPage(self._index.site, title)
page.page_number = page_number # remember page number in djvu file
yield page
def treat(self, page) -> None:
"""Process one page."""
old_text = page.text
# Overwrite body of the page with content from djvu
page.body = self._djvu.get_page(page.page_number)
new_text = page.text
if page.exists() and not self.opt.force:
pywikibot.output(
'Page {} already exists, not adding!\n'
'Use -force option to overwrite the output page.'
.format(page))
else:
self.userPut(page, old_text, new_text, summary=self.opt.summary)
def main(*args: str) -> None:
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
index = None
djvu_path = '.' # default djvu file directory
pages = '1-'
options = {}
# Parse command line arguments.
local_args = pywikibot.handle_args(args)
for arg in local_args:
opt, _, value = arg.partition(':')
if opt == '-index':
index = value
elif opt == '-djvu':
djvu_path = value
elif opt == '-pages':
pages = value
elif opt == '-summary':
options['summary'] = value
elif opt in ('-force', '-always'):
options[opt[1:]] = True
else:
pywikibot.output('Unknown argument ' + arg)
# index is mandatory.
if not index:
pywikibot.bot.suggest_help(missing_parameters=['-index'])
return
# If djvu_path is not a file, build djvu_path from dir+index.
djvu_path = os.path.expanduser(djvu_path)
djvu_path = os.path.abspath(djvu_path)
if not os.path.exists(djvu_path):
pywikibot.error('No such file or directory: ' + djvu_path)
return
if os.path.isdir(djvu_path):
djvu_path = os.path.join(djvu_path, index)
# Check the djvu file exists and, if so, create the DjVuFile wrapper.
djvu = DjVuFile(djvu_path)
if not djvu.has_text():
pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
return
# Parse pages param.
pages = pages.split(',')
for i, page_interval in enumerate(pages):
start, sep, end = page_interval.partition('-')
start = int(start or 1)
end = int(end or djvu.number_of_images()) if sep else start
pages[i] = (start, end)
site = pywikibot.Site()
if not site.has_extension('ProofreadPage'):
pywikibot.error('Site {} must have ProofreadPage extension.'
.format(site))
return
index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns)
if not index_page.exists():
raise NoPageError(index)
pywikibot.output('uploading text from {} to {}'
.format(djvu.file, index_page.title(as_link=True)))
bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options)
bot.run()
if __name__ == '__main__':
try:
main()
except Exception:
pywikibot.error('Fatal error:', exc_info=True)
<|fim▁end|> | self._pages = (1, self._djvu.number_of_images()) |
<|file_name|>djvutext.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
- path to a file name
- dir where a djvu file name as index is located
optional, by default is current dir '.'
-pages:<start>-<end>,...<start>-<end>,<start>-<end>
Page range to upload;
optional, start=1, end=djvu file number of images.
Page ranges can be specified as:
A-B -> pages A until B
A- -> pages A until number of images
A -> just page A
-B -> pages 1 until B
This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`.
The following options can be set within a settings file which is scripts.ini
by default:
-summary: custom edit summary.
Use quotes if edit summary contains spaces.
-force overwrites existing text
optional, default False
-always do not bother asking to confirm any of the changes.
"""
#
# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
import os.path
from typing import Optional
import pywikibot
from pywikibot import i18n
from pywikibot.bot import SingleSiteBot
from pywikibot.exceptions import NoPageError
from pywikibot.proofreadpage import ProofreadPage
from pywikibot.tools.djvu import DjVuFile
class DjVuTextBot(SingleSiteBot):
"""
A bot that uploads text-layer from djvu files to Page:namespace.
Works only on sites with Proofread Page extension installed.
.. versionchanged:: 7.0
CheckerBot is a ConfigParserBot
"""
update_options = {
'force': False,
'summary': '',
}
def __init__(
self,
djvu,
index,
pages: Optional[tuple] = None,
**kwargs
) -> None:
"""
Initializer.
:param djvu: djvu from where to fetch the text layer
:type djvu: DjVuFile object
:param index: index page in the Index: namespace
:type index: Page object
:param pages: page interval to upload (start, end)
"""
super().__init__(**kwargs)
self._djvu = djvu
self._index = index
self._prefix = self._index.title(with_ns=False)
self._page_ns = self.site._proofread_page_ns.custom_name
if not pages:
self._pages = (1, self._djvu.number_of_images())
else:
<|fim_middle|>
# Get edit summary message if it's empty.
if not self.opt.summary:
self.opt.summary = i18n.twtranslate(self._index.site,
'djvutext-creating')
def page_number_gen(self):
"""Generate pages numbers from specified page intervals."""
last = 0
for start, end in sorted(self._pages):
start = max(last, start)
last = end + 1
yield from range(start, last)
@property
def generator(self):
"""Generate pages from specified page interval."""
for page_number in self.page_number_gen():
title = '{page_ns}:{prefix}/{number}'.format(
page_ns=self._page_ns,
prefix=self._prefix,
number=page_number)
page = ProofreadPage(self._index.site, title)
page.page_number = page_number # remember page number in djvu file
yield page
def treat(self, page) -> None:
"""Process one page."""
old_text = page.text
# Overwrite body of the page with content from djvu
page.body = self._djvu.get_page(page.page_number)
new_text = page.text
if page.exists() and not self.opt.force:
pywikibot.output(
'Page {} already exists, not adding!\n'
'Use -force option to overwrite the output page.'
.format(page))
else:
self.userPut(page, old_text, new_text, summary=self.opt.summary)
def main(*args: str) -> None:
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
index = None
djvu_path = '.' # default djvu file directory
pages = '1-'
options = {}
# Parse command line arguments.
local_args = pywikibot.handle_args(args)
for arg in local_args:
opt, _, value = arg.partition(':')
if opt == '-index':
index = value
elif opt == '-djvu':
djvu_path = value
elif opt == '-pages':
pages = value
elif opt == '-summary':
options['summary'] = value
elif opt in ('-force', '-always'):
options[opt[1:]] = True
else:
pywikibot.output('Unknown argument ' + arg)
# index is mandatory.
if not index:
pywikibot.bot.suggest_help(missing_parameters=['-index'])
return
# If djvu_path is not a file, build djvu_path from dir+index.
djvu_path = os.path.expanduser(djvu_path)
djvu_path = os.path.abspath(djvu_path)
if not os.path.exists(djvu_path):
pywikibot.error('No such file or directory: ' + djvu_path)
return
if os.path.isdir(djvu_path):
djvu_path = os.path.join(djvu_path, index)
# Check the djvu file exists and, if so, create the DjVuFile wrapper.
djvu = DjVuFile(djvu_path)
if not djvu.has_text():
pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
return
# Parse pages param.
pages = pages.split(',')
for i, page_interval in enumerate(pages):
start, sep, end = page_interval.partition('-')
start = int(start or 1)
end = int(end or djvu.number_of_images()) if sep else start
pages[i] = (start, end)
site = pywikibot.Site()
if not site.has_extension('ProofreadPage'):
pywikibot.error('Site {} must have ProofreadPage extension.'
.format(site))
return
index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns)
if not index_page.exists():
raise NoPageError(index)
pywikibot.output('uploading text from {} to {}'
.format(djvu.file, index_page.title(as_link=True)))
bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options)
bot.run()
if __name__ == '__main__':
try:
main()
except Exception:
pywikibot.error('Fatal error:', exc_info=True)
<|fim▁end|> | self._pages = pages |
<|file_name|>djvutext.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
- path to a file name
- dir where a djvu file name as index is located
optional, by default is current dir '.'
-pages:<start>-<end>,...<start>-<end>,<start>-<end>
Page range to upload;
optional, start=1, end=djvu file number of images.
Page ranges can be specified as:
A-B -> pages A until B
A- -> pages A until number of images
A -> just page A
-B -> pages 1 until B
This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`.
The following options can be set within a settings file which is scripts.ini
by default:
-summary: custom edit summary.
Use quotes if edit summary contains spaces.
-force overwrites existing text
optional, default False
-always do not bother asking to confirm any of the changes.
"""
#
# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
import os.path
from typing import Optional
import pywikibot
from pywikibot import i18n
from pywikibot.bot import SingleSiteBot
from pywikibot.exceptions import NoPageError
from pywikibot.proofreadpage import ProofreadPage
from pywikibot.tools.djvu import DjVuFile
class DjVuTextBot(SingleSiteBot):
"""
A bot that uploads text-layer from djvu files to Page:namespace.
Works only on sites with Proofread Page extension installed.
.. versionchanged:: 7.0
CheckerBot is a ConfigParserBot
"""
update_options = {
'force': False,
'summary': '',
}
def __init__(
self,
djvu,
index,
pages: Optional[tuple] = None,
**kwargs
) -> None:
"""
Initializer.
:param djvu: djvu from where to fetch the text layer
:type djvu: DjVuFile object
:param index: index page in the Index: namespace
:type index: Page object
:param pages: page interval to upload (start, end)
"""
super().__init__(**kwargs)
self._djvu = djvu
self._index = index
self._prefix = self._index.title(with_ns=False)
self._page_ns = self.site._proofread_page_ns.custom_name
if not pages:
self._pages = (1, self._djvu.number_of_images())
else:
self._pages = pages
# Get edit summary message if it's empty.
if not self.opt.summary:
<|fim_middle|>
def page_number_gen(self):
"""Generate pages numbers from specified page intervals."""
last = 0
for start, end in sorted(self._pages):
start = max(last, start)
last = end + 1
yield from range(start, last)
@property
def generator(self):
"""Generate pages from specified page interval."""
for page_number in self.page_number_gen():
title = '{page_ns}:{prefix}/{number}'.format(
page_ns=self._page_ns,
prefix=self._prefix,
number=page_number)
page = ProofreadPage(self._index.site, title)
page.page_number = page_number # remember page number in djvu file
yield page
def treat(self, page) -> None:
"""Process one page."""
old_text = page.text
# Overwrite body of the page with content from djvu
page.body = self._djvu.get_page(page.page_number)
new_text = page.text
if page.exists() and not self.opt.force:
pywikibot.output(
'Page {} already exists, not adding!\n'
'Use -force option to overwrite the output page.'
.format(page))
else:
self.userPut(page, old_text, new_text, summary=self.opt.summary)
def main(*args: str) -> None:
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
index = None
djvu_path = '.' # default djvu file directory
pages = '1-'
options = {}
# Parse command line arguments.
local_args = pywikibot.handle_args(args)
for arg in local_args:
opt, _, value = arg.partition(':')
if opt == '-index':
index = value
elif opt == '-djvu':
djvu_path = value
elif opt == '-pages':
pages = value
elif opt == '-summary':
options['summary'] = value
elif opt in ('-force', '-always'):
options[opt[1:]] = True
else:
pywikibot.output('Unknown argument ' + arg)
# index is mandatory.
if not index:
pywikibot.bot.suggest_help(missing_parameters=['-index'])
return
# If djvu_path is not a file, build djvu_path from dir+index.
djvu_path = os.path.expanduser(djvu_path)
djvu_path = os.path.abspath(djvu_path)
if not os.path.exists(djvu_path):
pywikibot.error('No such file or directory: ' + djvu_path)
return
if os.path.isdir(djvu_path):
djvu_path = os.path.join(djvu_path, index)
# Check the djvu file exists and, if so, create the DjVuFile wrapper.
djvu = DjVuFile(djvu_path)
if not djvu.has_text():
pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
return
# Parse pages param.
pages = pages.split(',')
for i, page_interval in enumerate(pages):
start, sep, end = page_interval.partition('-')
start = int(start or 1)
end = int(end or djvu.number_of_images()) if sep else start
pages[i] = (start, end)
site = pywikibot.Site()
if not site.has_extension('ProofreadPage'):
pywikibot.error('Site {} must have ProofreadPage extension.'
.format(site))
return
index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns)
if not index_page.exists():
raise NoPageError(index)
pywikibot.output('uploading text from {} to {}'
.format(djvu.file, index_page.title(as_link=True)))
bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options)
bot.run()
if __name__ == '__main__':
try:
main()
except Exception:
pywikibot.error('Fatal error:', exc_info=True)
<|fim▁end|> | self.opt.summary = i18n.twtranslate(self._index.site,
'djvutext-creating') |
<|file_name|>djvutext.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
- path to a file name
- dir where a djvu file name as index is located
optional, by default is current dir '.'
-pages:<start>-<end>,...<start>-<end>,<start>-<end>
Page range to upload;
optional, start=1, end=djvu file number of images.
Page ranges can be specified as:
A-B -> pages A until B
A- -> pages A until number of images
A -> just page A
-B -> pages 1 until B
This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`.
The following options can be set within a settings file which is scripts.ini
by default:
-summary: custom edit summary.
Use quotes if edit summary contains spaces.
-force overwrites existing text
optional, default False
-always do not bother asking to confirm any of the changes.
"""
#
# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
import os.path
from typing import Optional
import pywikibot
from pywikibot import i18n
from pywikibot.bot import SingleSiteBot
from pywikibot.exceptions import NoPageError
from pywikibot.proofreadpage import ProofreadPage
from pywikibot.tools.djvu import DjVuFile
class DjVuTextBot(SingleSiteBot):
"""
A bot that uploads text-layer from djvu files to Page:namespace.
Works only on sites with Proofread Page extension installed.
.. versionchanged:: 7.0
CheckerBot is a ConfigParserBot
"""
update_options = {
'force': False,
'summary': '',
}
def __init__(
self,
djvu,
index,
pages: Optional[tuple] = None,
**kwargs
) -> None:
"""
Initializer.
:param djvu: djvu from where to fetch the text layer
:type djvu: DjVuFile object
:param index: index page in the Index: namespace
:type index: Page object
:param pages: page interval to upload (start, end)
"""
super().__init__(**kwargs)
self._djvu = djvu
self._index = index
self._prefix = self._index.title(with_ns=False)
self._page_ns = self.site._proofread_page_ns.custom_name
if not pages:
self._pages = (1, self._djvu.number_of_images())
else:
self._pages = pages
# Get edit summary message if it's empty.
if not self.opt.summary:
self.opt.summary = i18n.twtranslate(self._index.site,
'djvutext-creating')
def page_number_gen(self):
"""Generate pages numbers from specified page intervals."""
last = 0
for start, end in sorted(self._pages):
start = max(last, start)
last = end + 1
yield from range(start, last)
@property
def generator(self):
"""Generate pages from specified page interval."""
for page_number in self.page_number_gen():
title = '{page_ns}:{prefix}/{number}'.format(
page_ns=self._page_ns,
prefix=self._prefix,
number=page_number)
page = ProofreadPage(self._index.site, title)
page.page_number = page_number # remember page number in djvu file
yield page
def treat(self, page) -> None:
"""Process one page."""
old_text = page.text
# Overwrite body of the page with content from djvu
page.body = self._djvu.get_page(page.page_number)
new_text = page.text
if page.exists() and not self.opt.force:
<|fim_middle|>
else:
self.userPut(page, old_text, new_text, summary=self.opt.summary)
def main(*args: str) -> None:
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
index = None
djvu_path = '.' # default djvu file directory
pages = '1-'
options = {}
# Parse command line arguments.
local_args = pywikibot.handle_args(args)
for arg in local_args:
opt, _, value = arg.partition(':')
if opt == '-index':
index = value
elif opt == '-djvu':
djvu_path = value
elif opt == '-pages':
pages = value
elif opt == '-summary':
options['summary'] = value
elif opt in ('-force', '-always'):
options[opt[1:]] = True
else:
pywikibot.output('Unknown argument ' + arg)
# index is mandatory.
if not index:
pywikibot.bot.suggest_help(missing_parameters=['-index'])
return
# If djvu_path is not a file, build djvu_path from dir+index.
djvu_path = os.path.expanduser(djvu_path)
djvu_path = os.path.abspath(djvu_path)
if not os.path.exists(djvu_path):
pywikibot.error('No such file or directory: ' + djvu_path)
return
if os.path.isdir(djvu_path):
djvu_path = os.path.join(djvu_path, index)
# Check the djvu file exists and, if so, create the DjVuFile wrapper.
djvu = DjVuFile(djvu_path)
if not djvu.has_text():
pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
return
# Parse pages param.
pages = pages.split(',')
for i, page_interval in enumerate(pages):
start, sep, end = page_interval.partition('-')
start = int(start or 1)
end = int(end or djvu.number_of_images()) if sep else start
pages[i] = (start, end)
site = pywikibot.Site()
if not site.has_extension('ProofreadPage'):
pywikibot.error('Site {} must have ProofreadPage extension.'
.format(site))
return
index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns)
if not index_page.exists():
raise NoPageError(index)
pywikibot.output('uploading text from {} to {}'
.format(djvu.file, index_page.title(as_link=True)))
bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options)
bot.run()
if __name__ == '__main__':
try:
main()
except Exception:
pywikibot.error('Fatal error:', exc_info=True)
<|fim▁end|> | pywikibot.output(
'Page {} already exists, not adding!\n'
'Use -force option to overwrite the output page.'
.format(page)) |
<|file_name|>djvutext.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
- path to a file name
- dir where a djvu file name as index is located
optional, by default is current dir '.'
-pages:<start>-<end>,...<start>-<end>,<start>-<end>
Page range to upload;
optional, start=1, end=djvu file number of images.
Page ranges can be specified as:
A-B -> pages A until B
A- -> pages A until number of images
A -> just page A
-B -> pages 1 until B
This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`.
The following options can be set within a settings file which is scripts.ini
by default:
-summary: custom edit summary.
Use quotes if edit summary contains spaces.
-force overwrites existing text
optional, default False
-always do not bother asking to confirm any of the changes.
"""
#
# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
import os.path
from typing import Optional
import pywikibot
from pywikibot import i18n
from pywikibot.bot import SingleSiteBot
from pywikibot.exceptions import NoPageError
from pywikibot.proofreadpage import ProofreadPage
from pywikibot.tools.djvu import DjVuFile
class DjVuTextBot(SingleSiteBot):
"""
A bot that uploads text-layer from djvu files to Page:namespace.
Works only on sites with Proofread Page extension installed.
.. versionchanged:: 7.0
CheckerBot is a ConfigParserBot
"""
update_options = {
'force': False,
'summary': '',
}
def __init__(
self,
djvu,
index,
pages: Optional[tuple] = None,
**kwargs
) -> None:
"""
Initializer.
:param djvu: djvu from where to fetch the text layer
:type djvu: DjVuFile object
:param index: index page in the Index: namespace
:type index: Page object
:param pages: page interval to upload (start, end)
"""
super().__init__(**kwargs)
self._djvu = djvu
self._index = index
self._prefix = self._index.title(with_ns=False)
self._page_ns = self.site._proofread_page_ns.custom_name
if not pages:
self._pages = (1, self._djvu.number_of_images())
else:
self._pages = pages
# Get edit summary message if it's empty.
if not self.opt.summary:
self.opt.summary = i18n.twtranslate(self._index.site,
'djvutext-creating')
def page_number_gen(self):
"""Generate pages numbers from specified page intervals."""
last = 0
for start, end in sorted(self._pages):
start = max(last, start)
last = end + 1
yield from range(start, last)
@property
def generator(self):
"""Generate pages from specified page interval."""
for page_number in self.page_number_gen():
title = '{page_ns}:{prefix}/{number}'.format(
page_ns=self._page_ns,
prefix=self._prefix,
number=page_number)
page = ProofreadPage(self._index.site, title)
page.page_number = page_number # remember page number in djvu file
yield page
def treat(self, page) -> None:
"""Process one page."""
old_text = page.text
# Overwrite body of the page with content from djvu
page.body = self._djvu.get_page(page.page_number)
new_text = page.text
if page.exists() and not self.opt.force:
pywikibot.output(
'Page {} already exists, not adding!\n'
'Use -force option to overwrite the output page.'
.format(page))
else:
<|fim_middle|>
def main(*args: str) -> None:
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
index = None
djvu_path = '.' # default djvu file directory
pages = '1-'
options = {}
# Parse command line arguments.
local_args = pywikibot.handle_args(args)
for arg in local_args:
opt, _, value = arg.partition(':')
if opt == '-index':
index = value
elif opt == '-djvu':
djvu_path = value
elif opt == '-pages':
pages = value
elif opt == '-summary':
options['summary'] = value
elif opt in ('-force', '-always'):
options[opt[1:]] = True
else:
pywikibot.output('Unknown argument ' + arg)
# index is mandatory.
if not index:
pywikibot.bot.suggest_help(missing_parameters=['-index'])
return
# If djvu_path is not a file, build djvu_path from dir+index.
djvu_path = os.path.expanduser(djvu_path)
djvu_path = os.path.abspath(djvu_path)
if not os.path.exists(djvu_path):
pywikibot.error('No such file or directory: ' + djvu_path)
return
if os.path.isdir(djvu_path):
djvu_path = os.path.join(djvu_path, index)
# Check the djvu file exists and, if so, create the DjVuFile wrapper.
djvu = DjVuFile(djvu_path)
if not djvu.has_text():
pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
return
# Parse pages param.
pages = pages.split(',')
for i, page_interval in enumerate(pages):
start, sep, end = page_interval.partition('-')
start = int(start or 1)
end = int(end or djvu.number_of_images()) if sep else start
pages[i] = (start, end)
site = pywikibot.Site()
if not site.has_extension('ProofreadPage'):
pywikibot.error('Site {} must have ProofreadPage extension.'
.format(site))
return
index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns)
if not index_page.exists():
raise NoPageError(index)
pywikibot.output('uploading text from {} to {}'
.format(djvu.file, index_page.title(as_link=True)))
bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options)
bot.run()
if __name__ == '__main__':
try:
main()
except Exception:
pywikibot.error('Fatal error:', exc_info=True)
<|fim▁end|> | self.userPut(page, old_text, new_text, summary=self.opt.summary) |
<|file_name|>djvutext.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
- path to a file name
- dir where a djvu file name as index is located
optional, by default is current dir '.'
-pages:<start>-<end>,...<start>-<end>,<start>-<end>
Page range to upload;
optional, start=1, end=djvu file number of images.
Page ranges can be specified as:
A-B -> pages A until B
A- -> pages A until number of images
A -> just page A
-B -> pages 1 until B
This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`.
The following options can be set within a settings file which is scripts.ini
by default:
-summary: custom edit summary.
Use quotes if edit summary contains spaces.
-force overwrites existing text
optional, default False
-always do not bother asking to confirm any of the changes.
"""
#
# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
import os.path
from typing import Optional
import pywikibot
from pywikibot import i18n
from pywikibot.bot import SingleSiteBot
from pywikibot.exceptions import NoPageError
from pywikibot.proofreadpage import ProofreadPage
from pywikibot.tools.djvu import DjVuFile
class DjVuTextBot(SingleSiteBot):
"""
A bot that uploads text-layer from djvu files to Page:namespace.
Works only on sites with Proofread Page extension installed.
.. versionchanged:: 7.0
CheckerBot is a ConfigParserBot
"""
update_options = {
'force': False,
'summary': '',
}
def __init__(
self,
djvu,
index,
pages: Optional[tuple] = None,
**kwargs
) -> None:
"""
Initializer.
:param djvu: djvu from where to fetch the text layer
:type djvu: DjVuFile object
:param index: index page in the Index: namespace
:type index: Page object
:param pages: page interval to upload (start, end)
"""
super().__init__(**kwargs)
self._djvu = djvu
self._index = index
self._prefix = self._index.title(with_ns=False)
self._page_ns = self.site._proofread_page_ns.custom_name
if not pages:
self._pages = (1, self._djvu.number_of_images())
else:
self._pages = pages
# Get edit summary message if it's empty.
if not self.opt.summary:
self.opt.summary = i18n.twtranslate(self._index.site,
'djvutext-creating')
def page_number_gen(self):
"""Generate pages numbers from specified page intervals."""
last = 0
for start, end in sorted(self._pages):
start = max(last, start)
last = end + 1
yield from range(start, last)
@property
def generator(self):
"""Generate pages from specified page interval."""
for page_number in self.page_number_gen():
title = '{page_ns}:{prefix}/{number}'.format(
page_ns=self._page_ns,
prefix=self._prefix,
number=page_number)
page = ProofreadPage(self._index.site, title)
page.page_number = page_number # remember page number in djvu file
yield page
def treat(self, page) -> None:
"""Process one page."""
old_text = page.text
# Overwrite body of the page with content from djvu
page.body = self._djvu.get_page(page.page_number)
new_text = page.text
if page.exists() and not self.opt.force:
pywikibot.output(
'Page {} already exists, not adding!\n'
'Use -force option to overwrite the output page.'
.format(page))
else:
self.userPut(page, old_text, new_text, summary=self.opt.summary)
def main(*args: str) -> None:
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
index = None
djvu_path = '.' # default djvu file directory
pages = '1-'
options = {}
# Parse command line arguments.
local_args = pywikibot.handle_args(args)
for arg in local_args:
opt, _, value = arg.partition(':')
if opt == '-index':
<|fim_middle|>
elif opt == '-djvu':
djvu_path = value
elif opt == '-pages':
pages = value
elif opt == '-summary':
options['summary'] = value
elif opt in ('-force', '-always'):
options[opt[1:]] = True
else:
pywikibot.output('Unknown argument ' + arg)
# index is mandatory.
if not index:
pywikibot.bot.suggest_help(missing_parameters=['-index'])
return
# If djvu_path is not a file, build djvu_path from dir+index.
djvu_path = os.path.expanduser(djvu_path)
djvu_path = os.path.abspath(djvu_path)
if not os.path.exists(djvu_path):
pywikibot.error('No such file or directory: ' + djvu_path)
return
if os.path.isdir(djvu_path):
djvu_path = os.path.join(djvu_path, index)
# Check the djvu file exists and, if so, create the DjVuFile wrapper.
djvu = DjVuFile(djvu_path)
if not djvu.has_text():
pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
return
# Parse pages param.
pages = pages.split(',')
for i, page_interval in enumerate(pages):
start, sep, end = page_interval.partition('-')
start = int(start or 1)
end = int(end or djvu.number_of_images()) if sep else start
pages[i] = (start, end)
site = pywikibot.Site()
if not site.has_extension('ProofreadPage'):
pywikibot.error('Site {} must have ProofreadPage extension.'
.format(site))
return
index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns)
if not index_page.exists():
raise NoPageError(index)
pywikibot.output('uploading text from {} to {}'
.format(djvu.file, index_page.title(as_link=True)))
bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options)
bot.run()
if __name__ == '__main__':
try:
main()
except Exception:
pywikibot.error('Fatal error:', exc_info=True)
<|fim▁end|> | index = value |
<|file_name|>djvutext.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
- path to a file name
- dir where a djvu file name as index is located
optional, by default is current dir '.'
-pages:<start>-<end>,...<start>-<end>,<start>-<end>
Page range to upload;
optional, start=1, end=djvu file number of images.
Page ranges can be specified as:
A-B -> pages A until B
A- -> pages A until number of images
A -> just page A
-B -> pages 1 until B
This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`.
The following options can be set within a settings file which is scripts.ini
by default:
-summary: custom edit summary.
Use quotes if edit summary contains spaces.
-force overwrites existing text
optional, default False
-always do not bother asking to confirm any of the changes.
"""
#
# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
import os.path
from typing import Optional
import pywikibot
from pywikibot import i18n
from pywikibot.bot import SingleSiteBot
from pywikibot.exceptions import NoPageError
from pywikibot.proofreadpage import ProofreadPage
from pywikibot.tools.djvu import DjVuFile
class DjVuTextBot(SingleSiteBot):
"""
A bot that uploads text-layer from djvu files to Page:namespace.
Works only on sites with Proofread Page extension installed.
.. versionchanged:: 7.0
CheckerBot is a ConfigParserBot
"""
update_options = {
'force': False,
'summary': '',
}
def __init__(
self,
djvu,
index,
pages: Optional[tuple] = None,
**kwargs
) -> None:
"""
Initializer.
:param djvu: djvu from where to fetch the text layer
:type djvu: DjVuFile object
:param index: index page in the Index: namespace
:type index: Page object
:param pages: page interval to upload (start, end)
"""
super().__init__(**kwargs)
self._djvu = djvu
self._index = index
self._prefix = self._index.title(with_ns=False)
self._page_ns = self.site._proofread_page_ns.custom_name
if not pages:
self._pages = (1, self._djvu.number_of_images())
else:
self._pages = pages
# Get edit summary message if it's empty.
if not self.opt.summary:
self.opt.summary = i18n.twtranslate(self._index.site,
'djvutext-creating')
def page_number_gen(self):
"""Generate pages numbers from specified page intervals."""
last = 0
for start, end in sorted(self._pages):
start = max(last, start)
last = end + 1
yield from range(start, last)
@property
def generator(self):
"""Generate pages from specified page interval."""
for page_number in self.page_number_gen():
title = '{page_ns}:{prefix}/{number}'.format(
page_ns=self._page_ns,
prefix=self._prefix,
number=page_number)
page = ProofreadPage(self._index.site, title)
page.page_number = page_number # remember page number in djvu file
yield page
def treat(self, page) -> None:
"""Process one page."""
old_text = page.text
# Overwrite body of the page with content from djvu
page.body = self._djvu.get_page(page.page_number)
new_text = page.text
if page.exists() and not self.opt.force:
pywikibot.output(
'Page {} already exists, not adding!\n'
'Use -force option to overwrite the output page.'
.format(page))
else:
self.userPut(page, old_text, new_text, summary=self.opt.summary)
def main(*args: str) -> None:
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
index = None
djvu_path = '.' # default djvu file directory
pages = '1-'
options = {}
# Parse command line arguments.
local_args = pywikibot.handle_args(args)
for arg in local_args:
opt, _, value = arg.partition(':')
if opt == '-index':
index = value
elif opt == '-djvu':
<|fim_middle|>
elif opt == '-pages':
pages = value
elif opt == '-summary':
options['summary'] = value
elif opt in ('-force', '-always'):
options[opt[1:]] = True
else:
pywikibot.output('Unknown argument ' + arg)
# index is mandatory.
if not index:
pywikibot.bot.suggest_help(missing_parameters=['-index'])
return
# If djvu_path is not a file, build djvu_path from dir+index.
djvu_path = os.path.expanduser(djvu_path)
djvu_path = os.path.abspath(djvu_path)
if not os.path.exists(djvu_path):
pywikibot.error('No such file or directory: ' + djvu_path)
return
if os.path.isdir(djvu_path):
djvu_path = os.path.join(djvu_path, index)
# Check the djvu file exists and, if so, create the DjVuFile wrapper.
djvu = DjVuFile(djvu_path)
if not djvu.has_text():
pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
return
# Parse pages param.
pages = pages.split(',')
for i, page_interval in enumerate(pages):
start, sep, end = page_interval.partition('-')
start = int(start or 1)
end = int(end or djvu.number_of_images()) if sep else start
pages[i] = (start, end)
site = pywikibot.Site()
if not site.has_extension('ProofreadPage'):
pywikibot.error('Site {} must have ProofreadPage extension.'
.format(site))
return
index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns)
if not index_page.exists():
raise NoPageError(index)
pywikibot.output('uploading text from {} to {}'
.format(djvu.file, index_page.title(as_link=True)))
bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options)
bot.run()
if __name__ == '__main__':
try:
main()
except Exception:
pywikibot.error('Fatal error:', exc_info=True)
<|fim▁end|> | djvu_path = value |
<|file_name|>djvutext.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
- path to a file name
- dir where a djvu file name as index is located
optional, by default is current dir '.'
-pages:<start>-<end>,...<start>-<end>,<start>-<end>
Page range to upload;
optional, start=1, end=djvu file number of images.
Page ranges can be specified as:
A-B -> pages A until B
A- -> pages A until number of images
A -> just page A
-B -> pages 1 until B
This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`.
The following options can be set within a settings file which is scripts.ini
by default:
-summary: custom edit summary.
Use quotes if edit summary contains spaces.
-force overwrites existing text
optional, default False
-always do not bother asking to confirm any of the changes.
"""
#
# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
import os.path
from typing import Optional
import pywikibot
from pywikibot import i18n
from pywikibot.bot import SingleSiteBot
from pywikibot.exceptions import NoPageError
from pywikibot.proofreadpage import ProofreadPage
from pywikibot.tools.djvu import DjVuFile
class DjVuTextBot(SingleSiteBot):
"""
A bot that uploads text-layer from djvu files to Page:namespace.
Works only on sites with Proofread Page extension installed.
.. versionchanged:: 7.0
CheckerBot is a ConfigParserBot
"""
update_options = {
'force': False,
'summary': '',
}
def __init__(
self,
djvu,
index,
pages: Optional[tuple] = None,
**kwargs
) -> None:
"""
Initializer.
:param djvu: djvu from where to fetch the text layer
:type djvu: DjVuFile object
:param index: index page in the Index: namespace
:type index: Page object
:param pages: page interval to upload (start, end)
"""
super().__init__(**kwargs)
self._djvu = djvu
self._index = index
self._prefix = self._index.title(with_ns=False)
self._page_ns = self.site._proofread_page_ns.custom_name
if not pages:
self._pages = (1, self._djvu.number_of_images())
else:
self._pages = pages
# Get edit summary message if it's empty.
if not self.opt.summary:
self.opt.summary = i18n.twtranslate(self._index.site,
'djvutext-creating')
def page_number_gen(self):
"""Generate pages numbers from specified page intervals."""
last = 0
for start, end in sorted(self._pages):
start = max(last, start)
last = end + 1
yield from range(start, last)
@property
def generator(self):
"""Generate pages from specified page interval."""
for page_number in self.page_number_gen():
title = '{page_ns}:{prefix}/{number}'.format(
page_ns=self._page_ns,
prefix=self._prefix,
number=page_number)
page = ProofreadPage(self._index.site, title)
page.page_number = page_number # remember page number in djvu file
yield page
def treat(self, page) -> None:
"""Process one page."""
old_text = page.text
# Overwrite body of the page with content from djvu
page.body = self._djvu.get_page(page.page_number)
new_text = page.text
if page.exists() and not self.opt.force:
pywikibot.output(
'Page {} already exists, not adding!\n'
'Use -force option to overwrite the output page.'
.format(page))
else:
self.userPut(page, old_text, new_text, summary=self.opt.summary)
def main(*args: str) -> None:
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
index = None
djvu_path = '.' # default djvu file directory
pages = '1-'
options = {}
# Parse command line arguments.
local_args = pywikibot.handle_args(args)
for arg in local_args:
opt, _, value = arg.partition(':')
if opt == '-index':
index = value
elif opt == '-djvu':
djvu_path = value
elif opt == '-pages':
<|fim_middle|>
elif opt == '-summary':
options['summary'] = value
elif opt in ('-force', '-always'):
options[opt[1:]] = True
else:
pywikibot.output('Unknown argument ' + arg)
# index is mandatory.
if not index:
pywikibot.bot.suggest_help(missing_parameters=['-index'])
return
# If djvu_path is not a file, build djvu_path from dir+index.
djvu_path = os.path.expanduser(djvu_path)
djvu_path = os.path.abspath(djvu_path)
if not os.path.exists(djvu_path):
pywikibot.error('No such file or directory: ' + djvu_path)
return
if os.path.isdir(djvu_path):
djvu_path = os.path.join(djvu_path, index)
# Check the djvu file exists and, if so, create the DjVuFile wrapper.
djvu = DjVuFile(djvu_path)
if not djvu.has_text():
pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
return
# Parse pages param.
pages = pages.split(',')
for i, page_interval in enumerate(pages):
start, sep, end = page_interval.partition('-')
start = int(start or 1)
end = int(end or djvu.number_of_images()) if sep else start
pages[i] = (start, end)
site = pywikibot.Site()
if not site.has_extension('ProofreadPage'):
pywikibot.error('Site {} must have ProofreadPage extension.'
.format(site))
return
index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns)
if not index_page.exists():
raise NoPageError(index)
pywikibot.output('uploading text from {} to {}'
.format(djvu.file, index_page.title(as_link=True)))
bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options)
bot.run()
if __name__ == '__main__':
try:
main()
except Exception:
pywikibot.error('Fatal error:', exc_info=True)
<|fim▁end|> | pages = value |
<|file_name|>djvutext.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
- path to a file name
- dir where a djvu file name as index is located
optional, by default is current dir '.'
-pages:<start>-<end>,...<start>-<end>,<start>-<end>
Page range to upload;
optional, start=1, end=djvu file number of images.
Page ranges can be specified as:
A-B -> pages A until B
A- -> pages A until number of images
A -> just page A
-B -> pages 1 until B
This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`.
The following options can be set within a settings file which is scripts.ini
by default:
-summary: custom edit summary.
Use quotes if edit summary contains spaces.
-force overwrites existing text
optional, default False
-always do not bother asking to confirm any of the changes.
"""
#
# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
import os.path
from typing import Optional
import pywikibot
from pywikibot import i18n
from pywikibot.bot import SingleSiteBot
from pywikibot.exceptions import NoPageError
from pywikibot.proofreadpage import ProofreadPage
from pywikibot.tools.djvu import DjVuFile
class DjVuTextBot(SingleSiteBot):
"""
A bot that uploads text-layer from djvu files to Page:namespace.
Works only on sites with Proofread Page extension installed.
.. versionchanged:: 7.0
CheckerBot is a ConfigParserBot
"""
update_options = {
'force': False,
'summary': '',
}
def __init__(
self,
djvu,
index,
pages: Optional[tuple] = None,
**kwargs
) -> None:
"""
Initializer.
:param djvu: djvu from where to fetch the text layer
:type djvu: DjVuFile object
:param index: index page in the Index: namespace
:type index: Page object
:param pages: page interval to upload (start, end)
"""
super().__init__(**kwargs)
self._djvu = djvu
self._index = index
self._prefix = self._index.title(with_ns=False)
self._page_ns = self.site._proofread_page_ns.custom_name
if not pages:
self._pages = (1, self._djvu.number_of_images())
else:
self._pages = pages
# Get edit summary message if it's empty.
if not self.opt.summary:
self.opt.summary = i18n.twtranslate(self._index.site,
'djvutext-creating')
def page_number_gen(self):
"""Generate pages numbers from specified page intervals."""
last = 0
for start, end in sorted(self._pages):
start = max(last, start)
last = end + 1
yield from range(start, last)
@property
def generator(self):
"""Generate pages from specified page interval."""
for page_number in self.page_number_gen():
title = '{page_ns}:{prefix}/{number}'.format(
page_ns=self._page_ns,
prefix=self._prefix,
number=page_number)
page = ProofreadPage(self._index.site, title)
page.page_number = page_number # remember page number in djvu file
yield page
def treat(self, page) -> None:
"""Process one page."""
old_text = page.text
# Overwrite body of the page with content from djvu
page.body = self._djvu.get_page(page.page_number)
new_text = page.text
if page.exists() and not self.opt.force:
pywikibot.output(
'Page {} already exists, not adding!\n'
'Use -force option to overwrite the output page.'
.format(page))
else:
self.userPut(page, old_text, new_text, summary=self.opt.summary)
def main(*args: str) -> None:
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
index = None
djvu_path = '.' # default djvu file directory
pages = '1-'
options = {}
# Parse command line arguments.
local_args = pywikibot.handle_args(args)
for arg in local_args:
opt, _, value = arg.partition(':')
if opt == '-index':
index = value
elif opt == '-djvu':
djvu_path = value
elif opt == '-pages':
pages = value
elif opt == '-summary':
<|fim_middle|>
elif opt in ('-force', '-always'):
options[opt[1:]] = True
else:
pywikibot.output('Unknown argument ' + arg)
# index is mandatory.
if not index:
pywikibot.bot.suggest_help(missing_parameters=['-index'])
return
# If djvu_path is not a file, build djvu_path from dir+index.
djvu_path = os.path.expanduser(djvu_path)
djvu_path = os.path.abspath(djvu_path)
if not os.path.exists(djvu_path):
pywikibot.error('No such file or directory: ' + djvu_path)
return
if os.path.isdir(djvu_path):
djvu_path = os.path.join(djvu_path, index)
# Check the djvu file exists and, if so, create the DjVuFile wrapper.
djvu = DjVuFile(djvu_path)
if not djvu.has_text():
pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
return
# Parse pages param.
pages = pages.split(',')
for i, page_interval in enumerate(pages):
start, sep, end = page_interval.partition('-')
start = int(start or 1)
end = int(end or djvu.number_of_images()) if sep else start
pages[i] = (start, end)
site = pywikibot.Site()
if not site.has_extension('ProofreadPage'):
pywikibot.error('Site {} must have ProofreadPage extension.'
.format(site))
return
index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns)
if not index_page.exists():
raise NoPageError(index)
pywikibot.output('uploading text from {} to {}'
.format(djvu.file, index_page.title(as_link=True)))
bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options)
bot.run()
if __name__ == '__main__':
try:
main()
except Exception:
pywikibot.error('Fatal error:', exc_info=True)
<|fim▁end|> | options['summary'] = value |
<|file_name|>djvutext.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
- path to a file name
- dir where a djvu file name as index is located
optional, by default is current dir '.'
-pages:<start>-<end>,...<start>-<end>,<start>-<end>
Page range to upload;
optional, start=1, end=djvu file number of images.
Page ranges can be specified as:
A-B -> pages A until B
A- -> pages A until number of images
A -> just page A
-B -> pages 1 until B
This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`.
The following options can be set within a settings file which is scripts.ini
by default:
-summary: custom edit summary.
Use quotes if edit summary contains spaces.
-force overwrites existing text
optional, default False
-always do not bother asking to confirm any of the changes.
"""
#
# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
import os.path
from typing import Optional
import pywikibot
from pywikibot import i18n
from pywikibot.bot import SingleSiteBot
from pywikibot.exceptions import NoPageError
from pywikibot.proofreadpage import ProofreadPage
from pywikibot.tools.djvu import DjVuFile
class DjVuTextBot(SingleSiteBot):
"""
A bot that uploads text-layer from djvu files to Page:namespace.
Works only on sites with Proofread Page extension installed.
.. versionchanged:: 7.0
CheckerBot is a ConfigParserBot
"""
update_options = {
'force': False,
'summary': '',
}
def __init__(
self,
djvu,
index,
pages: Optional[tuple] = None,
**kwargs
) -> None:
"""
Initializer.
:param djvu: djvu from where to fetch the text layer
:type djvu: DjVuFile object
:param index: index page in the Index: namespace
:type index: Page object
:param pages: page interval to upload (start, end)
"""
super().__init__(**kwargs)
self._djvu = djvu
self._index = index
self._prefix = self._index.title(with_ns=False)
self._page_ns = self.site._proofread_page_ns.custom_name
if not pages:
self._pages = (1, self._djvu.number_of_images())
else:
self._pages = pages
# Get edit summary message if it's empty.
if not self.opt.summary:
self.opt.summary = i18n.twtranslate(self._index.site,
'djvutext-creating')
def page_number_gen(self):
"""Generate pages numbers from specified page intervals."""
last = 0
for start, end in sorted(self._pages):
start = max(last, start)
last = end + 1
yield from range(start, last)
@property
def generator(self):
"""Generate pages from specified page interval."""
for page_number in self.page_number_gen():
title = '{page_ns}:{prefix}/{number}'.format(
page_ns=self._page_ns,
prefix=self._prefix,
number=page_number)
page = ProofreadPage(self._index.site, title)
page.page_number = page_number # remember page number in djvu file
yield page
def treat(self, page) -> None:
"""Process one page."""
old_text = page.text
# Overwrite body of the page with content from djvu
page.body = self._djvu.get_page(page.page_number)
new_text = page.text
if page.exists() and not self.opt.force:
pywikibot.output(
'Page {} already exists, not adding!\n'
'Use -force option to overwrite the output page.'
.format(page))
else:
self.userPut(page, old_text, new_text, summary=self.opt.summary)
def main(*args: str) -> None:
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
index = None
djvu_path = '.' # default djvu file directory
pages = '1-'
options = {}
# Parse command line arguments.
local_args = pywikibot.handle_args(args)
for arg in local_args:
opt, _, value = arg.partition(':')
if opt == '-index':
index = value
elif opt == '-djvu':
djvu_path = value
elif opt == '-pages':
pages = value
elif opt == '-summary':
options['summary'] = value
elif opt in ('-force', '-always'):
<|fim_middle|>
else:
pywikibot.output('Unknown argument ' + arg)
# index is mandatory.
if not index:
pywikibot.bot.suggest_help(missing_parameters=['-index'])
return
# If djvu_path is not a file, build djvu_path from dir+index.
djvu_path = os.path.expanduser(djvu_path)
djvu_path = os.path.abspath(djvu_path)
if not os.path.exists(djvu_path):
pywikibot.error('No such file or directory: ' + djvu_path)
return
if os.path.isdir(djvu_path):
djvu_path = os.path.join(djvu_path, index)
# Check the djvu file exists and, if so, create the DjVuFile wrapper.
djvu = DjVuFile(djvu_path)
if not djvu.has_text():
pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
return
# Parse pages param.
pages = pages.split(',')
for i, page_interval in enumerate(pages):
start, sep, end = page_interval.partition('-')
start = int(start or 1)
end = int(end or djvu.number_of_images()) if sep else start
pages[i] = (start, end)
site = pywikibot.Site()
if not site.has_extension('ProofreadPage'):
pywikibot.error('Site {} must have ProofreadPage extension.'
.format(site))
return
index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns)
if not index_page.exists():
raise NoPageError(index)
pywikibot.output('uploading text from {} to {}'
.format(djvu.file, index_page.title(as_link=True)))
bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options)
bot.run()
if __name__ == '__main__':
try:
main()
except Exception:
pywikibot.error('Fatal error:', exc_info=True)
<|fim▁end|> | options[opt[1:]] = True |
<|file_name|>djvutext.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
- path to a file name
- dir where a djvu file name as index is located
optional, by default is current dir '.'
-pages:<start>-<end>,...<start>-<end>,<start>-<end>
Page range to upload;
optional, start=1, end=djvu file number of images.
Page ranges can be specified as:
A-B -> pages A until B
A- -> pages A until number of images
A -> just page A
-B -> pages 1 until B
This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`.
The following options can be set within a settings file which is scripts.ini
by default:
-summary: custom edit summary.
Use quotes if edit summary contains spaces.
-force overwrites existing text
optional, default False
-always do not bother asking to confirm any of the changes.
"""
#
# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
import os.path
from typing import Optional
import pywikibot
from pywikibot import i18n
from pywikibot.bot import SingleSiteBot
from pywikibot.exceptions import NoPageError
from pywikibot.proofreadpage import ProofreadPage
from pywikibot.tools.djvu import DjVuFile
class DjVuTextBot(SingleSiteBot):
"""
A bot that uploads text-layer from djvu files to Page:namespace.
Works only on sites with Proofread Page extension installed.
.. versionchanged:: 7.0
CheckerBot is a ConfigParserBot
"""
update_options = {
'force': False,
'summary': '',
}
def __init__(
self,
djvu,
index,
pages: Optional[tuple] = None,
**kwargs
) -> None:
"""
Initializer.
:param djvu: djvu from where to fetch the text layer
:type djvu: DjVuFile object
:param index: index page in the Index: namespace
:type index: Page object
:param pages: page interval to upload (start, end)
"""
super().__init__(**kwargs)
self._djvu = djvu
self._index = index
self._prefix = self._index.title(with_ns=False)
self._page_ns = self.site._proofread_page_ns.custom_name
if not pages:
self._pages = (1, self._djvu.number_of_images())
else:
self._pages = pages
# Get edit summary message if it's empty.
if not self.opt.summary:
self.opt.summary = i18n.twtranslate(self._index.site,
'djvutext-creating')
def page_number_gen(self):
"""Generate pages numbers from specified page intervals."""
last = 0
for start, end in sorted(self._pages):
start = max(last, start)
last = end + 1
yield from range(start, last)
@property
def generator(self):
"""Generate pages from specified page interval."""
for page_number in self.page_number_gen():
title = '{page_ns}:{prefix}/{number}'.format(
page_ns=self._page_ns,
prefix=self._prefix,
number=page_number)
page = ProofreadPage(self._index.site, title)
page.page_number = page_number # remember page number in djvu file
yield page
def treat(self, page) -> None:
"""Process one page."""
old_text = page.text
# Overwrite body of the page with content from djvu
page.body = self._djvu.get_page(page.page_number)
new_text = page.text
if page.exists() and not self.opt.force:
pywikibot.output(
'Page {} already exists, not adding!\n'
'Use -force option to overwrite the output page.'
.format(page))
else:
self.userPut(page, old_text, new_text, summary=self.opt.summary)
def main(*args: str) -> None:
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
index = None
djvu_path = '.' # default djvu file directory
pages = '1-'
options = {}
# Parse command line arguments.
local_args = pywikibot.handle_args(args)
for arg in local_args:
opt, _, value = arg.partition(':')
if opt == '-index':
index = value
elif opt == '-djvu':
djvu_path = value
elif opt == '-pages':
pages = value
elif opt == '-summary':
options['summary'] = value
elif opt in ('-force', '-always'):
options[opt[1:]] = True
else:
<|fim_middle|>
# index is mandatory.
if not index:
pywikibot.bot.suggest_help(missing_parameters=['-index'])
return
# If djvu_path is not a file, build djvu_path from dir+index.
djvu_path = os.path.expanduser(djvu_path)
djvu_path = os.path.abspath(djvu_path)
if not os.path.exists(djvu_path):
pywikibot.error('No such file or directory: ' + djvu_path)
return
if os.path.isdir(djvu_path):
djvu_path = os.path.join(djvu_path, index)
# Check the djvu file exists and, if so, create the DjVuFile wrapper.
djvu = DjVuFile(djvu_path)
if not djvu.has_text():
pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
return
# Parse pages param.
pages = pages.split(',')
for i, page_interval in enumerate(pages):
start, sep, end = page_interval.partition('-')
start = int(start or 1)
end = int(end or djvu.number_of_images()) if sep else start
pages[i] = (start, end)
site = pywikibot.Site()
if not site.has_extension('ProofreadPage'):
pywikibot.error('Site {} must have ProofreadPage extension.'
.format(site))
return
index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns)
if not index_page.exists():
raise NoPageError(index)
pywikibot.output('uploading text from {} to {}'
.format(djvu.file, index_page.title(as_link=True)))
bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options)
bot.run()
if __name__ == '__main__':
try:
main()
except Exception:
pywikibot.error('Fatal error:', exc_info=True)
<|fim▁end|> | pywikibot.output('Unknown argument ' + arg) |
<|file_name|>djvutext.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
- path to a file name
- dir where a djvu file name as index is located
optional, by default is current dir '.'
-pages:<start>-<end>,...<start>-<end>,<start>-<end>
Page range to upload;
optional, start=1, end=djvu file number of images.
Page ranges can be specified as:
A-B -> pages A until B
A- -> pages A until number of images
A -> just page A
-B -> pages 1 until B
This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`.
The following options can be set within a settings file which is scripts.ini
by default:
-summary: custom edit summary.
Use quotes if edit summary contains spaces.
-force overwrites existing text
optional, default False
-always do not bother asking to confirm any of the changes.
"""
#
# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
import os.path
from typing import Optional
import pywikibot
from pywikibot import i18n
from pywikibot.bot import SingleSiteBot
from pywikibot.exceptions import NoPageError
from pywikibot.proofreadpage import ProofreadPage
from pywikibot.tools.djvu import DjVuFile
class DjVuTextBot(SingleSiteBot):
"""
A bot that uploads text-layer from djvu files to Page:namespace.
Works only on sites with Proofread Page extension installed.
.. versionchanged:: 7.0
CheckerBot is a ConfigParserBot
"""
update_options = {
'force': False,
'summary': '',
}
def __init__(
self,
djvu,
index,
pages: Optional[tuple] = None,
**kwargs
) -> None:
"""
Initializer.
:param djvu: djvu from where to fetch the text layer
:type djvu: DjVuFile object
:param index: index page in the Index: namespace
:type index: Page object
:param pages: page interval to upload (start, end)
"""
super().__init__(**kwargs)
self._djvu = djvu
self._index = index
self._prefix = self._index.title(with_ns=False)
self._page_ns = self.site._proofread_page_ns.custom_name
if not pages:
self._pages = (1, self._djvu.number_of_images())
else:
self._pages = pages
# Get edit summary message if it's empty.
if not self.opt.summary:
self.opt.summary = i18n.twtranslate(self._index.site,
'djvutext-creating')
def page_number_gen(self):
"""Generate pages numbers from specified page intervals."""
last = 0
for start, end in sorted(self._pages):
start = max(last, start)
last = end + 1
yield from range(start, last)
@property
def generator(self):
"""Generate pages from specified page interval."""
for page_number in self.page_number_gen():
title = '{page_ns}:{prefix}/{number}'.format(
page_ns=self._page_ns,
prefix=self._prefix,
number=page_number)
page = ProofreadPage(self._index.site, title)
page.page_number = page_number # remember page number in djvu file
yield page
def treat(self, page) -> None:
"""Process one page."""
old_text = page.text
# Overwrite body of the page with content from djvu
page.body = self._djvu.get_page(page.page_number)
new_text = page.text
if page.exists() and not self.opt.force:
pywikibot.output(
'Page {} already exists, not adding!\n'
'Use -force option to overwrite the output page.'
.format(page))
else:
self.userPut(page, old_text, new_text, summary=self.opt.summary)
def main(*args: str) -> None:
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
index = None
djvu_path = '.' # default djvu file directory
pages = '1-'
options = {}
# Parse command line arguments.
local_args = pywikibot.handle_args(args)
for arg in local_args:
opt, _, value = arg.partition(':')
if opt == '-index':
index = value
elif opt == '-djvu':
djvu_path = value
elif opt == '-pages':
pages = value
elif opt == '-summary':
options['summary'] = value
elif opt in ('-force', '-always'):
options[opt[1:]] = True
else:
pywikibot.output('Unknown argument ' + arg)
# index is mandatory.
if not index:
<|fim_middle|>
# If djvu_path is not a file, build djvu_path from dir+index.
djvu_path = os.path.expanduser(djvu_path)
djvu_path = os.path.abspath(djvu_path)
if not os.path.exists(djvu_path):
pywikibot.error('No such file or directory: ' + djvu_path)
return
if os.path.isdir(djvu_path):
djvu_path = os.path.join(djvu_path, index)
# Check the djvu file exists and, if so, create the DjVuFile wrapper.
djvu = DjVuFile(djvu_path)
if not djvu.has_text():
pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
return
# Parse pages param.
pages = pages.split(',')
for i, page_interval in enumerate(pages):
start, sep, end = page_interval.partition('-')
start = int(start or 1)
end = int(end or djvu.number_of_images()) if sep else start
pages[i] = (start, end)
site = pywikibot.Site()
if not site.has_extension('ProofreadPage'):
pywikibot.error('Site {} must have ProofreadPage extension.'
.format(site))
return
index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns)
if not index_page.exists():
raise NoPageError(index)
pywikibot.output('uploading text from {} to {}'
.format(djvu.file, index_page.title(as_link=True)))
bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options)
bot.run()
if __name__ == '__main__':
try:
main()
except Exception:
pywikibot.error('Fatal error:', exc_info=True)
<|fim▁end|> | pywikibot.bot.suggest_help(missing_parameters=['-index'])
return |
<|file_name|>djvutext.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
- path to a file name
- dir where a djvu file name as index is located
optional, by default is current dir '.'
-pages:<start>-<end>,...<start>-<end>,<start>-<end>
Page range to upload;
optional, start=1, end=djvu file number of images.
Page ranges can be specified as:
A-B -> pages A until B
A- -> pages A until number of images
A -> just page A
-B -> pages 1 until B
This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`.
The following options can be set within a settings file which is scripts.ini
by default:
-summary: custom edit summary.
Use quotes if edit summary contains spaces.
-force overwrites existing text
optional, default False
-always do not bother asking to confirm any of the changes.
"""
#
# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
import os.path
from typing import Optional
import pywikibot
from pywikibot import i18n
from pywikibot.bot import SingleSiteBot
from pywikibot.exceptions import NoPageError
from pywikibot.proofreadpage import ProofreadPage
from pywikibot.tools.djvu import DjVuFile
class DjVuTextBot(SingleSiteBot):
"""
A bot that uploads text-layer from djvu files to Page:namespace.
Works only on sites with Proofread Page extension installed.
.. versionchanged:: 7.0
CheckerBot is a ConfigParserBot
"""
update_options = {
'force': False,
'summary': '',
}
def __init__(
self,
djvu,
index,
pages: Optional[tuple] = None,
**kwargs
) -> None:
"""
Initializer.
:param djvu: djvu from where to fetch the text layer
:type djvu: DjVuFile object
:param index: index page in the Index: namespace
:type index: Page object
:param pages: page interval to upload (start, end)
"""
super().__init__(**kwargs)
self._djvu = djvu
self._index = index
self._prefix = self._index.title(with_ns=False)
self._page_ns = self.site._proofread_page_ns.custom_name
if not pages:
self._pages = (1, self._djvu.number_of_images())
else:
self._pages = pages
# Get edit summary message if it's empty.
if not self.opt.summary:
self.opt.summary = i18n.twtranslate(self._index.site,
'djvutext-creating')
def page_number_gen(self):
"""Generate pages numbers from specified page intervals."""
last = 0
for start, end in sorted(self._pages):
start = max(last, start)
last = end + 1
yield from range(start, last)
@property
def generator(self):
"""Generate pages from specified page interval."""
for page_number in self.page_number_gen():
title = '{page_ns}:{prefix}/{number}'.format(
page_ns=self._page_ns,
prefix=self._prefix,
number=page_number)
page = ProofreadPage(self._index.site, title)
page.page_number = page_number # remember page number in djvu file
yield page
def treat(self, page) -> None:
"""Process one page."""
old_text = page.text
# Overwrite body of the page with content from djvu
page.body = self._djvu.get_page(page.page_number)
new_text = page.text
if page.exists() and not self.opt.force:
pywikibot.output(
'Page {} already exists, not adding!\n'
'Use -force option to overwrite the output page.'
.format(page))
else:
self.userPut(page, old_text, new_text, summary=self.opt.summary)
def main(*args: str) -> None:
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
index = None
djvu_path = '.' # default djvu file directory
pages = '1-'
options = {}
# Parse command line arguments.
local_args = pywikibot.handle_args(args)
for arg in local_args:
opt, _, value = arg.partition(':')
if opt == '-index':
index = value
elif opt == '-djvu':
djvu_path = value
elif opt == '-pages':
pages = value
elif opt == '-summary':
options['summary'] = value
elif opt in ('-force', '-always'):
options[opt[1:]] = True
else:
pywikibot.output('Unknown argument ' + arg)
# index is mandatory.
if not index:
pywikibot.bot.suggest_help(missing_parameters=['-index'])
return
# If djvu_path is not a file, build djvu_path from dir+index.
djvu_path = os.path.expanduser(djvu_path)
djvu_path = os.path.abspath(djvu_path)
if not os.path.exists(djvu_path):
<|fim_middle|>
if os.path.isdir(djvu_path):
djvu_path = os.path.join(djvu_path, index)
# Check the djvu file exists and, if so, create the DjVuFile wrapper.
djvu = DjVuFile(djvu_path)
if not djvu.has_text():
pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
return
# Parse pages param.
pages = pages.split(',')
for i, page_interval in enumerate(pages):
start, sep, end = page_interval.partition('-')
start = int(start or 1)
end = int(end or djvu.number_of_images()) if sep else start
pages[i] = (start, end)
site = pywikibot.Site()
if not site.has_extension('ProofreadPage'):
pywikibot.error('Site {} must have ProofreadPage extension.'
.format(site))
return
index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns)
if not index_page.exists():
raise NoPageError(index)
pywikibot.output('uploading text from {} to {}'
.format(djvu.file, index_page.title(as_link=True)))
bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options)
bot.run()
if __name__ == '__main__':
try:
main()
except Exception:
pywikibot.error('Fatal error:', exc_info=True)
<|fim▁end|> | pywikibot.error('No such file or directory: ' + djvu_path)
return |
<|file_name|>djvutext.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
- path to a file name
- dir where a djvu file name as index is located
optional, by default is current dir '.'
-pages:<start>-<end>,...<start>-<end>,<start>-<end>
Page range to upload;
optional, start=1, end=djvu file number of images.
Page ranges can be specified as:
A-B -> pages A until B
A- -> pages A until number of images
A -> just page A
-B -> pages 1 until B
This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`.
The following options can be set within a settings file which is scripts.ini
by default:
-summary: custom edit summary.
Use quotes if edit summary contains spaces.
-force overwrites existing text
optional, default False
-always do not bother asking to confirm any of the changes.
"""
#
# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
import os.path
from typing import Optional
import pywikibot
from pywikibot import i18n
from pywikibot.bot import SingleSiteBot
from pywikibot.exceptions import NoPageError
from pywikibot.proofreadpage import ProofreadPage
from pywikibot.tools.djvu import DjVuFile
class DjVuTextBot(SingleSiteBot):
"""
A bot that uploads text-layer from djvu files to Page:namespace.
Works only on sites with Proofread Page extension installed.
.. versionchanged:: 7.0
CheckerBot is a ConfigParserBot
"""
update_options = {
'force': False,
'summary': '',
}
def __init__(
self,
djvu,
index,
pages: Optional[tuple] = None,
**kwargs
) -> None:
"""
Initializer.
:param djvu: djvu from where to fetch the text layer
:type djvu: DjVuFile object
:param index: index page in the Index: namespace
:type index: Page object
:param pages: page interval to upload (start, end)
"""
super().__init__(**kwargs)
self._djvu = djvu
self._index = index
self._prefix = self._index.title(with_ns=False)
self._page_ns = self.site._proofread_page_ns.custom_name
if not pages:
self._pages = (1, self._djvu.number_of_images())
else:
self._pages = pages
# Get edit summary message if it's empty.
if not self.opt.summary:
self.opt.summary = i18n.twtranslate(self._index.site,
'djvutext-creating')
def page_number_gen(self):
"""Generate pages numbers from specified page intervals."""
last = 0
for start, end in sorted(self._pages):
start = max(last, start)
last = end + 1
yield from range(start, last)
@property
def generator(self):
"""Generate pages from specified page interval."""
for page_number in self.page_number_gen():
title = '{page_ns}:{prefix}/{number}'.format(
page_ns=self._page_ns,
prefix=self._prefix,
number=page_number)
page = ProofreadPage(self._index.site, title)
page.page_number = page_number # remember page number in djvu file
yield page
def treat(self, page) -> None:
"""Process one page."""
old_text = page.text
# Overwrite body of the page with content from djvu
page.body = self._djvu.get_page(page.page_number)
new_text = page.text
if page.exists() and not self.opt.force:
pywikibot.output(
'Page {} already exists, not adding!\n'
'Use -force option to overwrite the output page.'
.format(page))
else:
self.userPut(page, old_text, new_text, summary=self.opt.summary)
def main(*args: str) -> None:
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
index = None
djvu_path = '.' # default djvu file directory
pages = '1-'
options = {}
# Parse command line arguments.
local_args = pywikibot.handle_args(args)
for arg in local_args:
opt, _, value = arg.partition(':')
if opt == '-index':
index = value
elif opt == '-djvu':
djvu_path = value
elif opt == '-pages':
pages = value
elif opt == '-summary':
options['summary'] = value
elif opt in ('-force', '-always'):
options[opt[1:]] = True
else:
pywikibot.output('Unknown argument ' + arg)
# index is mandatory.
if not index:
pywikibot.bot.suggest_help(missing_parameters=['-index'])
return
# If djvu_path is not a file, build djvu_path from dir+index.
djvu_path = os.path.expanduser(djvu_path)
djvu_path = os.path.abspath(djvu_path)
if not os.path.exists(djvu_path):
pywikibot.error('No such file or directory: ' + djvu_path)
return
if os.path.isdir(djvu_path):
<|fim_middle|>
# Check the djvu file exists and, if so, create the DjVuFile wrapper.
djvu = DjVuFile(djvu_path)
if not djvu.has_text():
pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
return
# Parse pages param.
pages = pages.split(',')
for i, page_interval in enumerate(pages):
start, sep, end = page_interval.partition('-')
start = int(start or 1)
end = int(end or djvu.number_of_images()) if sep else start
pages[i] = (start, end)
site = pywikibot.Site()
if not site.has_extension('ProofreadPage'):
pywikibot.error('Site {} must have ProofreadPage extension.'
.format(site))
return
index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns)
if not index_page.exists():
raise NoPageError(index)
pywikibot.output('uploading text from {} to {}'
.format(djvu.file, index_page.title(as_link=True)))
bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options)
bot.run()
if __name__ == '__main__':
try:
main()
except Exception:
pywikibot.error('Fatal error:', exc_info=True)
<|fim▁end|> | djvu_path = os.path.join(djvu_path, index) |
<|file_name|>djvutext.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
- path to a file name
- dir where a djvu file name as index is located
optional, by default is current dir '.'
-pages:<start>-<end>,...<start>-<end>,<start>-<end>
Page range to upload;
optional, start=1, end=djvu file number of images.
Page ranges can be specified as:
A-B -> pages A until B
A- -> pages A until number of images
A -> just page A
-B -> pages 1 until B
This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`.
The following options can be set within a settings file which is scripts.ini
by default:
-summary: custom edit summary.
Use quotes if edit summary contains spaces.
-force overwrites existing text
optional, default False
-always do not bother asking to confirm any of the changes.
"""
#
# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
import os.path
from typing import Optional
import pywikibot
from pywikibot import i18n
from pywikibot.bot import SingleSiteBot
from pywikibot.exceptions import NoPageError
from pywikibot.proofreadpage import ProofreadPage
from pywikibot.tools.djvu import DjVuFile
class DjVuTextBot(SingleSiteBot):
"""
A bot that uploads text-layer from djvu files to Page:namespace.
Works only on sites with Proofread Page extension installed.
.. versionchanged:: 7.0
CheckerBot is a ConfigParserBot
"""
update_options = {
'force': False,
'summary': '',
}
def __init__(
self,
djvu,
index,
pages: Optional[tuple] = None,
**kwargs
) -> None:
"""
Initializer.
:param djvu: djvu from where to fetch the text layer
:type djvu: DjVuFile object
:param index: index page in the Index: namespace
:type index: Page object
:param pages: page interval to upload (start, end)
"""
super().__init__(**kwargs)
self._djvu = djvu
self._index = index
self._prefix = self._index.title(with_ns=False)
self._page_ns = self.site._proofread_page_ns.custom_name
if not pages:
self._pages = (1, self._djvu.number_of_images())
else:
self._pages = pages
# Get edit summary message if it's empty.
if not self.opt.summary:
self.opt.summary = i18n.twtranslate(self._index.site,
'djvutext-creating')
def page_number_gen(self):
"""Generate pages numbers from specified page intervals."""
last = 0
for start, end in sorted(self._pages):
start = max(last, start)
last = end + 1
yield from range(start, last)
@property
def generator(self):
"""Generate pages from specified page interval."""
for page_number in self.page_number_gen():
title = '{page_ns}:{prefix}/{number}'.format(
page_ns=self._page_ns,
prefix=self._prefix,
number=page_number)
page = ProofreadPage(self._index.site, title)
page.page_number = page_number # remember page number in djvu file
yield page
def treat(self, page) -> None:
"""Process one page."""
old_text = page.text
# Overwrite body of the page with content from djvu
page.body = self._djvu.get_page(page.page_number)
new_text = page.text
if page.exists() and not self.opt.force:
pywikibot.output(
'Page {} already exists, not adding!\n'
'Use -force option to overwrite the output page.'
.format(page))
else:
self.userPut(page, old_text, new_text, summary=self.opt.summary)
def main(*args: str) -> None:
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
index = None
djvu_path = '.' # default djvu file directory
pages = '1-'
options = {}
# Parse command line arguments.
local_args = pywikibot.handle_args(args)
for arg in local_args:
opt, _, value = arg.partition(':')
if opt == '-index':
index = value
elif opt == '-djvu':
djvu_path = value
elif opt == '-pages':
pages = value
elif opt == '-summary':
options['summary'] = value
elif opt in ('-force', '-always'):
options[opt[1:]] = True
else:
pywikibot.output('Unknown argument ' + arg)
# index is mandatory.
if not index:
pywikibot.bot.suggest_help(missing_parameters=['-index'])
return
# If djvu_path is not a file, build djvu_path from dir+index.
djvu_path = os.path.expanduser(djvu_path)
djvu_path = os.path.abspath(djvu_path)
if not os.path.exists(djvu_path):
pywikibot.error('No such file or directory: ' + djvu_path)
return
if os.path.isdir(djvu_path):
djvu_path = os.path.join(djvu_path, index)
# Check the djvu file exists and, if so, create the DjVuFile wrapper.
djvu = DjVuFile(djvu_path)
if not djvu.has_text():
<|fim_middle|>
# Parse pages param.
pages = pages.split(',')
for i, page_interval in enumerate(pages):
start, sep, end = page_interval.partition('-')
start = int(start or 1)
end = int(end or djvu.number_of_images()) if sep else start
pages[i] = (start, end)
site = pywikibot.Site()
if not site.has_extension('ProofreadPage'):
pywikibot.error('Site {} must have ProofreadPage extension.'
.format(site))
return
index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns)
if not index_page.exists():
raise NoPageError(index)
pywikibot.output('uploading text from {} to {}'
.format(djvu.file, index_page.title(as_link=True)))
bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options)
bot.run()
if __name__ == '__main__':
try:
main()
except Exception:
pywikibot.error('Fatal error:', exc_info=True)
<|fim▁end|> | pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
return |
<|file_name|>djvutext.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
- path to a file name
- dir where a djvu file name as index is located
optional, by default is current dir '.'
-pages:<start>-<end>,...<start>-<end>,<start>-<end>
Page range to upload;
optional, start=1, end=djvu file number of images.
Page ranges can be specified as:
A-B -> pages A until B
A- -> pages A until number of images
A -> just page A
-B -> pages 1 until B
This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`.
The following options can be set within a settings file which is scripts.ini
by default:
-summary: custom edit summary.
Use quotes if edit summary contains spaces.
-force overwrites existing text
optional, default False
-always do not bother asking to confirm any of the changes.
"""
#
# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
import os.path
from typing import Optional
import pywikibot
from pywikibot import i18n
from pywikibot.bot import SingleSiteBot
from pywikibot.exceptions import NoPageError
from pywikibot.proofreadpage import ProofreadPage
from pywikibot.tools.djvu import DjVuFile
class DjVuTextBot(SingleSiteBot):
"""
A bot that uploads text-layer from djvu files to Page:namespace.
Works only on sites with Proofread Page extension installed.
.. versionchanged:: 7.0
CheckerBot is a ConfigParserBot
"""
update_options = {
'force': False,
'summary': '',
}
def __init__(
self,
djvu,
index,
pages: Optional[tuple] = None,
**kwargs
) -> None:
"""
Initializer.
:param djvu: djvu from where to fetch the text layer
:type djvu: DjVuFile object
:param index: index page in the Index: namespace
:type index: Page object
:param pages: page interval to upload (start, end)
"""
super().__init__(**kwargs)
self._djvu = djvu
self._index = index
self._prefix = self._index.title(with_ns=False)
self._page_ns = self.site._proofread_page_ns.custom_name
if not pages:
self._pages = (1, self._djvu.number_of_images())
else:
self._pages = pages
# Get edit summary message if it's empty.
if not self.opt.summary:
self.opt.summary = i18n.twtranslate(self._index.site,
'djvutext-creating')
def page_number_gen(self):
"""Generate pages numbers from specified page intervals."""
last = 0
for start, end in sorted(self._pages):
start = max(last, start)
last = end + 1
yield from range(start, last)
@property
def generator(self):
"""Generate pages from specified page interval."""
for page_number in self.page_number_gen():
title = '{page_ns}:{prefix}/{number}'.format(
page_ns=self._page_ns,
prefix=self._prefix,
number=page_number)
page = ProofreadPage(self._index.site, title)
page.page_number = page_number # remember page number in djvu file
yield page
def treat(self, page) -> None:
"""Process one page."""
old_text = page.text
# Overwrite body of the page with content from djvu
page.body = self._djvu.get_page(page.page_number)
new_text = page.text
if page.exists() and not self.opt.force:
pywikibot.output(
'Page {} already exists, not adding!\n'
'Use -force option to overwrite the output page.'
.format(page))
else:
self.userPut(page, old_text, new_text, summary=self.opt.summary)
def main(*args: str) -> None:
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
index = None
djvu_path = '.' # default djvu file directory
pages = '1-'
options = {}
# Parse command line arguments.
local_args = pywikibot.handle_args(args)
for arg in local_args:
opt, _, value = arg.partition(':')
if opt == '-index':
index = value
elif opt == '-djvu':
djvu_path = value
elif opt == '-pages':
pages = value
elif opt == '-summary':
options['summary'] = value
elif opt in ('-force', '-always'):
options[opt[1:]] = True
else:
pywikibot.output('Unknown argument ' + arg)
# index is mandatory.
if not index:
pywikibot.bot.suggest_help(missing_parameters=['-index'])
return
# If djvu_path is not a file, build djvu_path from dir+index.
djvu_path = os.path.expanduser(djvu_path)
djvu_path = os.path.abspath(djvu_path)
if not os.path.exists(djvu_path):
pywikibot.error('No such file or directory: ' + djvu_path)
return
if os.path.isdir(djvu_path):
djvu_path = os.path.join(djvu_path, index)
# Check the djvu file exists and, if so, create the DjVuFile wrapper.
djvu = DjVuFile(djvu_path)
if not djvu.has_text():
pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
return
# Parse pages param.
pages = pages.split(',')
for i, page_interval in enumerate(pages):
start, sep, end = page_interval.partition('-')
start = int(start or 1)
end = int(end or djvu.number_of_images()) if sep else start
pages[i] = (start, end)
site = pywikibot.Site()
if not site.has_extension('ProofreadPage'):
<|fim_middle|>
index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns)
if not index_page.exists():
raise NoPageError(index)
pywikibot.output('uploading text from {} to {}'
.format(djvu.file, index_page.title(as_link=True)))
bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options)
bot.run()
if __name__ == '__main__':
try:
main()
except Exception:
pywikibot.error('Fatal error:', exc_info=True)
<|fim▁end|> | pywikibot.error('Site {} must have ProofreadPage extension.'
.format(site))
return |
<|file_name|>djvutext.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
- path to a file name
- dir where a djvu file name as index is located
optional, by default is current dir '.'
-pages:<start>-<end>,...<start>-<end>,<start>-<end>
Page range to upload;
optional, start=1, end=djvu file number of images.
Page ranges can be specified as:
A-B -> pages A until B
A- -> pages A until number of images
A -> just page A
-B -> pages 1 until B
This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`.
The following options can be set within a settings file which is scripts.ini
by default:
-summary: custom edit summary.
Use quotes if edit summary contains spaces.
-force overwrites existing text
optional, default False
-always do not bother asking to confirm any of the changes.
"""
#
# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
import os.path
from typing import Optional
import pywikibot
from pywikibot import i18n
from pywikibot.bot import SingleSiteBot
from pywikibot.exceptions import NoPageError
from pywikibot.proofreadpage import ProofreadPage
from pywikibot.tools.djvu import DjVuFile
class DjVuTextBot(SingleSiteBot):
"""
A bot that uploads text-layer from djvu files to Page:namespace.
Works only on sites with Proofread Page extension installed.
.. versionchanged:: 7.0
CheckerBot is a ConfigParserBot
"""
update_options = {
'force': False,
'summary': '',
}
def __init__(
self,
djvu,
index,
pages: Optional[tuple] = None,
**kwargs
) -> None:
"""
Initializer.
:param djvu: djvu from where to fetch the text layer
:type djvu: DjVuFile object
:param index: index page in the Index: namespace
:type index: Page object
:param pages: page interval to upload (start, end)
"""
super().__init__(**kwargs)
self._djvu = djvu
self._index = index
self._prefix = self._index.title(with_ns=False)
self._page_ns = self.site._proofread_page_ns.custom_name
if not pages:
self._pages = (1, self._djvu.number_of_images())
else:
self._pages = pages
# Get edit summary message if it's empty.
if not self.opt.summary:
self.opt.summary = i18n.twtranslate(self._index.site,
'djvutext-creating')
def page_number_gen(self):
"""Generate pages numbers from specified page intervals."""
last = 0
for start, end in sorted(self._pages):
start = max(last, start)
last = end + 1
yield from range(start, last)
@property
def generator(self):
"""Generate pages from specified page interval."""
for page_number in self.page_number_gen():
title = '{page_ns}:{prefix}/{number}'.format(
page_ns=self._page_ns,
prefix=self._prefix,
number=page_number)
page = ProofreadPage(self._index.site, title)
page.page_number = page_number # remember page number in djvu file
yield page
def treat(self, page) -> None:
"""Process one page."""
old_text = page.text
# Overwrite body of the page with content from djvu
page.body = self._djvu.get_page(page.page_number)
new_text = page.text
if page.exists() and not self.opt.force:
pywikibot.output(
'Page {} already exists, not adding!\n'
'Use -force option to overwrite the output page.'
.format(page))
else:
self.userPut(page, old_text, new_text, summary=self.opt.summary)
def main(*args: str) -> None:
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
index = None
djvu_path = '.' # default djvu file directory
pages = '1-'
options = {}
# Parse command line arguments.
local_args = pywikibot.handle_args(args)
for arg in local_args:
opt, _, value = arg.partition(':')
if opt == '-index':
index = value
elif opt == '-djvu':
djvu_path = value
elif opt == '-pages':
pages = value
elif opt == '-summary':
options['summary'] = value
elif opt in ('-force', '-always'):
options[opt[1:]] = True
else:
pywikibot.output('Unknown argument ' + arg)
# index is mandatory.
if not index:
pywikibot.bot.suggest_help(missing_parameters=['-index'])
return
# If djvu_path is not a file, build djvu_path from dir+index.
djvu_path = os.path.expanduser(djvu_path)
djvu_path = os.path.abspath(djvu_path)
if not os.path.exists(djvu_path):
pywikibot.error('No such file or directory: ' + djvu_path)
return
if os.path.isdir(djvu_path):
djvu_path = os.path.join(djvu_path, index)
# Check the djvu file exists and, if so, create the DjVuFile wrapper.
djvu = DjVuFile(djvu_path)
if not djvu.has_text():
pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
return
# Parse pages param.
pages = pages.split(',')
for i, page_interval in enumerate(pages):
start, sep, end = page_interval.partition('-')
start = int(start or 1)
end = int(end or djvu.number_of_images()) if sep else start
pages[i] = (start, end)
site = pywikibot.Site()
if not site.has_extension('ProofreadPage'):
pywikibot.error('Site {} must have ProofreadPage extension.'
.format(site))
return
index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns)
if not index_page.exists():
<|fim_middle|>
pywikibot.output('uploading text from {} to {}'
.format(djvu.file, index_page.title(as_link=True)))
bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options)
bot.run()
if __name__ == '__main__':
try:
main()
except Exception:
pywikibot.error('Fatal error:', exc_info=True)
<|fim▁end|> | raise NoPageError(index) |
<|file_name|>djvutext.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
- path to a file name
- dir where a djvu file name as index is located
optional, by default is current dir '.'
-pages:<start>-<end>,...<start>-<end>,<start>-<end>
Page range to upload;
optional, start=1, end=djvu file number of images.
Page ranges can be specified as:
A-B -> pages A until B
A- -> pages A until number of images
A -> just page A
-B -> pages 1 until B
This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`.
The following options can be set within a settings file which is scripts.ini
by default:
-summary: custom edit summary.
Use quotes if edit summary contains spaces.
-force overwrites existing text
optional, default False
-always do not bother asking to confirm any of the changes.
"""
#
# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
import os.path
from typing import Optional
import pywikibot
from pywikibot import i18n
from pywikibot.bot import SingleSiteBot
from pywikibot.exceptions import NoPageError
from pywikibot.proofreadpage import ProofreadPage
from pywikibot.tools.djvu import DjVuFile
class DjVuTextBot(SingleSiteBot):
"""
A bot that uploads text-layer from djvu files to Page:namespace.
Works only on sites with Proofread Page extension installed.
.. versionchanged:: 7.0
CheckerBot is a ConfigParserBot
"""
update_options = {
'force': False,
'summary': '',
}
def __init__(
self,
djvu,
index,
pages: Optional[tuple] = None,
**kwargs
) -> None:
"""
Initializer.
:param djvu: djvu from where to fetch the text layer
:type djvu: DjVuFile object
:param index: index page in the Index: namespace
:type index: Page object
:param pages: page interval to upload (start, end)
"""
super().__init__(**kwargs)
self._djvu = djvu
self._index = index
self._prefix = self._index.title(with_ns=False)
self._page_ns = self.site._proofread_page_ns.custom_name
if not pages:
self._pages = (1, self._djvu.number_of_images())
else:
self._pages = pages
# Get edit summary message if it's empty.
if not self.opt.summary:
self.opt.summary = i18n.twtranslate(self._index.site,
'djvutext-creating')
def page_number_gen(self):
"""Generate pages numbers from specified page intervals."""
last = 0
for start, end in sorted(self._pages):
start = max(last, start)
last = end + 1
yield from range(start, last)
@property
def generator(self):
"""Generate pages from specified page interval."""
for page_number in self.page_number_gen():
title = '{page_ns}:{prefix}/{number}'.format(
page_ns=self._page_ns,
prefix=self._prefix,
number=page_number)
page = ProofreadPage(self._index.site, title)
page.page_number = page_number # remember page number in djvu file
yield page
def treat(self, page) -> None:
"""Process one page."""
old_text = page.text
# Overwrite body of the page with content from djvu
page.body = self._djvu.get_page(page.page_number)
new_text = page.text
if page.exists() and not self.opt.force:
pywikibot.output(
'Page {} already exists, not adding!\n'
'Use -force option to overwrite the output page.'
.format(page))
else:
self.userPut(page, old_text, new_text, summary=self.opt.summary)
def main(*args: str) -> None:
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
index = None
djvu_path = '.' # default djvu file directory
pages = '1-'
options = {}
# Parse command line arguments.
local_args = pywikibot.handle_args(args)
for arg in local_args:
opt, _, value = arg.partition(':')
if opt == '-index':
index = value
elif opt == '-djvu':
djvu_path = value
elif opt == '-pages':
pages = value
elif opt == '-summary':
options['summary'] = value
elif opt in ('-force', '-always'):
options[opt[1:]] = True
else:
pywikibot.output('Unknown argument ' + arg)
# index is mandatory.
if not index:
pywikibot.bot.suggest_help(missing_parameters=['-index'])
return
# If djvu_path is not a file, build djvu_path from dir+index.
djvu_path = os.path.expanduser(djvu_path)
djvu_path = os.path.abspath(djvu_path)
if not os.path.exists(djvu_path):
pywikibot.error('No such file or directory: ' + djvu_path)
return
if os.path.isdir(djvu_path):
djvu_path = os.path.join(djvu_path, index)
# Check the djvu file exists and, if so, create the DjVuFile wrapper.
djvu = DjVuFile(djvu_path)
if not djvu.has_text():
pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
return
# Parse pages param.
pages = pages.split(',')
for i, page_interval in enumerate(pages):
start, sep, end = page_interval.partition('-')
start = int(start or 1)
end = int(end or djvu.number_of_images()) if sep else start
pages[i] = (start, end)
site = pywikibot.Site()
if not site.has_extension('ProofreadPage'):
pywikibot.error('Site {} must have ProofreadPage extension.'
.format(site))
return
index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns)
if not index_page.exists():
raise NoPageError(index)
pywikibot.output('uploading text from {} to {}'
.format(djvu.file, index_page.title(as_link=True)))
bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options)
bot.run()
if __name__ == '__main__':
<|fim_middle|>
<|fim▁end|> | try:
main()
except Exception:
pywikibot.error('Fatal error:', exc_info=True) |
<|file_name|>djvutext.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
- path to a file name
- dir where a djvu file name as index is located
optional, by default is current dir '.'
-pages:<start>-<end>,...<start>-<end>,<start>-<end>
Page range to upload;
optional, start=1, end=djvu file number of images.
Page ranges can be specified as:
A-B -> pages A until B
A- -> pages A until number of images
A -> just page A
-B -> pages 1 until B
This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`.
The following options can be set within a settings file which is scripts.ini
by default:
-summary: custom edit summary.
Use quotes if edit summary contains spaces.
-force overwrites existing text
optional, default False
-always do not bother asking to confirm any of the changes.
"""
#
# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
import os.path
from typing import Optional
import pywikibot
from pywikibot import i18n
from pywikibot.bot import SingleSiteBot
from pywikibot.exceptions import NoPageError
from pywikibot.proofreadpage import ProofreadPage
from pywikibot.tools.djvu import DjVuFile
class DjVuTextBot(SingleSiteBot):
"""
A bot that uploads text-layer from djvu files to Page:namespace.
Works only on sites with Proofread Page extension installed.
.. versionchanged:: 7.0
CheckerBot is a ConfigParserBot
"""
update_options = {
'force': False,
'summary': '',
}
def <|fim_middle|>(
self,
djvu,
index,
pages: Optional[tuple] = None,
**kwargs
) -> None:
"""
Initializer.
:param djvu: djvu from where to fetch the text layer
:type djvu: DjVuFile object
:param index: index page in the Index: namespace
:type index: Page object
:param pages: page interval to upload (start, end)
"""
super().__init__(**kwargs)
self._djvu = djvu
self._index = index
self._prefix = self._index.title(with_ns=False)
self._page_ns = self.site._proofread_page_ns.custom_name
if not pages:
self._pages = (1, self._djvu.number_of_images())
else:
self._pages = pages
# Get edit summary message if it's empty.
if not self.opt.summary:
self.opt.summary = i18n.twtranslate(self._index.site,
'djvutext-creating')
def page_number_gen(self):
"""Generate pages numbers from specified page intervals."""
last = 0
for start, end in sorted(self._pages):
start = max(last, start)
last = end + 1
yield from range(start, last)
@property
def generator(self):
"""Generate pages from specified page interval."""
for page_number in self.page_number_gen():
title = '{page_ns}:{prefix}/{number}'.format(
page_ns=self._page_ns,
prefix=self._prefix,
number=page_number)
page = ProofreadPage(self._index.site, title)
page.page_number = page_number # remember page number in djvu file
yield page
def treat(self, page) -> None:
"""Process one page."""
old_text = page.text
# Overwrite body of the page with content from djvu
page.body = self._djvu.get_page(page.page_number)
new_text = page.text
if page.exists() and not self.opt.force:
pywikibot.output(
'Page {} already exists, not adding!\n'
'Use -force option to overwrite the output page.'
.format(page))
else:
self.userPut(page, old_text, new_text, summary=self.opt.summary)
def main(*args: str) -> None:
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
index = None
djvu_path = '.' # default djvu file directory
pages = '1-'
options = {}
# Parse command line arguments.
local_args = pywikibot.handle_args(args)
for arg in local_args:
opt, _, value = arg.partition(':')
if opt == '-index':
index = value
elif opt == '-djvu':
djvu_path = value
elif opt == '-pages':
pages = value
elif opt == '-summary':
options['summary'] = value
elif opt in ('-force', '-always'):
options[opt[1:]] = True
else:
pywikibot.output('Unknown argument ' + arg)
# index is mandatory.
if not index:
pywikibot.bot.suggest_help(missing_parameters=['-index'])
return
# If djvu_path is not a file, build djvu_path from dir+index.
djvu_path = os.path.expanduser(djvu_path)
djvu_path = os.path.abspath(djvu_path)
if not os.path.exists(djvu_path):
pywikibot.error('No such file or directory: ' + djvu_path)
return
if os.path.isdir(djvu_path):
djvu_path = os.path.join(djvu_path, index)
# Check the djvu file exists and, if so, create the DjVuFile wrapper.
djvu = DjVuFile(djvu_path)
if not djvu.has_text():
pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
return
# Parse pages param.
pages = pages.split(',')
for i, page_interval in enumerate(pages):
start, sep, end = page_interval.partition('-')
start = int(start or 1)
end = int(end or djvu.number_of_images()) if sep else start
pages[i] = (start, end)
site = pywikibot.Site()
if not site.has_extension('ProofreadPage'):
pywikibot.error('Site {} must have ProofreadPage extension.'
.format(site))
return
index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns)
if not index_page.exists():
raise NoPageError(index)
pywikibot.output('uploading text from {} to {}'
.format(djvu.file, index_page.title(as_link=True)))
bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options)
bot.run()
if __name__ == '__main__':
try:
main()
except Exception:
pywikibot.error('Fatal error:', exc_info=True)
<|fim▁end|> | __init__ |
<|file_name|>djvutext.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
- path to a file name
- dir where a djvu file name as index is located
optional, by default is current dir '.'
-pages:<start>-<end>,...<start>-<end>,<start>-<end>
Page range to upload;
optional, start=1, end=djvu file number of images.
Page ranges can be specified as:
A-B -> pages A until B
A- -> pages A until number of images
A -> just page A
-B -> pages 1 until B
This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`.
The following options can be set within a settings file which is scripts.ini
by default:
-summary: custom edit summary.
Use quotes if edit summary contains spaces.
-force overwrites existing text
optional, default False
-always do not bother asking to confirm any of the changes.
"""
#
# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
import os.path
from typing import Optional
import pywikibot
from pywikibot import i18n
from pywikibot.bot import SingleSiteBot
from pywikibot.exceptions import NoPageError
from pywikibot.proofreadpage import ProofreadPage
from pywikibot.tools.djvu import DjVuFile
class DjVuTextBot(SingleSiteBot):
"""
A bot that uploads text-layer from djvu files to Page:namespace.
Works only on sites with Proofread Page extension installed.
.. versionchanged:: 7.0
CheckerBot is a ConfigParserBot
"""
update_options = {
'force': False,
'summary': '',
}
def __init__(
self,
djvu,
index,
pages: Optional[tuple] = None,
**kwargs
) -> None:
"""
Initializer.
:param djvu: djvu from where to fetch the text layer
:type djvu: DjVuFile object
:param index: index page in the Index: namespace
:type index: Page object
:param pages: page interval to upload (start, end)
"""
super().__init__(**kwargs)
self._djvu = djvu
self._index = index
self._prefix = self._index.title(with_ns=False)
self._page_ns = self.site._proofread_page_ns.custom_name
if not pages:
self._pages = (1, self._djvu.number_of_images())
else:
self._pages = pages
# Get edit summary message if it's empty.
if not self.opt.summary:
self.opt.summary = i18n.twtranslate(self._index.site,
'djvutext-creating')
def <|fim_middle|>(self):
"""Generate pages numbers from specified page intervals."""
last = 0
for start, end in sorted(self._pages):
start = max(last, start)
last = end + 1
yield from range(start, last)
@property
def generator(self):
"""Generate pages from specified page interval."""
for page_number in self.page_number_gen():
title = '{page_ns}:{prefix}/{number}'.format(
page_ns=self._page_ns,
prefix=self._prefix,
number=page_number)
page = ProofreadPage(self._index.site, title)
page.page_number = page_number # remember page number in djvu file
yield page
def treat(self, page) -> None:
"""Process one page."""
old_text = page.text
# Overwrite body of the page with content from djvu
page.body = self._djvu.get_page(page.page_number)
new_text = page.text
if page.exists() and not self.opt.force:
pywikibot.output(
'Page {} already exists, not adding!\n'
'Use -force option to overwrite the output page.'
.format(page))
else:
self.userPut(page, old_text, new_text, summary=self.opt.summary)
def main(*args: str) -> None:
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
index = None
djvu_path = '.' # default djvu file directory
pages = '1-'
options = {}
# Parse command line arguments.
local_args = pywikibot.handle_args(args)
for arg in local_args:
opt, _, value = arg.partition(':')
if opt == '-index':
index = value
elif opt == '-djvu':
djvu_path = value
elif opt == '-pages':
pages = value
elif opt == '-summary':
options['summary'] = value
elif opt in ('-force', '-always'):
options[opt[1:]] = True
else:
pywikibot.output('Unknown argument ' + arg)
# index is mandatory.
if not index:
pywikibot.bot.suggest_help(missing_parameters=['-index'])
return
# If djvu_path is not a file, build djvu_path from dir+index.
djvu_path = os.path.expanduser(djvu_path)
djvu_path = os.path.abspath(djvu_path)
if not os.path.exists(djvu_path):
pywikibot.error('No such file or directory: ' + djvu_path)
return
if os.path.isdir(djvu_path):
djvu_path = os.path.join(djvu_path, index)
# Check the djvu file exists and, if so, create the DjVuFile wrapper.
djvu = DjVuFile(djvu_path)
if not djvu.has_text():
pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
return
# Parse pages param.
pages = pages.split(',')
for i, page_interval in enumerate(pages):
start, sep, end = page_interval.partition('-')
start = int(start or 1)
end = int(end or djvu.number_of_images()) if sep else start
pages[i] = (start, end)
site = pywikibot.Site()
if not site.has_extension('ProofreadPage'):
pywikibot.error('Site {} must have ProofreadPage extension.'
.format(site))
return
index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns)
if not index_page.exists():
raise NoPageError(index)
pywikibot.output('uploading text from {} to {}'
.format(djvu.file, index_page.title(as_link=True)))
bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options)
bot.run()
if __name__ == '__main__':
try:
main()
except Exception:
pywikibot.error('Fatal error:', exc_info=True)
<|fim▁end|> | page_number_gen |
<|file_name|>djvutext.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
- path to a file name
- dir where a djvu file name as index is located
optional, by default is current dir '.'
-pages:<start>-<end>,...<start>-<end>,<start>-<end>
Page range to upload;
optional, start=1, end=djvu file number of images.
Page ranges can be specified as:
A-B -> pages A until B
A- -> pages A until number of images
A -> just page A
-B -> pages 1 until B
This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`.
The following options can be set within a settings file which is scripts.ini
by default:
-summary: custom edit summary.
Use quotes if edit summary contains spaces.
-force overwrites existing text
optional, default False
-always do not bother asking to confirm any of the changes.
"""
#
# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
import os.path
from typing import Optional
import pywikibot
from pywikibot import i18n
from pywikibot.bot import SingleSiteBot
from pywikibot.exceptions import NoPageError
from pywikibot.proofreadpage import ProofreadPage
from pywikibot.tools.djvu import DjVuFile
class DjVuTextBot(SingleSiteBot):
"""
A bot that uploads text-layer from djvu files to Page:namespace.
Works only on sites with Proofread Page extension installed.
.. versionchanged:: 7.0
CheckerBot is a ConfigParserBot
"""
update_options = {
'force': False,
'summary': '',
}
def __init__(
self,
djvu,
index,
pages: Optional[tuple] = None,
**kwargs
) -> None:
"""
Initializer.
:param djvu: djvu from where to fetch the text layer
:type djvu: DjVuFile object
:param index: index page in the Index: namespace
:type index: Page object
:param pages: page interval to upload (start, end)
"""
super().__init__(**kwargs)
self._djvu = djvu
self._index = index
self._prefix = self._index.title(with_ns=False)
self._page_ns = self.site._proofread_page_ns.custom_name
if not pages:
self._pages = (1, self._djvu.number_of_images())
else:
self._pages = pages
# Get edit summary message if it's empty.
if not self.opt.summary:
self.opt.summary = i18n.twtranslate(self._index.site,
'djvutext-creating')
def page_number_gen(self):
"""Generate pages numbers from specified page intervals."""
last = 0
for start, end in sorted(self._pages):
start = max(last, start)
last = end + 1
yield from range(start, last)
@property
def <|fim_middle|>(self):
"""Generate pages from specified page interval."""
for page_number in self.page_number_gen():
title = '{page_ns}:{prefix}/{number}'.format(
page_ns=self._page_ns,
prefix=self._prefix,
number=page_number)
page = ProofreadPage(self._index.site, title)
page.page_number = page_number # remember page number in djvu file
yield page
def treat(self, page) -> None:
"""Process one page."""
old_text = page.text
# Overwrite body of the page with content from djvu
page.body = self._djvu.get_page(page.page_number)
new_text = page.text
if page.exists() and not self.opt.force:
pywikibot.output(
'Page {} already exists, not adding!\n'
'Use -force option to overwrite the output page.'
.format(page))
else:
self.userPut(page, old_text, new_text, summary=self.opt.summary)
def main(*args: str) -> None:
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
index = None
djvu_path = '.' # default djvu file directory
pages = '1-'
options = {}
# Parse command line arguments.
local_args = pywikibot.handle_args(args)
for arg in local_args:
opt, _, value = arg.partition(':')
if opt == '-index':
index = value
elif opt == '-djvu':
djvu_path = value
elif opt == '-pages':
pages = value
elif opt == '-summary':
options['summary'] = value
elif opt in ('-force', '-always'):
options[opt[1:]] = True
else:
pywikibot.output('Unknown argument ' + arg)
# index is mandatory.
if not index:
pywikibot.bot.suggest_help(missing_parameters=['-index'])
return
# If djvu_path is not a file, build djvu_path from dir+index.
djvu_path = os.path.expanduser(djvu_path)
djvu_path = os.path.abspath(djvu_path)
if not os.path.exists(djvu_path):
pywikibot.error('No such file or directory: ' + djvu_path)
return
if os.path.isdir(djvu_path):
djvu_path = os.path.join(djvu_path, index)
# Check the djvu file exists and, if so, create the DjVuFile wrapper.
djvu = DjVuFile(djvu_path)
if not djvu.has_text():
pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
return
# Parse pages param.
pages = pages.split(',')
for i, page_interval in enumerate(pages):
start, sep, end = page_interval.partition('-')
start = int(start or 1)
end = int(end or djvu.number_of_images()) if sep else start
pages[i] = (start, end)
site = pywikibot.Site()
if not site.has_extension('ProofreadPage'):
pywikibot.error('Site {} must have ProofreadPage extension.'
.format(site))
return
index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns)
if not index_page.exists():
raise NoPageError(index)
pywikibot.output('uploading text from {} to {}'
.format(djvu.file, index_page.title(as_link=True)))
bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options)
bot.run()
if __name__ == '__main__':
try:
main()
except Exception:
pywikibot.error('Fatal error:', exc_info=True)
<|fim▁end|> | generator |
<|file_name|>djvutext.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
- path to a file name
- dir where a djvu file name as index is located
optional, by default is current dir '.'
-pages:<start>-<end>,...<start>-<end>,<start>-<end>
Page range to upload;
optional, start=1, end=djvu file number of images.
Page ranges can be specified as:
A-B -> pages A until B
A- -> pages A until number of images
A -> just page A
-B -> pages 1 until B
This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`.
The following options can be set within a settings file which is scripts.ini
by default:
-summary: custom edit summary.
Use quotes if edit summary contains spaces.
-force overwrites existing text
optional, default False
-always do not bother asking to confirm any of the changes.
"""
#
# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
import os.path
from typing import Optional
import pywikibot
from pywikibot import i18n
from pywikibot.bot import SingleSiteBot
from pywikibot.exceptions import NoPageError
from pywikibot.proofreadpage import ProofreadPage
from pywikibot.tools.djvu import DjVuFile
class DjVuTextBot(SingleSiteBot):
"""
A bot that uploads text-layer from djvu files to Page:namespace.
Works only on sites with Proofread Page extension installed.
.. versionchanged:: 7.0
CheckerBot is a ConfigParserBot
"""
update_options = {
'force': False,
'summary': '',
}
def __init__(
self,
djvu,
index,
pages: Optional[tuple] = None,
**kwargs
) -> None:
"""
Initializer.
:param djvu: djvu from where to fetch the text layer
:type djvu: DjVuFile object
:param index: index page in the Index: namespace
:type index: Page object
:param pages: page interval to upload (start, end)
"""
super().__init__(**kwargs)
self._djvu = djvu
self._index = index
self._prefix = self._index.title(with_ns=False)
self._page_ns = self.site._proofread_page_ns.custom_name
if not pages:
self._pages = (1, self._djvu.number_of_images())
else:
self._pages = pages
# Get edit summary message if it's empty.
if not self.opt.summary:
self.opt.summary = i18n.twtranslate(self._index.site,
'djvutext-creating')
def page_number_gen(self):
"""Generate pages numbers from specified page intervals."""
last = 0
for start, end in sorted(self._pages):
start = max(last, start)
last = end + 1
yield from range(start, last)
@property
def generator(self):
"""Generate pages from specified page interval."""
for page_number in self.page_number_gen():
title = '{page_ns}:{prefix}/{number}'.format(
page_ns=self._page_ns,
prefix=self._prefix,
number=page_number)
page = ProofreadPage(self._index.site, title)
page.page_number = page_number # remember page number in djvu file
yield page
def <|fim_middle|>(self, page) -> None:
"""Process one page."""
old_text = page.text
# Overwrite body of the page with content from djvu
page.body = self._djvu.get_page(page.page_number)
new_text = page.text
if page.exists() and not self.opt.force:
pywikibot.output(
'Page {} already exists, not adding!\n'
'Use -force option to overwrite the output page.'
.format(page))
else:
self.userPut(page, old_text, new_text, summary=self.opt.summary)
def main(*args: str) -> None:
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
index = None
djvu_path = '.' # default djvu file directory
pages = '1-'
options = {}
# Parse command line arguments.
local_args = pywikibot.handle_args(args)
for arg in local_args:
opt, _, value = arg.partition(':')
if opt == '-index':
index = value
elif opt == '-djvu':
djvu_path = value
elif opt == '-pages':
pages = value
elif opt == '-summary':
options['summary'] = value
elif opt in ('-force', '-always'):
options[opt[1:]] = True
else:
pywikibot.output('Unknown argument ' + arg)
# index is mandatory.
if not index:
pywikibot.bot.suggest_help(missing_parameters=['-index'])
return
# If djvu_path is not a file, build djvu_path from dir+index.
djvu_path = os.path.expanduser(djvu_path)
djvu_path = os.path.abspath(djvu_path)
if not os.path.exists(djvu_path):
pywikibot.error('No such file or directory: ' + djvu_path)
return
if os.path.isdir(djvu_path):
djvu_path = os.path.join(djvu_path, index)
# Check the djvu file exists and, if so, create the DjVuFile wrapper.
djvu = DjVuFile(djvu_path)
if not djvu.has_text():
pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
return
# Parse pages param.
pages = pages.split(',')
for i, page_interval in enumerate(pages):
start, sep, end = page_interval.partition('-')
start = int(start or 1)
end = int(end or djvu.number_of_images()) if sep else start
pages[i] = (start, end)
site = pywikibot.Site()
if not site.has_extension('ProofreadPage'):
pywikibot.error('Site {} must have ProofreadPage extension.'
.format(site))
return
index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns)
if not index_page.exists():
raise NoPageError(index)
pywikibot.output('uploading text from {} to {}'
.format(djvu.file, index_page.title(as_link=True)))
bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options)
bot.run()
if __name__ == '__main__':
try:
main()
except Exception:
pywikibot.error('Fatal error:', exc_info=True)
<|fim▁end|> | treat |
<|file_name|>djvutext.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
- path to a file name
- dir where a djvu file name as index is located
optional, by default is current dir '.'
-pages:<start>-<end>,...<start>-<end>,<start>-<end>
Page range to upload;
optional, start=1, end=djvu file number of images.
Page ranges can be specified as:
A-B -> pages A until B
A- -> pages A until number of images
A -> just page A
-B -> pages 1 until B
This script is a :py:obj:`ConfigParserBot <pywikibot.bot.ConfigParserBot>`.
The following options can be set within a settings file which is scripts.ini
by default:
-summary: custom edit summary.
Use quotes if edit summary contains spaces.
-force overwrites existing text
optional, default False
-always do not bother asking to confirm any of the changes.
"""
#
# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
import os.path
from typing import Optional
import pywikibot
from pywikibot import i18n
from pywikibot.bot import SingleSiteBot
from pywikibot.exceptions import NoPageError
from pywikibot.proofreadpage import ProofreadPage
from pywikibot.tools.djvu import DjVuFile
class DjVuTextBot(SingleSiteBot):
"""
A bot that uploads text-layer from djvu files to Page:namespace.
Works only on sites with Proofread Page extension installed.
.. versionchanged:: 7.0
CheckerBot is a ConfigParserBot
"""
update_options = {
'force': False,
'summary': '',
}
def __init__(
self,
djvu,
index,
pages: Optional[tuple] = None,
**kwargs
) -> None:
"""
Initializer.
:param djvu: djvu from where to fetch the text layer
:type djvu: DjVuFile object
:param index: index page in the Index: namespace
:type index: Page object
:param pages: page interval to upload (start, end)
"""
super().__init__(**kwargs)
self._djvu = djvu
self._index = index
self._prefix = self._index.title(with_ns=False)
self._page_ns = self.site._proofread_page_ns.custom_name
if not pages:
self._pages = (1, self._djvu.number_of_images())
else:
self._pages = pages
# Get edit summary message if it's empty.
if not self.opt.summary:
self.opt.summary = i18n.twtranslate(self._index.site,
'djvutext-creating')
def page_number_gen(self):
"""Generate pages numbers from specified page intervals."""
last = 0
for start, end in sorted(self._pages):
start = max(last, start)
last = end + 1
yield from range(start, last)
@property
def generator(self):
"""Generate pages from specified page interval."""
for page_number in self.page_number_gen():
title = '{page_ns}:{prefix}/{number}'.format(
page_ns=self._page_ns,
prefix=self._prefix,
number=page_number)
page = ProofreadPage(self._index.site, title)
page.page_number = page_number # remember page number in djvu file
yield page
def treat(self, page) -> None:
"""Process one page."""
old_text = page.text
# Overwrite body of the page with content from djvu
page.body = self._djvu.get_page(page.page_number)
new_text = page.text
if page.exists() and not self.opt.force:
pywikibot.output(
'Page {} already exists, not adding!\n'
'Use -force option to overwrite the output page.'
.format(page))
else:
self.userPut(page, old_text, new_text, summary=self.opt.summary)
def <|fim_middle|>(*args: str) -> None:
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
index = None
djvu_path = '.' # default djvu file directory
pages = '1-'
options = {}
# Parse command line arguments.
local_args = pywikibot.handle_args(args)
for arg in local_args:
opt, _, value = arg.partition(':')
if opt == '-index':
index = value
elif opt == '-djvu':
djvu_path = value
elif opt == '-pages':
pages = value
elif opt == '-summary':
options['summary'] = value
elif opt in ('-force', '-always'):
options[opt[1:]] = True
else:
pywikibot.output('Unknown argument ' + arg)
# index is mandatory.
if not index:
pywikibot.bot.suggest_help(missing_parameters=['-index'])
return
# If djvu_path is not a file, build djvu_path from dir+index.
djvu_path = os.path.expanduser(djvu_path)
djvu_path = os.path.abspath(djvu_path)
if not os.path.exists(djvu_path):
pywikibot.error('No such file or directory: ' + djvu_path)
return
if os.path.isdir(djvu_path):
djvu_path = os.path.join(djvu_path, index)
# Check the djvu file exists and, if so, create the DjVuFile wrapper.
djvu = DjVuFile(djvu_path)
if not djvu.has_text():
pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
return
# Parse pages param.
pages = pages.split(',')
for i, page_interval in enumerate(pages):
start, sep, end = page_interval.partition('-')
start = int(start or 1)
end = int(end or djvu.number_of_images()) if sep else start
pages[i] = (start, end)
site = pywikibot.Site()
if not site.has_extension('ProofreadPage'):
pywikibot.error('Site {} must have ProofreadPage extension.'
.format(site))
return
index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns)
if not index_page.exists():
raise NoPageError(index)
pywikibot.output('uploading text from {} to {}'
.format(djvu.file, index_page.title(as_link=True)))
bot = DjVuTextBot(djvu, index_page, pages=pages, site=site, **options)
bot.run()
if __name__ == '__main__':
try:
main()
except Exception:
pywikibot.error('Fatal error:', exc_info=True)
<|fim▁end|> | main |
<|file_name|>garch.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.
#
# -------------------------------------------------------------
# Autogenerated By : src/main/python/generator/generator.py
# Autogenerated From : scripts/builtin/garch.dml
from typing import Dict, Iterable
from systemds.operator import OperationNode, Matrix, Frame, List, MultiReturn, Scalar
from systemds.script_building.dag import OutputType
from systemds.utils.consts import VALID_INPUT_TYPES
def garch(X: Matrix,
kmax: int,
momentum: float,
start_stepsize: float,
end_stepsize: float,
start_vicinity: float,
end_vicinity: float,
sim_seed: int,
verbose: bool):
"""
:param X: The input Matrix to apply Arima on.
:param kmax: Number of iterations
:param momentum: Momentum for momentum-gradient descent (set to 0 to deactivate)
:param start_stepsize: Initial gradient-descent stepsize
:param end_stepsize: gradient-descent stepsize at end (linear descent)
:param start_vicinity: proportion of randomness of restart-location for gradient descent at beginning
:param end_vicinity: same at end (linear decay)
:param sim_seed: seed for simulation of process on fitted coefficients
:param verbose: verbosity, comments during fitting
:return: 'OperationNode' containing simulated garch(1,1) process on fitted coefficients & variances of simulated fitted process & constant term of fitted process & 1-st arch-coefficient of fitted process & 1-st garch-coefficient of fitted process & drawbacks: slow convergence of optimization (sort of simulated annealing/gradient descent)
"""
params_dict = {'X': X, 'kmax': kmax, 'momentum': momentum, 'start_stepsize': start_stepsize, 'end_stepsize': end_stepsize, 'start_vicinity': start_vicinity, 'end_vicinity': end_vicinity, 'sim_seed': sim_seed, 'verbose': verbose}
vX_0 = Matrix(X.sds_context, '')
vX_1 = Matrix(X.sds_context, '')
vX_2 = Scalar(X.sds_context, '')
vX_3 = Scalar(X.sds_context, '')
vX_4 = Scalar(X.sds_context, '')
output_nodes = [vX_0, vX_1, vX_2, vX_3, vX_4, ]
op = MultiReturn(X.sds_context, 'garch', output_nodes, named_input_nodes=params_dict)
vX_0._unnamed_input_nodes = [op]
vX_1._unnamed_input_nodes = [op]<|fim▁hole|> vX_3._unnamed_input_nodes = [op]
vX_4._unnamed_input_nodes = [op]
return op<|fim▁end|> | vX_2._unnamed_input_nodes = [op] |
<|file_name|>garch.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.
#
# -------------------------------------------------------------
# Autogenerated By : src/main/python/generator/generator.py
# Autogenerated From : scripts/builtin/garch.dml
from typing import Dict, Iterable
from systemds.operator import OperationNode, Matrix, Frame, List, MultiReturn, Scalar
from systemds.script_building.dag import OutputType
from systemds.utils.consts import VALID_INPUT_TYPES
def garch(X: Matrix,
kmax: int,
momentum: float,
start_stepsize: float,
end_stepsize: float,
start_vicinity: float,
end_vicinity: float,
sim_seed: int,
verbose: bool):
<|fim_middle|>
<|fim▁end|> | """
:param X: The input Matrix to apply Arima on.
:param kmax: Number of iterations
:param momentum: Momentum for momentum-gradient descent (set to 0 to deactivate)
:param start_stepsize: Initial gradient-descent stepsize
:param end_stepsize: gradient-descent stepsize at end (linear descent)
:param start_vicinity: proportion of randomness of restart-location for gradient descent at beginning
:param end_vicinity: same at end (linear decay)
:param sim_seed: seed for simulation of process on fitted coefficients
:param verbose: verbosity, comments during fitting
:return: 'OperationNode' containing simulated garch(1,1) process on fitted coefficients & variances of simulated fitted process & constant term of fitted process & 1-st arch-coefficient of fitted process & 1-st garch-coefficient of fitted process & drawbacks: slow convergence of optimization (sort of simulated annealing/gradient descent)
"""
params_dict = {'X': X, 'kmax': kmax, 'momentum': momentum, 'start_stepsize': start_stepsize, 'end_stepsize': end_stepsize, 'start_vicinity': start_vicinity, 'end_vicinity': end_vicinity, 'sim_seed': sim_seed, 'verbose': verbose}
vX_0 = Matrix(X.sds_context, '')
vX_1 = Matrix(X.sds_context, '')
vX_2 = Scalar(X.sds_context, '')
vX_3 = Scalar(X.sds_context, '')
vX_4 = Scalar(X.sds_context, '')
output_nodes = [vX_0, vX_1, vX_2, vX_3, vX_4, ]
op = MultiReturn(X.sds_context, 'garch', output_nodes, named_input_nodes=params_dict)
vX_0._unnamed_input_nodes = [op]
vX_1._unnamed_input_nodes = [op]
vX_2._unnamed_input_nodes = [op]
vX_3._unnamed_input_nodes = [op]
vX_4._unnamed_input_nodes = [op]
return op |
<|file_name|>garch.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.
#
# -------------------------------------------------------------
# Autogenerated By : src/main/python/generator/generator.py
# Autogenerated From : scripts/builtin/garch.dml
from typing import Dict, Iterable
from systemds.operator import OperationNode, Matrix, Frame, List, MultiReturn, Scalar
from systemds.script_building.dag import OutputType
from systemds.utils.consts import VALID_INPUT_TYPES
def <|fim_middle|>(X: Matrix,
kmax: int,
momentum: float,
start_stepsize: float,
end_stepsize: float,
start_vicinity: float,
end_vicinity: float,
sim_seed: int,
verbose: bool):
"""
:param X: The input Matrix to apply Arima on.
:param kmax: Number of iterations
:param momentum: Momentum for momentum-gradient descent (set to 0 to deactivate)
:param start_stepsize: Initial gradient-descent stepsize
:param end_stepsize: gradient-descent stepsize at end (linear descent)
:param start_vicinity: proportion of randomness of restart-location for gradient descent at beginning
:param end_vicinity: same at end (linear decay)
:param sim_seed: seed for simulation of process on fitted coefficients
:param verbose: verbosity, comments during fitting
:return: 'OperationNode' containing simulated garch(1,1) process on fitted coefficients & variances of simulated fitted process & constant term of fitted process & 1-st arch-coefficient of fitted process & 1-st garch-coefficient of fitted process & drawbacks: slow convergence of optimization (sort of simulated annealing/gradient descent)
"""
params_dict = {'X': X, 'kmax': kmax, 'momentum': momentum, 'start_stepsize': start_stepsize, 'end_stepsize': end_stepsize, 'start_vicinity': start_vicinity, 'end_vicinity': end_vicinity, 'sim_seed': sim_seed, 'verbose': verbose}
vX_0 = Matrix(X.sds_context, '')
vX_1 = Matrix(X.sds_context, '')
vX_2 = Scalar(X.sds_context, '')
vX_3 = Scalar(X.sds_context, '')
vX_4 = Scalar(X.sds_context, '')
output_nodes = [vX_0, vX_1, vX_2, vX_3, vX_4, ]
op = MultiReturn(X.sds_context, 'garch', output_nodes, named_input_nodes=params_dict)
vX_0._unnamed_input_nodes = [op]
vX_1._unnamed_input_nodes = [op]
vX_2._unnamed_input_nodes = [op]
vX_3._unnamed_input_nodes = [op]
vX_4._unnamed_input_nodes = [op]
return op
<|fim▁end|> | garch |
<|file_name|>187.py<|end_file_name|><|fim▁begin|>from math import log
def num_prime_factors(upper_limit):
"""
Create an array whose entries are the number of not necessarily distinct
prime factors of the index. The upper bound is the first number not
included.
"""
factor_count = [0] * upper_limit<|fim▁hole|> prime_power = prime
for exponent in range(int(log(upper_limit, prime))):
for hit in range(prime_power, upper_limit, prime_power):
factor_count[hit] += 1
prime_power *= prime
while True:
prime += 1
if prime >= upper_limit:
return factor_count
if factor_count[prime] == 0: break
print(sum(1 if n == 2 else 0 for n in num_prime_factors(100000000)))<|fim▁end|> | prime = 2 #start with the first prime, which is 2
while True: |
<|file_name|>187.py<|end_file_name|><|fim▁begin|>from math import log
def num_prime_factors(upper_limit):
<|fim_middle|>
print(sum(1 if n == 2 else 0 for n in num_prime_factors(100000000)))
<|fim▁end|> | """
Create an array whose entries are the number of not necessarily distinct
prime factors of the index. The upper bound is the first number not
included.
"""
factor_count = [0] * upper_limit
prime = 2 #start with the first prime, which is 2
while True:
prime_power = prime
for exponent in range(int(log(upper_limit, prime))):
for hit in range(prime_power, upper_limit, prime_power):
factor_count[hit] += 1
prime_power *= prime
while True:
prime += 1
if prime >= upper_limit:
return factor_count
if factor_count[prime] == 0: break |
<|file_name|>187.py<|end_file_name|><|fim▁begin|>from math import log
def num_prime_factors(upper_limit):
"""
Create an array whose entries are the number of not necessarily distinct
prime factors of the index. The upper bound is the first number not
included.
"""
factor_count = [0] * upper_limit
prime = 2 #start with the first prime, which is 2
while True:
prime_power = prime
for exponent in range(int(log(upper_limit, prime))):
for hit in range(prime_power, upper_limit, prime_power):
factor_count[hit] += 1
prime_power *= prime
while True:
prime += 1
if prime >= upper_limit:
<|fim_middle|>
if factor_count[prime] == 0: break
print(sum(1 if n == 2 else 0 for n in num_prime_factors(100000000)))
<|fim▁end|> | return factor_count |
<|file_name|>187.py<|end_file_name|><|fim▁begin|>from math import log
def num_prime_factors(upper_limit):
"""
Create an array whose entries are the number of not necessarily distinct
prime factors of the index. The upper bound is the first number not
included.
"""
factor_count = [0] * upper_limit
prime = 2 #start with the first prime, which is 2
while True:
prime_power = prime
for exponent in range(int(log(upper_limit, prime))):
for hit in range(prime_power, upper_limit, prime_power):
factor_count[hit] += 1
prime_power *= prime
while True:
prime += 1
if prime >= upper_limit:
return factor_count
if factor_count[prime] == 0: <|fim_middle|>
print(sum(1 if n == 2 else 0 for n in num_prime_factors(100000000)))
<|fim▁end|> | break |
<|file_name|>187.py<|end_file_name|><|fim▁begin|>from math import log
def <|fim_middle|>(upper_limit):
"""
Create an array whose entries are the number of not necessarily distinct
prime factors of the index. The upper bound is the first number not
included.
"""
factor_count = [0] * upper_limit
prime = 2 #start with the first prime, which is 2
while True:
prime_power = prime
for exponent in range(int(log(upper_limit, prime))):
for hit in range(prime_power, upper_limit, prime_power):
factor_count[hit] += 1
prime_power *= prime
while True:
prime += 1
if prime >= upper_limit:
return factor_count
if factor_count[prime] == 0: break
print(sum(1 if n == 2 else 0 for n in num_prime_factors(100000000)))
<|fim▁end|> | num_prime_factors |
<|file_name|>session_recording.py<|end_file_name|><|fim▁begin|># Source Generated with Decompyle++
# File: session_recording.pyc (Python 2.5)
from __future__ import absolute_import
from pushbase.session_recording_component import FixedLengthSessionRecordingComponent
class SessionRecordingComponent(FixedLengthSessionRecordingComponent):
def __init__(self, *a, **k):
super(SessionRecordingComponent, self).__init__(*a, **a)
self.set_trigger_recording_on_release(not (self._record_button.is_pressed))
def set_trigger_recording_on_release(self, trigger_recording):
self._should_trigger_recording = trigger_recording
def _on_record_button_pressed(self):
pass
def _on_record_button_released(self):<|fim▁hole|> self._should_trigger_recording = True<|fim▁end|> | if self._should_trigger_recording:
self._trigger_recording()
|
<|file_name|>session_recording.py<|end_file_name|><|fim▁begin|># Source Generated with Decompyle++
# File: session_recording.pyc (Python 2.5)
from __future__ import absolute_import
from pushbase.session_recording_component import FixedLengthSessionRecordingComponent
class SessionRecordingComponent(FixedLengthSessionRecordingComponent):
<|fim_middle|>
<|fim▁end|> | def __init__(self, *a, **k):
super(SessionRecordingComponent, self).__init__(*a, **a)
self.set_trigger_recording_on_release(not (self._record_button.is_pressed))
def set_trigger_recording_on_release(self, trigger_recording):
self._should_trigger_recording = trigger_recording
def _on_record_button_pressed(self):
pass
def _on_record_button_released(self):
if self._should_trigger_recording:
self._trigger_recording()
self._should_trigger_recording = True |
<|file_name|>session_recording.py<|end_file_name|><|fim▁begin|># Source Generated with Decompyle++
# File: session_recording.pyc (Python 2.5)
from __future__ import absolute_import
from pushbase.session_recording_component import FixedLengthSessionRecordingComponent
class SessionRecordingComponent(FixedLengthSessionRecordingComponent):
def __init__(self, *a, **k):
<|fim_middle|>
def set_trigger_recording_on_release(self, trigger_recording):
self._should_trigger_recording = trigger_recording
def _on_record_button_pressed(self):
pass
def _on_record_button_released(self):
if self._should_trigger_recording:
self._trigger_recording()
self._should_trigger_recording = True
<|fim▁end|> | super(SessionRecordingComponent, self).__init__(*a, **a)
self.set_trigger_recording_on_release(not (self._record_button.is_pressed)) |
<|file_name|>session_recording.py<|end_file_name|><|fim▁begin|># Source Generated with Decompyle++
# File: session_recording.pyc (Python 2.5)
from __future__ import absolute_import
from pushbase.session_recording_component import FixedLengthSessionRecordingComponent
class SessionRecordingComponent(FixedLengthSessionRecordingComponent):
def __init__(self, *a, **k):
super(SessionRecordingComponent, self).__init__(*a, **a)
self.set_trigger_recording_on_release(not (self._record_button.is_pressed))
def set_trigger_recording_on_release(self, trigger_recording):
<|fim_middle|>
def _on_record_button_pressed(self):
pass
def _on_record_button_released(self):
if self._should_trigger_recording:
self._trigger_recording()
self._should_trigger_recording = True
<|fim▁end|> | self._should_trigger_recording = trigger_recording |
<|file_name|>session_recording.py<|end_file_name|><|fim▁begin|># Source Generated with Decompyle++
# File: session_recording.pyc (Python 2.5)
from __future__ import absolute_import
from pushbase.session_recording_component import FixedLengthSessionRecordingComponent
class SessionRecordingComponent(FixedLengthSessionRecordingComponent):
def __init__(self, *a, **k):
super(SessionRecordingComponent, self).__init__(*a, **a)
self.set_trigger_recording_on_release(not (self._record_button.is_pressed))
def set_trigger_recording_on_release(self, trigger_recording):
self._should_trigger_recording = trigger_recording
def _on_record_button_pressed(self):
<|fim_middle|>
def _on_record_button_released(self):
if self._should_trigger_recording:
self._trigger_recording()
self._should_trigger_recording = True
<|fim▁end|> | pass |
<|file_name|>session_recording.py<|end_file_name|><|fim▁begin|># Source Generated with Decompyle++
# File: session_recording.pyc (Python 2.5)
from __future__ import absolute_import
from pushbase.session_recording_component import FixedLengthSessionRecordingComponent
class SessionRecordingComponent(FixedLengthSessionRecordingComponent):
def __init__(self, *a, **k):
super(SessionRecordingComponent, self).__init__(*a, **a)
self.set_trigger_recording_on_release(not (self._record_button.is_pressed))
def set_trigger_recording_on_release(self, trigger_recording):
self._should_trigger_recording = trigger_recording
def _on_record_button_pressed(self):
pass
def _on_record_button_released(self):
<|fim_middle|>
<|fim▁end|> | if self._should_trigger_recording:
self._trigger_recording()
self._should_trigger_recording = True |
<|file_name|>session_recording.py<|end_file_name|><|fim▁begin|># Source Generated with Decompyle++
# File: session_recording.pyc (Python 2.5)
from __future__ import absolute_import
from pushbase.session_recording_component import FixedLengthSessionRecordingComponent
class SessionRecordingComponent(FixedLengthSessionRecordingComponent):
def __init__(self, *a, **k):
super(SessionRecordingComponent, self).__init__(*a, **a)
self.set_trigger_recording_on_release(not (self._record_button.is_pressed))
def set_trigger_recording_on_release(self, trigger_recording):
self._should_trigger_recording = trigger_recording
def _on_record_button_pressed(self):
pass
def _on_record_button_released(self):
if self._should_trigger_recording:
<|fim_middle|>
self._should_trigger_recording = True
<|fim▁end|> | self._trigger_recording() |
<|file_name|>session_recording.py<|end_file_name|><|fim▁begin|># Source Generated with Decompyle++
# File: session_recording.pyc (Python 2.5)
from __future__ import absolute_import
from pushbase.session_recording_component import FixedLengthSessionRecordingComponent
class SessionRecordingComponent(FixedLengthSessionRecordingComponent):
def <|fim_middle|>(self, *a, **k):
super(SessionRecordingComponent, self).__init__(*a, **a)
self.set_trigger_recording_on_release(not (self._record_button.is_pressed))
def set_trigger_recording_on_release(self, trigger_recording):
self._should_trigger_recording = trigger_recording
def _on_record_button_pressed(self):
pass
def _on_record_button_released(self):
if self._should_trigger_recording:
self._trigger_recording()
self._should_trigger_recording = True
<|fim▁end|> | __init__ |
<|file_name|>session_recording.py<|end_file_name|><|fim▁begin|># Source Generated with Decompyle++
# File: session_recording.pyc (Python 2.5)
from __future__ import absolute_import
from pushbase.session_recording_component import FixedLengthSessionRecordingComponent
class SessionRecordingComponent(FixedLengthSessionRecordingComponent):
def __init__(self, *a, **k):
super(SessionRecordingComponent, self).__init__(*a, **a)
self.set_trigger_recording_on_release(not (self._record_button.is_pressed))
def <|fim_middle|>(self, trigger_recording):
self._should_trigger_recording = trigger_recording
def _on_record_button_pressed(self):
pass
def _on_record_button_released(self):
if self._should_trigger_recording:
self._trigger_recording()
self._should_trigger_recording = True
<|fim▁end|> | set_trigger_recording_on_release |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.